|
| 1 | +import numpy as np |
| 2 | +import argparse |
| 3 | +import tensorflow as tf |
| 4 | +import cv2 |
| 5 | +import pathlib |
| 6 | +import os |
| 7 | +import pandas as pd |
| 8 | +from PIL import Image |
| 9 | +import datetime |
| 10 | + |
| 11 | +from object_detection.utils import ops as utils_ops |
| 12 | +from object_detection.utils import label_map_util |
| 13 | +from object_detection.utils import visualization_utils as vis_util |
| 14 | + |
| 15 | +# patch tf1 into `utils.ops` |
| 16 | +utils_ops.tf = tf.compat.v1 |
| 17 | + |
| 18 | +# Patch the location of gfile |
| 19 | +tf.gfile = tf.io.gfile |
| 20 | + |
| 21 | + |
| 22 | +def load_model(model_name): |
| 23 | + base_url = 'http://download.tensorflow.org/models/object_detection/' |
| 24 | + model_file = model_name + '.tar.gz' |
| 25 | + model_dir = tf.keras.utils.get_file( |
| 26 | + fname=model_name, |
| 27 | + origin=base_url + model_file, |
| 28 | + untar=True) |
| 29 | + |
| 30 | + model_dir = pathlib.Path(model_dir) / "saved_model" |
| 31 | + |
| 32 | + model = tf.saved_model.load(str(model_dir)) |
| 33 | + model = model.signatures['serving_default'] |
| 34 | + |
| 35 | + return model |
| 36 | + |
| 37 | + |
| 38 | +def run_inference_for_single_image(model, image): |
| 39 | + image = np.asarray(image) |
| 40 | + # The input needs to be a tensor, convert it using `tf.convert_to_tensor`. |
| 41 | + input_tensor = tf.convert_to_tensor(image) |
| 42 | + # The model expects a batch of images, so add an axis with `tf.newaxis`. |
| 43 | + input_tensor = input_tensor[tf.newaxis, ...] |
| 44 | + |
| 45 | + # Run inference |
| 46 | + output_dict = model(input_tensor) |
| 47 | + |
| 48 | + # All outputs are batches tensors. |
| 49 | + # Convert to numpy arrays, and take index [0] to remove the batch dimension. |
| 50 | + # We're only interested in the first num_detections. |
| 51 | + num_detections = int(output_dict.pop('num_detections')) |
| 52 | + output_dict = {key: value[0, :num_detections].numpy() |
| 53 | + for key, value in output_dict.items()} |
| 54 | + output_dict['num_detections'] = num_detections |
| 55 | + |
| 56 | + # detection_classes should be ints. |
| 57 | + output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64) |
| 58 | + |
| 59 | + # Handle models with masks: |
| 60 | + if 'detection_masks' in output_dict: |
| 61 | + # Reframe the the bbox mask to the image size. |
| 62 | + detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( |
| 63 | + output_dict['detection_masks'], output_dict['detection_boxes'], |
| 64 | + image.shape[0], image.shape[1]) |
| 65 | + detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5, tf.uint8) |
| 66 | + output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy() |
| 67 | + |
| 68 | + return output_dict |
| 69 | + |
| 70 | + |
| 71 | +def run_inference(model, category_index, cap, show_video_steam, label_to_look_for, output_directory): |
| 72 | + os.makedirs(output_directory, exist_ok=True) |
| 73 | + os.makedirs(output_directory + '/images', exist_ok=True) |
| 74 | + |
| 75 | + if os.path.exists(output_directory + '/results.csv'): |
| 76 | + df = pd.read_csv(output_directory + '/results.csv') |
| 77 | + else: |
| 78 | + df = pd.DataFrame(columns=['timestamp', 'img_path']) |
| 79 | + |
| 80 | + while True: |
| 81 | + ret, image_np = cap.read() |
| 82 | + # Copy image for later |
| 83 | + image_show = np.copy(image_np) |
| 84 | + image_height, image_width, _ = image_np.shape |
| 85 | + # Actual detection. |
| 86 | + output_dict = run_inference_for_single_image(model, image_np) |
| 87 | + # Visualization of the results of a detection. |
| 88 | + if show_video_steam: |
| 89 | + vis_util.visualize_boxes_and_labels_on_image_array( |
| 90 | + image_np, |
| 91 | + output_dict['detection_boxes'], |
| 92 | + output_dict['detection_classes'], |
| 93 | + output_dict['detection_scores'], |
| 94 | + category_index, |
| 95 | + instance_masks=output_dict.get('detection_masks_reframed', None), |
| 96 | + use_normalized_coordinates=True, |
| 97 | + line_thickness=8) |
| 98 | + cv2.imshow('object_detection', cv2.resize(image_np, (800, 600))) |
| 99 | + if cv2.waitKey(25) & 0xFF == ord('q'): |
| 100 | + cap.release() |
| 101 | + cv2.destroyAllWindows() |
| 102 | + break |
| 103 | + |
| 104 | + # Get data(label, xmin, ymin, xmax, ymax) |
| 105 | + output = [] |
| 106 | + for index, score in enumerate(output_dict['detection_scores']): |
| 107 | + label = category_index[output_dict['detection_classes'][index]]['name'] |
| 108 | + ymin, xmin, ymax, xmax = output_dict['detection_boxes'][index] |
| 109 | + output.append((label, int(xmin * image_width), int(ymin * image_height), int(xmax * image_width), |
| 110 | + int(ymax * image_height))) |
| 111 | + |
| 112 | + # Save incident (could be extended to send a email or something) |
| 113 | + for l, x_min, y_min, x_max, y_max in output: |
| 114 | + if l == label_to_look_for: |
| 115 | + array = cv2.cvtColor(np.array(image_show), cv2.COLOR_RGB2BGR) |
| 116 | + image = Image.fromarray(array) |
| 117 | + cropped_img = image.crop((x_min, y_min, x_max, y_max)) |
| 118 | + file_path = output_directory + '/images/' + str(len(df)) + '.jpg' |
| 119 | + cropped_img.save(file_path, "JPEG", icc_profile=cropped_img.info.get('icc_profile')) |
| 120 | + df.loc[len(df)] = [datetime.datetime.now(), file_path] |
| 121 | + df.to_csv(output_directory + '/results.csv', index=None) |
| 122 | + |
| 123 | + |
| 124 | +if __name__ == '__main__': |
| 125 | + parser = argparse.ArgumentParser(description='Detect objects inside webcam videostream') |
| 126 | + parser.add_argument('-m', '--model', type=str, required=True, help='Model Path') |
| 127 | + parser.add_argument('-l', '--labelmap', type=str, required=True, help='Path to Labelmap') |
| 128 | + parser.add_argument('-s', '--show', default=True, action='store_true', help='Show window') |
| 129 | + parser.add_argument('-la', '--label', default='person', type=str, help='Label name to detect') |
| 130 | + parser.add_argument('-o', '--output_directory', default='results', type=str, help='Directory for the outputs') |
| 131 | + args = parser.parse_args() |
| 132 | + |
| 133 | + detection_model = load_model(args.model) |
| 134 | + category_index = label_map_util.create_category_index_from_labelmap(args.labelmap, use_display_name=True) |
| 135 | + |
| 136 | + cap = cv2.VideoCapture(0) |
| 137 | + run_inference(detection_model, category_index, cap, args.show, args.label, args.output_directory) |
0 commit comments