【问题标题】:OpenCV Python - How to use current screen as source image?OpenCV Python - 如何使用当前屏幕作为源图像?
【发布时间】:2022-01-13 20:50:55
【问题描述】:

每当图片出现在我的屏幕上时,我都会尝试在图片周围画一个红色方块。我正在使用python 3.7。这是我使用 opencv 的第一天,所以到目前为止我的代码非常笨拙。

import cv2
import numpy
from mss import mss

template = cv2.imread("mountain.png")
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
img = numpy.array(sct.grab(monitor))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# perform match
res = cv2.matchTemplate(gray,template ,cv2.TM_CCOEFF)
# get coordinates of best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = min_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
# draw red rectangle over original screen capture
cv2.rectangle(img,top_left, bottom_right,(0,0,255),3)
# display image
#cv2.imshow('Result',img)

我收到以下错误:

error                                     Traceback (most recent call last)
/var/folders/ks/mmylcnjn1cjdthv824f0l36h0000gn/T/ipykernel_7719/1707960325.py in <module>
     10 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     11 # perform match
---> 12 res = cv2.matchTemplate(gray,template ,cv2.TM_CCOEFF)
     13 # get coordinates of best match
     14 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

error: OpenCV(3.4.2) /opt/concourse/worker/volumes/live/9523d527-1b9e-48e0-7ed0-a36adde286f0/volume/opencv-suite_1535558719691/work/modules/imgproc/src/templmatch.cpp:1107: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'matchTemplate'

如果我没看错,那么问题是我正在尝试比较大于源图像的模板图像。但是,我不知道如何解决这个问题,因为屏幕截图肯定比图像大。

【问题讨论】:

    标签: python-3.x opencv


    【解决方案1】:

    我需要在代码前插入以下内容:

    with mss() as sct:
        monitor = sct.monitors[1]
    

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2014-06-13
      • 2014-09-24
      相关资源
      最近更新 更多