'OpenCV(4.1.0) error: (-215:Assertion failed)

I am following this tutorial series: https://www.youtube.com/watch?v=A4K6D_gx2Iw&list=PLQVvvaa0QuDfhTox0AjmQ6tvTgMBZBEXN&index=6

When I try to use the model outside the program by prediction it gives me the following error: error: OpenCV(4.1.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/resize.cpp:3718: error: (-215:Assertion failed) !ssize.empty() in function 'resize'

Below the code when loading the model:

import cv2
import tensorflow as tf

CATEGORIES = ["Dog", "Cat"]
    import cv2
import tensorflow as tf

CATEGORIES = ["Dog", "Cat"]

def prepare(filepath):
    IMG_SIZE = 50
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    #return img_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)

    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
#
model = tf.keras.models.load_model('iyad')
#
predication = model.predict([prepare("Dog.jpg")])

print(predication)


Solution 1:[1]

In addition @stormzhou answer: Just type this your script or ipython cell to verify if there is an empty or corrupt image that might create this error .

import os
from PIL import Image

img_dir = r"/content/downloads/Cars"
for filename in os.listdir(img_dir):
    try :
        with Image.open(img_dir + "/" + filename) as im:
             print('ok')
    except :
        print(img_dir + "/" + filename)
        os.remove(img_dir + "/" + filename)

Replace img_dir to the directory name from where you are trying to resize the images. Hope it was helpful .

Solution 2:[2]

It's a path error. Put the correct and full path.

Problem 1: When you run it from an IDE, the IDE console's path might be different and might not be able to locate the image so provide the full path i.e. instead of image.png do something like: _image = cv2.imread(r'C:/Desktop/pc_name/Desktop/images/cat.png')

Problem 2: Image extension. Check if the image is .jpg or '.png' or other.

Problem 3: You've written an incorrect image name or the image simply doesn't exist at the location provided.

Solution 3:[3]

    X=[]
count=0

path=TRAIN_PATH_X
for img in os.listdir(TRAIN_PATH_X):
    image=cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)
    try:
        image = cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH), interpolation=cv2.INTER_AREA)
        print(image.shape)
    except:
        break
    X.append([image])
    count = count +1
print(count)

Solution 4:[4]

error 215 assertion failed usually occurs when the image is not loading correctly, so check the path of the image

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajay Alex
Solution 2 Mujeeb Ishaque
Solution 3 Iftikhar humayun
Solution 4 Mohammed Younis