|
| 1 | +import numpy as np |
| 2 | +import argparse |
| 3 | +import os |
| 4 | +import tensorflow as tf |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import pathlib |
| 7 | + |
| 8 | +from object_detection.utils import ops as utils_ops |
| 9 | +from object_detection.utils import label_map_util |
| 10 | +from object_detection.utils import visualization_utils as vis_util |
| 11 | + |
| 12 | +# patch tf1 into `utils.ops` |
| 13 | +utils_ops.tf = tf.compat.v1 |
| 14 | + |
| 15 | +# Patch the location of gfile |
| 16 | +tf.gfile = tf.io.gfile |
| 17 | + |
| 18 | + |
| 19 | +def load_model(model_path): |
| 20 | + model = tf.saved_model.load(model_path) |
| 21 | + return model |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +def load_image_into_numpy_array(path): |
| 26 | + """Load an image from file into a numpy array. |
| 27 | + |
| 28 | + Puts image into numpy array to feed into tensorflow graph. |
| 29 | + Note that by convention we put it into a numpy array with shape |
| 30 | + (height, width, channels), where channels=3 for RGB. |
| 31 | + |
| 32 | + Args: |
| 33 | + path: a file path (this can be local or on colossus) |
| 34 | + |
| 35 | + Returns: |
| 36 | + uint8 numpy array with shape (img_height, img_width, 3) |
| 37 | + """ |
| 38 | + img_data = tf.io.gfile.GFile(path, 'rb').read() |
| 39 | + image = Image.open(BytesIO(img_data)) |
| 40 | + (im_width, im_height) = image.size |
| 41 | + return np.array(image.getdata()).reshape( |
| 42 | + (im_height, im_width, 3)).astype(np.uint8) |
| 43 | + |
| 44 | + |
| 45 | +def run_inference_for_single_image(model, image): |
| 46 | + # The input needs to be a tensor, convert it using `tf.convert_to_tensor`. |
| 47 | + input_tensor = tf.convert_to_tensor(image) |
| 48 | + # The model expects a batch of images, so add an axis with `tf.newaxis`. |
| 49 | + input_tensor = input_tensor[tf.newaxis,...] |
| 50 | + |
| 51 | + # Run inference |
| 52 | + output_dict = model(input_tensor) |
| 53 | + |
| 54 | + # All outputs are batches tensors. |
| 55 | + # Convert to numpy arrays, and take index [0] to remove the batch dimension. |
| 56 | + # We're only interested in the first num_detections. |
| 57 | + num_detections = int(output_dict.pop('num_detections')) |
| 58 | + output_dict = {key: value[0, :num_detections].numpy() |
| 59 | + for key, value in output_dict.items()} |
| 60 | + output_dict['num_detections'] = num_detections |
| 61 | + |
| 62 | + # detection_classes should be ints. |
| 63 | + output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64) |
| 64 | + |
| 65 | + # Handle models with masks: |
| 66 | + if 'detection_masks' in output_dict: |
| 67 | + # Reframe the the bbox mask to the image size. |
| 68 | + detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( |
| 69 | + output_dict['detection_masks'], output_dict['detection_boxes'], |
| 70 | + image.shape[0], image.shape[1]) |
| 71 | + detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5, tf.uint8) |
| 72 | + output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy() |
| 73 | + |
| 74 | + return output_dict |
| 75 | + |
| 76 | + |
| 77 | +def run_inference(model, category_index, image_path): |
| 78 | + if os.path.isdir(image_path): |
| 79 | + image_paths = [] |
| 80 | + for file_extension in ('*.png', '*jpg'): |
| 81 | + image_paths.extend(glob.glob(os.path.join(image_path, file_extension))) |
| 82 | + |
| 83 | + for i_path in image_paths: |
| 84 | + image_np = load_image_into_numpy_array(i_path) |
| 85 | + # Actual detection. |
| 86 | + output_dict = run_inference_for_single_image(model, image_np) |
| 87 | + # Visualization of the results of a detection. |
| 88 | + vis_util.visualize_boxes_and_labels_on_image_array( |
| 89 | + image_np, |
| 90 | + output_dict['detection_boxes'], |
| 91 | + output_dict['detection_classes'], |
| 92 | + output_dict['detection_scores'], |
| 93 | + category_index, |
| 94 | + instance_masks=output_dict.get('detection_masks_reframed', None), |
| 95 | + use_normalized_coordinates=True, |
| 96 | + line_thickness=8) |
| 97 | + plt.imshow(image_np) |
| 98 | + plt.show() |
| 99 | + elif |
| 100 | + image_np = load_image_into_numpy_array(image_path) |
| 101 | + # Actual detection. |
| 102 | + output_dict = run_inference_for_single_image(model, image_np) |
| 103 | + # Visualization of the results of a detection. |
| 104 | + vis_util.visualize_boxes_and_labels_on_image_array( |
| 105 | + image_np, |
| 106 | + output_dict['detection_boxes'], |
| 107 | + output_dict['detection_classes'], |
| 108 | + output_dict['detection_scores'], |
| 109 | + category_index, |
| 110 | + instance_masks=output_dict.get('detection_masks_reframed', None), |
| 111 | + use_normalized_coordinates=True, |
| 112 | + line_thickness=8) |
| 113 | + plt.imshow(image_np) |
| 114 | + plt.show() |
| 115 | + |
| 116 | + |
| 117 | +if __name__ == '__main__': |
| 118 | + parser = argparse.ArgumentParser(description='Detect objects inside webcam videostream') |
| 119 | + parser.add_argument('-m', '--model', type=str, required=True, help='Model Path') |
| 120 | + parser.add_argument('-l', '--labelmap', type=str, required=True, help='Path to Labelmap') |
| 121 | + parser.add_argument('-i', '--image_path', type=str, required=True, help='Path to image (or folder)') |
| 122 | + args = parser.parse_args() |
| 123 | + |
| 124 | + detection_model = load_model(args.model) |
| 125 | + category_index = label_map_util.create_category_index_from_labelmap(args.labelmap, use_display_name=True) |
| 126 | + |
| 127 | + run_inference(detection_model, category_index, args.image_path) |
0 commit comments