ValueError: could not broadcast input array from shape (128,128,3) into shape (128,128)

Viewed 6535

hi I am building an image classifier and this an small part of my code in this part m trying to 'img_data_list' is an array and I am converting this array into np.array but (img_ data = np.array(img_data_list)) this line of code giving me an error (could not broadcast input array from shape (128,128,3) into shape (128,128)) i dont know why this is happening

for dataset in data_dir_list:
    img_list=os.listdir(data_path+'/'+ dataset)

    print ('Loaded the images of dataset-'+'{}\n'.format(dataset))

    for img in img_list:
        image_path = os.path.join(data_path, dataset, img)

        input_img=cv2.imread(image_path)

        if input_img is not None:
            input_img_resize=cv2.resize(input_img,(128,128))
            img_data_list.append(input_img_resize)

        else:
            print(img+' image didnt read')

img_data = np.array(img_data_list)
img_data = img_data.astype('float32')
img_data /= 255
3 Answers

I found the solution some images are corrupted in dataset after removing them classifier is working perfectly

That happens when you have an image with the expected shape like @Rahul Pant said, maybe other than (224,224,3), since youve only checked the 0th element shape. I had this error with an Image array, and I was able to fix it by this code.

print(len(img_data_list)) #to check the lenght of the list with elements having different shape

for item in img_data_list:
  if item.shape!=(224,224,3):
    img_data_list.remove(item)

print(len(img_data_list)) #you'll know how many corrupt sized images you had
Related