[在此处输入图片描述][1]晚上好,我想制作一个屏幕截图并将其用于模板匹配但每次我尝试时都会出现此错误,我不是专业程序员我只是为了好玩而这样做有人可以帮助我,这将是惊人的。谢谢。
我得到的错误:
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1164: error: (-215:Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'[enter image description here][2]
如果我使用通过软件拍摄的截图,它可以完美运行,但是当我尝试使用这个脚本拍摄的截图时,它不起作用。
import cv2
import numpy as np
import pyautogui
from PIL import Image
#take a screenshot
pyautogui.screenshot().save("ecran.png")
# Load the image and convert to 32-bit RGB
im = Image.open("ecran.png").convert('RGB')
# Save result
im.save("ecran.PNG")
#input()
bureau = cv2.imread('C:/Users/ASUS/Desktop/Image-reconizer/ecran.PNG', cv2.IMREAD_UNCHANGED)
dossier = cv2.imread('C:/Users/ASUS/Desktop/Image-reconizer/dossier.PNG', cv2.IMREAD_UNCHANGED)
result = cv2.matchTemplate(bureau, dossier, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc, = cv2.minMaxLoc(result)
w = dossier.shape[1]
h = dossier.shape[0]
pos1 = max_loc[0] + h
pos2 = max_loc[1] + w
yloc, xloc = np.where(result >= 0.55)
rectangle = []
for (x, y) in zip(xloc, yloc):
rectangle.append([int(x), int(y), int(w), int(h)])
rectangle.append([int(x), int(y), int(w), int(h)])
rectangle, weights = cv2.groupRectangles(rectangle, 1, 0.2)
for (x, y, w, h) in rectangle:
rec = cv2.rectangle(bureau, (x, y), (x + w, y + h), (0, 255, 0), 2)
window = cv2.imshow("rectangle ", rec)
cv2.waitKey()
此版本的代码用于直接使用 2 张图片而没有截图:
import cv2
import numpy as np
import pyautogui
from PIL import Image
bureau = cv2.imread('C:/Users/ASUS/Desktop/Image-reconizer/ecran1.PNG', cv2.IMREAD_UNCHANGED)
dossier = cv2.imread('C:/Users/ASUS/Desktop/Image-reconizer/dossier.PNG', cv2.IMREAD_UNCHANGED)
result = cv2.matchTemplate(bureau, dossier, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc, = cv2.minMaxLoc(result)
w = dossier.shape[1]
h = dossier.shape[0]
pos1 = max_loc[0] + h
pos2 = max_loc[1] + w
yloc, xloc = np.where(result >= 0.55)
rectangle = []
for (x, y) in zip(xloc, yloc):
rectangle.append([int(x), int(y), int(w), int(h)])
rectangle.append([int(x), int(y), int(w), int(h)])
rectangle, weights = cv2.groupRectangles(rectangle, 1, 0.2)
for (x, y, w, h) in rectangle:
rec = cv2.rectangle(bureau, (x, y), (x + w, y + h), (0, 255, 0), 2)
window = cv2.imshow("rectangle ", rec)
cv2.waitKey()
错误图片:[1]:https ://i.stack.imgur.com/G0f5R.png
档案.png [2]:https ://i.stack.imgur.com/i1qea.png
ecran1.png(此图像是使用软件截取的屏幕截图,当我使用此图像而不是截取脚本时,代码可以完美运行)[3]:https ://i.stack.imgur.com/bQPFJ.jpg
这是我使用图像 3 而不是屏幕截图时的结果图像(程序有效)[4]:https ://i.stack.imgur.com/eAEXT.jpg