项目作者: alokyadav777

项目描述 :
Dog Breed classifier using Transfer learning
高级语言: Jupyter Notebook
项目地址: git://github.com/alokyadav777/Dog_Breed_Classifier.git
创建时间: 2018-08-19T11:33:18Z
项目社区:https://github.com/alokyadav777/Dog_Breed_Classifier

开源协议:MIT License

下载


Dog_Breed_Classifier

A dog breed classifier is to classify various breed of dog, classification of different object is a little easier task but classifying similar type of object is much more intresting and difficult.we created a system using google’s inception model and we trained for our custom dataset. result is 99% accuracy with Label.

This notebook will walk you step by step through the process of using a pre-trained model inception with our own custom data to classfy various bredd of dog in an image. Make sure to follow the installation instructions before you start.

Imports

  1. import numpy as np
  2. import os
  3. import six.moves.urllib as urllib
  4. import sys
  5. import tarfile
  6. import tensorflow as tf
  7. import zipfile
  8. from collections import defaultdict
  9. from io import StringIO
  10. from matplotlib import pyplot as plt
  11. from PIL import Image
  12. # This is needed since the notebook is stored in the object_detection folder.
  13. sys.path.append("..")
  14. from object_detection.utils import ops as utils_ops

Env setup

  1. # This is needed to display the images.
  2. %matplotlib inline

Object detection imports

Here are the imports from the object detection module.

  1. import label_map_util
  2. import visualization_utils as vis_util

Model preparation

Variables

Any model exported using the export_inference_graph.py tool can be loaded here simply by changing PATH_TO_FROZEN_GRAPH to point to a new .pb file.

By default we use an “SSD with Mobilenet” model here. See the detection model zoo for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

  1. # What model to download.
  2. MODEL_NAME = 'dog_breed_inference_graph'
  3. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  4. PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
  5. # List of the strings that is used to add correct label for each box.
  6. PATH_TO_LABELS = os.path.join('dog_breed_inference_graph', 'dog_breed_classification.pbtxt')
  7. NUM_CLASSES = 8

Download Model

Load a (frozen) Tensorflow model into memory.

  1. detection_graph = tf.Graph()
  2. with detection_graph.as_default():
  3. od_graph_def = tf.GraphDef()
  4. with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
  5. serialized_graph = fid.read()
  6. od_graph_def.ParseFromString(serialized_graph)
  7. tf.import_graph_def(od_graph_def, name='')

Loading label map

Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

  1. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  2. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  3. category_index = label_map_util.create_category_index(categories)

Helper code

  1. def load_image_into_numpy_array(image):
  2. (im_width, im_height) = image.size
  3. return np.array(image.getdata()).reshape(
  4. (im_height, im_width, 3)).astype(np.uint8)

Detection

  1. # For the sake of simplicity we will use only 2 images:
  2. # image1.jpg
  3. # image2.jpg
  4. # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
  5. PATH_TO_TEST_IMAGES_DIR = 'test_images'
  6. TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 8) ]
  7. # Size, in inches, of the output images.
  8. IMAGE_SIZE = (12,8)
  1. def run_inference_for_single_image(image, graph):
  2. with graph.as_default():
  3. with tf.Session() as sess:
  4. # Get handles to input and output tensors
  5. ops = tf.get_default_graph().get_operations()
  6. all_tensor_names = {output.name for op in ops for output in op.outputs}
  7. tensor_dict = {}
  8. for key in [
  9. 'num_detections', 'detection_boxes', 'detection_scores',
  10. 'detection_classes', 'detection_masks'
  11. ]:
  12. tensor_name = key + ':0'
  13. if tensor_name in all_tensor_names:
  14. tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
  15. tensor_name)
  16. if 'detection_masks' in tensor_dict:
  17. # The following processing is only for single image
  18. detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
  19. detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
  20. # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
  21. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
  22. detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
  23. detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
  24. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
  25. detection_masks, detection_boxes, image.shape[0], image.shape[1])
  26. detection_masks_reframed = tf.cast(
  27. tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  28. # Follow the convention by adding back the batch dimension
  29. tensor_dict['detection_masks'] = tf.expand_dims(
  30. detection_masks_reframed, 0)
  31. image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
  32. # Run inference
  33. output_dict = sess.run(tensor_dict,
  34. feed_dict={image_tensor: np.expand_dims(image, 0)})
  35. # all outputs are float32 numpy arrays, so convert types as appropriate
  36. output_dict['num_detections'] = int(output_dict['num_detections'][0])
  37. output_dict['detection_classes'] = output_dict[
  38. 'detection_classes'][0].astype(np.uint8)
  39. output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  40. output_dict['detection_scores'] = output_dict['detection_scores'][0]
  41. if 'detection_masks' in output_dict:
  42. output_dict['detection_masks'] = output_dict['detection_masks'][0]
  43. return output_dict
  1. for image_path in TEST_IMAGE_PATHS:
  2. image = Image.open(image_path)
  3. # the array based representation of the image will be used later in order to prepare the
  4. # result image with boxes and labels on it.
  5. image_np = load_image_into_numpy_array(image)
  6. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  7. image_np_expanded = np.expand_dims(image_np, axis=0)
  8. # Actual detection.
  9. output_dict = run_inference_for_single_image(image_np, detection_graph)
  10. # Visualization of the results of a detection.
  11. vis_util.visualize_boxes_and_labels_on_image_array(
  12. image_np,
  13. output_dict['detection_boxes'],
  14. output_dict['detection_classes'],
  15. output_dict['detection_scores'],
  16. category_index,
  17. instance_masks=output_dict.get('detection_masks'),
  18. use_normalized_coordinates=True,
  19. line_thickness=4)
  20. plt.figure(figsize=IMAGE_SIZE)
  21. plt.imshow(image_np)

alt text

alt text

alt text