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