Python 3.x - 使用 OpenCV 裁剪图像时出错

Python 3.x - Error when cropping images with OpenCV

所以我有这个代码:

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')

如您所见,我给出了正确的路径和所有内容:

所以,我不知道这有什么问题...

图片为空。因为你沿着错误的轴裁剪。

提示:看错误信息

error: (-215:Assertion failed) !_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)