从tensorflow对象检测api打印类名

2024-05-16 19:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

请注意:我在网上尝试过其他解决方案,但没有找到效果。 我使用tensorflow对象检测api和opencv从live feed检测对象。它工作正常,可以在屏幕上显示方框。现在我只想在终端上打印检测到的对象。 我试过各种各样的解决办法,却找不到任何有效的办法。我是新来的。 这是我的密码:

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)))

我尝试使用:

print(detections['detection_classes'])

但这只是打印出一组值。任何帮助都将不胜感激


Tags: 对象imagetrueinputtfwithnparray
1条回答
网友
1楼 · 发布于 2024-05-16 19:33:08

category_index是一本带有标签名的词典。使用detections['detection_classes']对其进行索引以获取类别的名称。类似这样的东西,但这不起作用,因为我在这里直接编写,不需要测试:

label_names = [i['name'] for i in category_index.items()]
label_names = np.array(label_names)

print(label_names[detections['detection_classes'].numpy()])

相关问题 更多 >