|
| 1 | +from object_detection.utils import visualization_utils as vis_util |
| 2 | +from object_detection.utils import label_map_util |
| 3 | +from object_detection.utils import ops as utils_ops |
| 4 | +import numpy as np |
| 5 | +import os |
| 6 | +import six.moves.urllib as urllib |
| 7 | +import sys |
| 8 | +import tarfile |
| 9 | +import tensorflow as tf |
| 10 | +import zipfile |
| 11 | + |
| 12 | +from collections import defaultdict |
| 13 | +from io import StringIO |
| 14 | +from matplotlib import pyplot as plt |
| 15 | +from PIL import Image |
| 16 | +import os |
| 17 | +import glob |
| 18 | + |
| 19 | +# Path to frozen detection graph. This is the actual model that is used for the object detection. |
| 20 | +PATH_TO_CKPT = './graphs/frozen_inference_graph.pb' |
| 21 | + |
| 22 | +# List of the strings that is used to add correct label for each box. |
| 23 | +PATH_TO_LABELS = './graphs/label_map.pbtxt' |
| 24 | + |
| 25 | +# Path to the images you want to infer |
| 26 | +PATH_TO_TEST_IMAGES_DIR = './images' |
| 27 | + |
| 28 | +assert os.path.isfile('./graphs/frozen_inference_graph.pb') |
| 29 | +assert os.path.isfile(PATH_TO_LABELS) |
| 30 | + |
| 31 | +TEST_IMAGE_PATHS = glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR, "*.*")) |
| 32 | +assert len(TEST_IMAGE_PATHS) > 0, 'No image found in `{}`.'.format( |
| 33 | + PATH_TO_TEST_IMAGES_DIR) |
| 34 | + |
| 35 | +try: |
| 36 | + |
| 37 | + detection_graph = tf.Graph() |
| 38 | + with detection_graph.as_default(): |
| 39 | + od_graph_def = tf.GraphDef() |
| 40 | + with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: |
| 41 | + serialized_graph = fid.read() |
| 42 | + od_graph_def.ParseFromString(serialized_graph) |
| 43 | + tf.import_graph_def(od_graph_def, name='') |
| 44 | + |
| 45 | + label_map = label_map_util.load_labelmap(PATH_TO_LABELS) |
| 46 | + categories = label_map_util.convert_label_map_to_categories( |
| 47 | + label_map, max_num_classes=36, use_display_name=True) |
| 48 | + category_index = label_map_util.create_category_index(categories) |
| 49 | + |
| 50 | + def load_image_into_numpy_array(image): |
| 51 | + (im_width, im_height) = image.size |
| 52 | + return np.array(image.getdata()).reshape( |
| 53 | + (im_height, im_width, 3)).astype(np.uint8) |
| 54 | + |
| 55 | + def get_files_on_directory(path): |
| 56 | + directory = os.path.basename(path) |
| 57 | + file_list = os.listdir(directory) |
| 58 | + return file_list |
| 59 | + |
| 60 | + def run_inference_for_single_image(image, graph): |
| 61 | + with graph.as_default(): |
| 62 | + with tf.Session() as sess: |
| 63 | + # Get handles to input and output tensors |
| 64 | + ops = tf.get_default_graph().get_operations() |
| 65 | + all_tensor_names = { |
| 66 | + output.name for op in ops for output in op.outputs} |
| 67 | + tensor_dict = {} |
| 68 | + for key in [ |
| 69 | + 'num_detections', 'detection_boxes', 'detection_scores', |
| 70 | + 'detection_classes', 'detection_masks' |
| 71 | + ]: |
| 72 | + tensor_name = key + ':0' |
| 73 | + if tensor_name in all_tensor_names: |
| 74 | + tensor_dict[key] = tf.get_default_graph().get_tensor_by_name( |
| 75 | + tensor_name) |
| 76 | + if 'detection_masks' in tensor_dict: |
| 77 | + # The following processing is only for single image |
| 78 | + detection_boxes = tf.squeeze( |
| 79 | + tensor_dict['detection_boxes'], [0]) |
| 80 | + detection_masks = tf.squeeze( |
| 81 | + tensor_dict['detection_masks'], [0]) |
| 82 | + # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size. |
| 83 | + real_num_detection = tf.cast( |
| 84 | + tensor_dict['num_detections'][0], tf.int32) |
| 85 | + detection_boxes = tf.slice(detection_boxes, [0, 0], [ |
| 86 | + real_num_detection, -1]) |
| 87 | + detection_masks = tf.slice(detection_masks, [0, 0, 0], [ |
| 88 | + real_num_detection, -1, -1]) |
| 89 | + detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( |
| 90 | + detection_masks, detection_boxes, image.shape[0], image.shape[1]) |
| 91 | + detection_masks_reframed = tf.cast( |
| 92 | + tf.greater(detection_masks_reframed, 0.5), tf.uint8) |
| 93 | + # Follow the convention by adding back the batch dimension |
| 94 | + tensor_dict['detection_masks'] = tf.expand_dims( |
| 95 | + detection_masks_reframed, 0) |
| 96 | + image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') |
| 97 | + |
| 98 | + # Run inference |
| 99 | + output_dict = sess.run(tensor_dict, |
| 100 | + feed_dict={image_tensor: np.expand_dims(image, 0)}) |
| 101 | + |
| 102 | + # all outputs are float32 numpy arrays, so convert types as appropriate |
| 103 | + output_dict['num_detections'] = int( |
| 104 | + output_dict['num_detections'][0]) |
| 105 | + output_dict['detection_classes'] = output_dict[ |
| 106 | + 'detection_classes'][0].astype(np.uint8) |
| 107 | + output_dict['detection_boxes'] = output_dict['detection_boxes'][0] |
| 108 | + output_dict['detection_scores'] = output_dict['detection_scores'][0] |
| 109 | + if 'detection_masks' in output_dict: |
| 110 | + output_dict['detection_masks'] = output_dict['detection_masks'][0] |
| 111 | + return output_dict |
| 112 | + |
| 113 | + count = 1 |
| 114 | + for image_path in TEST_IMAGE_PATHS: |
| 115 | + image = Image.open(image_path) |
| 116 | + print(image_path) |
| 117 | + |
| 118 | + |
| 119 | + if '.jpg' not in image_path: |
| 120 | + continue |
| 121 | + if sys.platform == 'win32': |
| 122 | + image_name = image_path.split('\\')[1].split('.')[0] |
| 123 | + else: |
| 124 | + image_name = image_path.split('/')[2].split('.')[0] |
| 125 | + |
| 126 | + im_width, im_height = image.size |
| 127 | + |
| 128 | + im_width_inche = im_width // 77 |
| 129 | + im_height_inche = im_height // 77 #redimensioning the image resolution |
| 130 | + |
| 131 | + IMAGE_SIZE = (im_width_inche, im_height_inche) |
| 132 | + |
| 133 | + # the array based representation of the image will be used later in order to prepare the |
| 134 | + # result image with boxes and labels on it. |
| 135 | + image_np = load_image_into_numpy_array(image) |
| 136 | + # Expand dimensions since the model expects images to have e:[1 shap, None, None, 3] |
| 137 | + image_np_expanded = np.expand_dims(image_np, axis=0) |
| 138 | + # Actual detection. |
| 139 | + output_dict = run_inference_for_single_image(image_np, detection_graph) |
| 140 | + |
| 141 | + # Visualization of the results of a detection. |
| 142 | + vis_util.visualize_boxes_and_labels_on_image_array( |
| 143 | + image_np, |
| 144 | + output_dict['detection_boxes'], |
| 145 | + output_dict['detection_classes'], |
| 146 | + output_dict['detection_scores'], |
| 147 | + category_index, |
| 148 | + instance_masks=output_dict.get('detection_masks'), |
| 149 | + use_normalized_coordinates=True, |
| 150 | + line_thickness=10, |
| 151 | + file_name=image_name |
| 152 | + ) |
| 153 | + |
| 154 | + plt.figure(figsize=IMAGE_SIZE) |
| 155 | + plt.axis('off') |
| 156 | + plt.imshow(image_np) |
| 157 | + |
| 158 | + plt.savefig('./results/image_' + image_name + '.jpg', bbox_inches='tight') |
| 159 | + count += 1 |
| 160 | + |
| 161 | +except Exception as error: |
| 162 | + print(error) |
0 commit comments