TomSelleck
TomSelleck

Reputation: 6968

keras.preprocessing.image.load_img "UnidentifiedImageError"

I'm trying to follow this Keras tutorial for image segmentation. It seems to run fine in Colab, but running locally, I get the following error:

for j, path in enumerate(batch_target_img_paths):
    img = load_img(path, target_size=self.img_size, color_mode="grayscale")

...

Exception has occurred: UnidentifiedImageError
cannot identify image file <_io.BytesIO object at 0x0000020130390400>
  File "C:\Computer Vision\main_tutorial.py", line 203, in __getitem__
    img = load_img(path, target_size=self.img_size, color_mode="grayscale")
  File "C:\Computer Vision\main_tutorial.py", line 102, in main
    model.fit(train_gen, epochs=epochs, validation_data=val_gen, callbacks=callbacks)
  File "C:\Computer Vision\main_tutorial.py", line 211, in <module>
    main()

I've verified the path is correct:

C:\Computer Vision\oxford-iiit-pet\train\annotations\._Abyssinian_10.png

The file in question ._Abyssinian_10.png doesn't appear to be a valid image (I believe it's a target mask) and can't be opened in a regular image viewing application.

Is there an environment or platform issue I'm missing?

Upvotes: 0

Views: 1325

Answers (2)

TomSelleck
TomSelleck

Reputation: 6968

The error was a mistake on my part.

The annotations/trimaps folder contains two files for each original image:

._Abyssinian_1.png

Abyssinian_1.png

I was trying to load the incorrect file ._Abyssinian_1.png where I should have been loading Abyssinian_1.png

Upvotes: 0

yudhiesh
yudhiesh

Reputation: 6809

If you are facing this error then the image is probably corrupted or of NoneType.

You cannot salvage this image in my experience and you are better off just removing it with the code below which checks if the image is valid as a PNG and if it isn't then remove the image. If you have JPEG images then you can just use jpeg instead.

You would have to run this over the entire directory of your images.

import cv2
import imghdr
import os

image_path = "C:\Computer Vision\oxford-iiit-pet\train\annotations\._Abyssinian_10.png"
image = cv2.imread(image_path)
img_type = imghdr.what(image_path)
if img_type != "png":
    os.remove(image_path)

Upvotes: 1

Related Questions