ValueError: could not broadcast input array from shape (224,224,4) into shape (224,224,3) , error while testing with GRAYSCALE IMAGES

Viewed 447

The following code works great with RGB images but not working with GRAYSCALE images, Also I need to know why grayimages are having shape as (224,224,4) , according to my knowledge it should be (224,224,1).

import silence_tensorflow.auto
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np

np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('models/keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)


def classify(img_path):
    image = Image.open(img_path)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)
    image_array = np.asarray(image)
    print(image_array.shape)
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    data[0] = normalized_image_array
    prediction = model.predict(data)
    print(prediction)
    if prediction[0][-1] == 1:      
        return False
    else:
        return True
1 Answers

For the benefit of community providing solution here

Grayscale images have 1 channel, RGB images have 3, and RGBA has 4 channels last channel represents alpha. You can try image = Image.open(img_path).convert('RGB') (paraphrased from Frightera)

Working code as shown below

import silence_tensorflow.auto
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np

np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('models/keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)


def classify(img_path):
    image = Image.open(img_path).convert('RGB')
    image = ImageOps.fit(image, size, Image.ANTIALIAS)
    image_array = np.asarray(image)
    print(image_array.shape)
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    data[0] = normalized_image_array
    prediction = model.predict(data)
    print(prediction)
    if prediction[0][-1] == 1:      
        return False
    else:
        return True
Related