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

问题描述 投票:0回答:2

所以我有这个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)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

所以,我不知道这是怎么回事...

python python-3.x image opencv crop
2个回答
0
投票
尝试将'cropped.png'保存为bmp。

此方法不支持png


0
投票
图像为空。因为您的种植方向错误。

提示:查看错误消息

错误:(-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)

© www.soinside.com 2019 - 2024. All rights reserved.