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

OpenCV模板匹配遇目标缩放时无法检测物体的技术求助

屏幕缩放场景下OpenCV模板匹配失效问题

我正在学习提升计算机视觉技能,编写了一个基于OpenCV模板匹配的屏幕物体检测脚本。但遇到一个问题:当目标物体进行缩放(放大或缩小)操作时,脚本无法完成检测。目前仅在目标缩放273%时检测成功,缩放205%时检测失败。

附上脚本代码如下:

import keyboard
import mss
import cv2
import numpy
from time import time, sleep
import pyautogui

pyautogui.PAUSE = 0

sct = mss.mss()
dimensions_left = {'left': 0,'top': 0,'width': 2560,'height': 1440}

print("Press 's' to start playing.")
print("Once started press 'p' to quit.")
keyboard.wait('s')

detect = cv2.imread('scend.png', cv2.COLOR_RGB2BGR)
w = detect.shape[1]
h = detect.shape[0]
ww , hh = int(w/2),int(h/2)

fps_time = time()

while True:
    im = numpy.array(sct.grab(dimensions_left))
    im = numpy.flip(im[9:, 9:, :1], 2)  # 1
    im = cv2.resize(im, (1000, 500))
    im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
    result = cv2.matchTemplate(im, detect, cv2.TM_CCOEFF_NORMED)

    threshold = .4
    yloc, xloc = numpy.where(result >= threshold)

    rectangles = []
    for (x, y) in zip(xloc, yloc):
        rectangles.append([int(x), int(y), int(w), int(h)])
        rectangles.append([int(x), int(y), int(w), int(h)])

    rectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)

    for (x, y, w, h) in rectangles:
        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 255), 2)
        cv2.rectangle(im, (x + ww, y + hh), (x + w - ww, y + h - hh), (0, 0, 255), 5)

        # pyautogui.moveTo(x, y, 0)

    cv2.imshow('Screen Shot', im)
    cv2.waitKey(1)
    if keyboard.is_pressed('p'):
        break

    print('FPS: {}'.format(1 / (time() - fps_time)))
    fps_time = time()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:57:22