使用OpenCV裁剪图像时出现Python3.x错误

2024-04-25 21:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这个代码:

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)train 而且,当我试图偷拍时,出现了一个错误。(您可以在上面看到)我从来没有使用过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')

我给了你正确的道路和你所看到的一切:

FIleTree

所以,我不知道这有什么问题。。。你知道吗


Tags: 代码inimportptimgpngrestemplate
1条回答
网友
1楼 · 发布于 2024-04-25 21:34:44

图像为空。因为你切错了轴。你知道吗

提示:查看错误消息

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)

相关问题 更多 >