Search code examples
tensorflowobject-detectionobject-detection-apimobilenet

Saving image in a real time object detector


I am currently running a real-time object detector using SSD MobileNetv2 in TensorFlow 1.x and would like to know if there are any ways where I can save an image when one of the class gets detected by the video stream.

PATH_TO_FROZEN_GRAPH = 'path-to-inference-graph.pb'
PATH_TO_LABEL_MAP = 'path-to-label-map.pbtxt'
NUM_CLASSES = 4
cap = cv2.VideoCapture(0)

Basically, I have built the detector to detect 4 classes and would like to save the image (maybe it is likely to come out as a burst of images, still fine) when one of the class gets detected.

label_map = label_map_util.load_labelmap(PATH_TO_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.read()
            image_np_expanded = np.expand_dims(image_np, axis=0)
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})

            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=3,
                )

            cv2.imshow('Detection', cv2.resize(image_np, (1200, 800)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

How do I achieve this? Are there any other variations for it?


Solution

  • After session.run, you get the results in (boxes, scores, classes, num_detections)

    You just have to iterate over them and see the class and score and finally save the

    if 'req_class_name' in classes:
       #check for confidence score also
       cv2.imwrite('/path/to/destination/image.png', image_np)