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

如何测试用TensorFlow2 exporter_main_v2导出的自定义目标检测模型?

解决自定义TensorFlow目标检测模型测试问题

错误原因

你遇到的OpenCV报错,核心是格式不兼容:exporter_main_v2.py导出的是TensorFlow SavedModel格式,而OpenCV的dnn模块仅支持解析旧版TensorFlow的GraphDef冻结.pb文件,直接用OpenCV加载SavedModel里的saved_model.pb必然失败。

两种测试导出模型的方法

方法一:用TensorFlow Object Detection API自带工具快速测试

如果已配置好API环境,直接用官方脚本一键测试:

  1. 切换到API的object_detection目录
  2. 运行命令(替换为你的实际路径):
python inference/detect_objects.py \
    --input_image=path/to/your/test_image.jpg \
    --output_directory=path/to/save/results \
    --saved_model_dir=path/to/exported_model/saved_model \
    --label_map_path=path/to/your/label_map.pbtxt

脚本会自动输出带检测框的结果图,并打印检测到的目标信息。

方法二:自定义Python脚本手动测试

如果需要更灵活的控制(比如调整置信度阈值、自定义后处理),用以下脚本:

import tensorflow as tf
import cv2
import numpy as np
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_utils

# 1. 配置路径
PATH_TO_SAVED_MODEL = 'D:/VSCode/Machine_Learning_Tests/Tensorflow/workspace/exported_models/first_model/saved_model'
PATH_TO_LABEL_MAP = 'path/to/your/label_map.pbtxt'  # 训练时用的标签映射文件
PATH_TO_TEST_IMAGE = 'path/to/your/test_deer_image.jpg'
MIN_CONFIDENCE_THRESHOLD = 0.5  # 过滤低置信度结果的阈值

# 2. 加载标签映射
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABEL_MAP, use_display_name=True)

# 3. 加载SavedModel
print('加载模型中...')
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)
print('模型加载完成')

# 4. 处理测试图片
image = cv2.imread(PATH_TO_TEST_IMAGE)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_tensor = tf.convert_to_tensor(np.expand_dims(image_rgb, 0), dtype=tf.uint8)

# 5. 运行检测
detections = detect_fn(image_tensor)

# 6. 解析检测结果(转成numpy数组)
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
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

# 7. 绘制检测框并输出结果
vis_utils.visualize_boxes_and_labels_on_image_array(
    image,
    detections['detection_boxes'],
    detections['detection_classes'],
    detections['detection_scores'],
    category_index,
    use_normalized_coordinates=True,
    max_boxes_to_draw=200,
    min_score_thresh=MIN_CONFIDENCE_THRESHOLD,
    agnostic_mode=False)

# 显示图片
cv2.imshow('检测结果', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存结果图片
cv2.imwrite('detection_result.jpg', image)

# 打印文本检测结果
print('检测到的目标:')
for i in range(num_detections):
    score = detections['detection_scores'][i]
    if score >= MIN_CONFIDENCE_THRESHOLD:
        class_name = category_index[detections['detection_classes'][i]]['name']
        print(f"- 目标:{class_name},置信度:{score:.2f}")

注意事项

  • 确保环境安装了TensorFlow 2.x、OpenCV,且TensorFlow Object Detection API依赖配置完成
  • label_map.pbtxt必须和训练时的类别完全对应,否则类别名称会出错
  • 可根据模型性能调整MIN_CONFIDENCE_THRESHOLD,过滤低置信度的误检测结果

内容的提问来源于stack exchange,提问作者pypypy123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:06:18