I am trying to draw a red square around a picture whenever it appears on my screen. I'm using python 3.7. This is my first day with opencv, so the code I have so far is extremely clunky.
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)
I get the following error:
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'
If I'm reading this right, then the problem is that I am trying to compare the template image which is bigger than the source image. However, I can't figure out how to solve this because the screen capture is definitely bigger than the image.
CodePudding user response:
This error shows when either,path of the image is wrong or name of the image is wrong. you can print your images for checking.
CodePudding user response:
This was a dumb mistake. But in case anybody is wondering, I needed to insert the following before the code:
with mss() as sct: monitor = sct.monitors[1]