'Print class name from tensorflow object detection api
PLEASE NOTE: I have tried other solutions accross the web and didnt find the working result. I am detecting objects from live feed using tensorflow object detection api and opencv. It is working fine and showing the boxes on the screen. Now i want to only print the detected object on the terminal. I Have tried various solutions and couldnt find anything which worked. I am new to this. Here's my code:
while True:
ret, frame = cap.read()
image_np = np.array(frame)
input_tensor = tf.convert_to_tensor(
np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(
np.int64)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes']+label_id_offset,
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=5,
min_score_thresh=.5,
agnostic_mode=False)
cv2.imshow('object detection', cv2.resize(
image_np_with_detections, (800, 600)))
I tried using:
print(detections['detection_classes'])
But that just prints a set of values.Any help would be appreciated
Solution 1:[1]
print(category_index[detections['detection_classes'][np.argmax(detections['detection_scores'])]+1]['name'])
try using this ( here category_index is where all your labels are )
Solution 2:[2]
category_index
is a dictionary with your label names. Index it with detections['detection_classes']
to get the name of the categories. Something like this, but this won't work because I'm writing it directly on here without testing:
label_names = [i['name'] for i in category_index.items()]
label_names = np.array(label_names)
print(label_names[detections['detection_classes'].numpy()])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Akshay Pavithran |
Solution 2 | Nicolas Gervais |