You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow Object Detection如何将检测目标打印输出到控制台

实现方法

TensorFlow Object Detection API的返回结果里,detections字典不直接存储字符串格式的检测目标名称,仅在detections['detection_classes']字段存储整数类型的类别ID;类别ID到实际目标名称的映射关系,存放在你传入可视化函数的category_index变量中,结构为{类别ID: {'id': 类别ID, 'name': '目标名称'}}。

你可以在完成detections字典预处理的代码段后、调用可视化函数之前或之后,添加如下遍历逻辑,把符合置信度要求的检测目标信息打印到控制台即可。注意打印逻辑的参数必须和可视化参数保持一致,避免ID匹配错位:

# 与可视化参数对齐的阈值配置
min_score_thresh = .8
label_id_offset = 1

print("===== 目标检测结果 =====")
for idx in range(detections['num_detections']):
    score = detections['detection_scores'][idx]
    # 过滤置信度不达标的检测框
    if score < min_score_thresh:
        continue
    # 换算匹配category_index的实际类别ID
    class_id = detections['detection_classes'][idx] + label_id_offset
    # 读取目标名称
    class_name = category_index[class_id]['name']
    detect_box = detections['detection_boxes'][idx]
    
    # 控制台输出,可按需调整字段
    print(f"目标:{class_name} | 置信度:{score:.2%} | 归一化坐标[y_min,x_min,y_max,x_max]:{np.round(detect_box, 3)}")

补充说明

  • 打印时给detection_classes加label_id_offset的操作必须和visualize_boxes_and_labels_on_image_array调用时的逻辑完全一致,否则会出现类别名匹配错误
  • 上述代码输出的是归一化格式的检测框坐标,如果需要像素级坐标,提前读取图像宽高做换算即可:
    img_h, img_w = image_np.shape[:2]
    # 像素坐标换算示例:y_min = int(detect_box[0] * img_h)
    
  • 如果需要限制打印的检测结果数量,和可视化的max_boxes_to_draw参数对齐,在循环里加计数截断逻辑就行。

内容的提问来源于stack exchange,提问作者Mustafa Öztekin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 15:36:26