Search code examples
pythonpython-3.ximageopencvcrop

Python 3.x - Error when cropping images with OpenCV


so I have this 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)

Here is my error as output:

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'

I'm trying to make a template matching, I have this image (1680 x 1050): train And, when I'm trying to cropt it there is an error occured. (Which you can see above.) I've never used OpenCV cropping I used PIL for it and it worked. In PIL my code could be:

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

I'm giving the right path and everythin as you can see:

FIleTree

So, I don't know what's wrong with this...


Solution

  • The image is empty. Because your cropping along the wrong axis.

    Hint: Look at the error message

    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)
    

    You need

    >>> img_speed = img_rgb[983:1025, 1466:1519]
    >>> img_speed.shape
    (42, 53, 3)