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

使用ssd_inception_v2_coco模型绘制检测框时遇TypeError问题求助

解决OpenVINO SSD模型检测框绘制时的TypeError问题

咱们先把你遇到的问题拆解清楚:TypeError: an integer is required (got type tuple) 这个报错出现在cv2.rectangle调用时,核心有两个问题导致了这个错误:

1. 图像张量维度不匹配

你预处理后的img形状是(1, 3, 300, 300),这是批量输入的CHW格式张量(通道在前,带批量维度),但cv2.rectangle需要的是单张图片的HWC格式(高度、宽度、通道,通道在后)。直接用这个张量画框,OpenCV无法正确解析图像维度,就会抛出类型错误。

2. cv2.imshow参数顺序搞反了

cv2.imshow的正确语法是cv2.imshow(窗口名称, 图像),但你写的是cv2.imshow(rect,'face_detection'),把图像和窗口名的顺序颠倒了,这也会引发后续异常。

修正后的完整代码

下面是调整后的代码,我标注了关键修改点:

import cv2

# Preprocessing image
img_path = r'D:\SriSailam.jpg'
# 保留原始图像,用于后续绘制检测框(避免被预处理操作覆盖)
original_img = cv2.imread(img_path)
# 单独创建预处理用的图像副本
processed_img = cv2.resize(original_img, (300, 300))
processed_img = processed_img.transpose((2, 0, 1))
processed_img = processed_img.reshape(1, 3, 300, 300)

exec_net = engine.load_network(net, 'cpu')
# Asynchronous request
infer_request_handle = exec_net.start_async(request_id=0, inputs={'image_tensor': processed_img})
infer_status = infer_request_handle.wait()
output = next(iter(net.outputs))
# 获取原始图像的真实宽高,用于缩放检测框坐标
h_original, w_original = original_img.shape[:2]
result = infer_request_handle.outputs[output] # Output shape is 1x1x100x7

''' Draw bounding boxes onto the image. '''
for box in result[0][0]: 
    conf = box[2] 
    print("probability value : ", conf)
    print("box[0] : ", box[0])
    print("box[1] : ", box[1])
    print("xmin : ", box[3])
    print("ymin : ", box[4])
    print("xmax : ", box[5])
    print("ymax : ", box[6])
    # 设置合理的置信度阈值(比如0.5),过滤低置信度的无效框
    if conf >= 0.5:
        # 用原始图像的宽高缩放坐标,确保框的位置匹配原图
        xmin = int(box[3] * w_original)
        ymin = int(box[4] * h_original)
        xmax = int(box[5] * w_original)
        ymax = int(box[6] * h_original)
        # 在原始图像上绘制检测框
        rect = cv2.rectangle(original_img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 1)
        # 修正cv2.imshow的参数顺序
        cv2.imshow('face_detection', rect)
        cv2.waitKey(0)
# 程序结束后释放窗口资源
cv2.destroyAllWindows()

关键修改说明:

  • 保留了原始图像original_img,避免预处理后的张量干扰绘制操作,同时用原始图像尺寸缩放检测框,保证框的位置准确。
  • 调整了cv2.imshow的参数顺序,把窗口名放在第一个位置。
  • 添加了合理的置信度阈值(0.5),过滤低置信度的检测结果,避免画面出现大量无效框。
  • 最后补充了cv2.destroyAllWindows(),防止程序结束后窗口残留。

运行修正后的代码,应该就能正常绘制检测框了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:22:49