所以我有这个code:
import cv2
import numpy as nm
img_rgb = cv2.imread('mta-screen_2020-01-01_12-07-24.png')
img_speed = img_rgb[1466:1519, 983:1025]
cv2.imwrite('cropped.png', img_speed)
img_speed_gray = cv2.cvtColor(img_speed, cv2.COLOR_BGR2GRAY)
path = 'D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\MTA_pyautogui\TrainImgs' + chr(92) + '1new.png'
# -------------------------------------------------------------------------------------------- #
template = cv2.imread(path, 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_speed_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.1
loc = nm.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.imwrite('res.png', img_rgb)
这是我的错误作为输出:
Traceback (most recent call last):
File "D:/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton/MTA_pyautogui/main.py", line 44, in <module>
cv2.imwrite('cropped.png', img_speed)
cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
我正在尝试使模板匹配,我有此图像(1680 x 1050)
:而且,当我尝试裁剪时,发生了错误。 (您可以在上面看到。)我从未使用过OpenCV裁剪,我使用了[[PIL
并成功了。在PIL
中,我的代码可能是:
im = Image.open('mta-screen_2020-01-01_12-07-24.png').convert('L')
im = im.crop((1466, 983, 1519, 1025))
im.save('cropped_speed.png')
正如您所看到的,我给了正确的道路和一切:所以,我不知道这是怎么回事...
此方法不支持png
提示:查看错误消息
错误:(-215:断言失败)!_img.empty()
>>> img_rgb.shape
(1050, 1680, 3)
>>> img_speed = img_rgb[1466:1519, 983:1025]
>>> img_speed.shape
(0, 42, 3)
您需要
>>> img_speed = img_rgb[983:1025, 1466:1519] >>> img_speed.shape (42, 53, 3)