CV2 Image Error: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'

Viewed 28956

I'm making an image classifier with TensorFlow and Python, but I'm having an error reading images with CV2. I'm very new to CV2, and I haven't been able to find anything that sufficiently solves my problem. Can anyone explain how to solve this?

def train_data_with_label():
  train_images = []
  for i in tqdm(os.listdir(train_data)):
    path = os.path.join(train_data, i)
    img = cv2.imread(path, 3)
    img = cv2.resize(img, (64,64))
    train_images.append([np.array(img), one_hot_label(i)])
  shuffle(train_images)
  return train_images
  
def test_data_with_label():
  test_images = []
  for i in tqdm(os.listdir(test_data)):
    path = os.path.join(test_data, i)
    img = cv2.imread(path, 3)
    img = cv2.resize(img, (64,64))
    test_images.append([np.array(img), one_hot_label(i)])
  shuffle(test_images)
  return test_images

This is the error I got:

Using TensorFlow backend.
  0%|                                                                                            | 0/2 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "retrain.py", line 47, in <module>
    training_images = train_data_with_label()
  File "retrain.py", line 32, in train_data_with_label
    img = cv2.resize(img, (64,64))
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
8 Answers

Your imread() call failed. It returned None.

When you try to imread() a file that doesn't exist, or it's not a proper picture file, imread signals that by returning None (in Python), instead of a proper numpy array.

Now, when you pass this None to resize(), resize() notices and throws this error. It tries to check if the argument is a proper array, and that it's not an empty array. In this case, your argument isn't even an array, but the error is the same.

How to fix this: check if the result of imread() is None. If it is None, reading failed. Just continue the loop on to the next picture file name.

img = cv2.imread(path)
if img is None:
    continue

by the way: the 3 in the second argument to imread means IMREAD_COLOR | IMREAD_ANYDEPTH

check if there _DS_Store file in the folder you're trying to iterate in the for loop, as it is not a image file cv2.resize() is not able to resize it.

You're probably reading in an invalid zero-pixel image. Check your image path since the size of your source image is most likely empty and has not been read in properly. You can check the image's shape to ensure that it has a valid (height, width, channels) dimension like this

image = cv2.imread('noexist.png')
print(image.shape)

If you get an AttributeError error similar to this, it means your image path is invalid/corrupted.

Traceback (most recent call last):
  File ".\test.py", line 4, in <module>
    print(image.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

OpenCV will not throw an exception until you try to do something with this NoneType object. So in the next line when you attempt to resize the image, it throws the error. Your situation is reproducible with this simple example

import cv2

image = cv2.imread('noexist.jpg')
resize = cv2.resize(image, (64,64))
cv2.waitKey()

Note if you remove the cv2.resize(), an exception will not be thrown. To fix your problem, you can use cv2.error and a try/except block to catch the exception

import cv2

image = cv2.imread('noexist.jpg')
try:
    resize = cv2.resize(image, (64,64))
except cv2.error as e:
    print('Invalid frame!')
cv2.waitKey()

Invalid frame!

Based on the error it seems there is some issue in the input. It should be a list of non empty arrays. Please verify the path and images for any corrupt image. Also, check the image formats; if any multi band tiff file is present which cv2.imread is not able to read.

Try reading the images in batches to identify the batch having the image that is causing the problem.

Before reading the image, check if there is an non-existent image. Try this before reading the images:

if not os.path.isfile(train_data):
    continue

path = os.path.join(train_data, i)

img = cv2.imread(path, 3)

I think the issue is with working directory. I have also received the same error and it was resolved when I correct my working directory. Below is my code which worked when run from correct directory.

def image_2_text(input_path,out_path):
 for ImgName in os.listdir(input_path):

    fullpath = os.path.join(input_path,ImgName)
    Img = cv2.imread(fullpath)
    text = pytesseract.image_to_string(Img,lang='eng')
    text = text.replace("\n"," ")
    text = " ".join(re.findall("[a-zA-Z]*",text))
    
    file_append = open(out_path,'a+')
    file_append.write(ImgName+'\t')
    file_append.write(text+'\n')
    file_append.close()
print("Process Complete")

I was getting this error because I was feeding multiple images to cv2.resize().

resizedNumpyImage = cv2.resize(numpyArrayOfSingleImage,(neWidth,newHeight))

changing the directory on my terminal worked for me!

cd C:/Users.../image location

Related