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

OpenCV Python在参考图像上绘制矩形时报错求助

问题解决:OpenCV绘制矩形参数错误

错误根源

你代码里的bottom_right构造逻辑出错了:

bottom_right = (top_left[0], needle_w, top_left[1] + needle_h)

这行代码生成了一个三元组(包含三个元素),但cv.rectangle要求pt2参数必须是仅含x、y坐标的二元组,因此触发了Can't parse 'pt2'. Expected sequence length 2, got 3的错误。

正确的右下角坐标应该是:左上角x坐标加上模板宽度,左上角y坐标加上模板高度,也就是(top_left[0] + needle_w, top_left[1] + needle_h)。

修正后的完整代码

import cv2 as cv
import numpy as np

haystack_img = cv.imread('IBL_FULLSIZE.png', cv.IMREAD_UNCHANGED)
needle_img = cv.imread('CAT_B.png', cv.IMREAD_UNCHANGED)

result = cv.matchTemplate(haystack_img, needle_img, cv.TM_CCOEFF_NORMED)
cv.imshow('asdfsdf', result)
cv.waitKey()

# 获取最佳匹配位置
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

print('best match top left position: %s' % str(max_loc))
print('Best match confidence: %s' % max_val)

# 设置匹配阈值
threshold = 0.9
if max_val >= threshold:
    print('FOUND ONE')

    # 获取模板图像的尺寸
    needle_w = needle_img.shape[1]
    needle_h = needle_img.shape[0]

    top_left = max_loc
    # 修正右下角坐标计算逻辑
    bottom_right = (top_left[0] + needle_w, top_left[1] + needle_h)

    cv.rectangle(haystack_img, top_left, bottom_right,
                 color=(255, 0, 255), thickness=2)

    cv.imshow('boxResult', haystack_img)
    cv.waitKey()

else:
    print('error')

额外提示

你代码里print(str(max_loc))后面的cv.waitKey()属于冗余代码,不会影响功能但可以删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:03:14