VicTheGreat
VicTheGreat

Reputation: 35

images (png, jpg or jpeg) is detected as corrupt with python's PIL / Pillow verify()

I am trying to detect corrupted images from a large dataset of images. I am using the Pillow package and verify(). I simply want to detect images that are corrupted or wont open with an image viewer or browser as "Bad flies" instead, ALL my images are always detected as "bad"

from os import listdir
from PIL import Image

for imageFolder in listdir('./batch1'):
    try:
        img = Image.open('./batch1'+imageFolder)
        img.verify()     # to veify if its an img
        img.close()     #to close img and free memory space
    except (IOError, SyntaxError) as e:
        print('Bad file:', imageFolder)

Am I doing something wrong?

Is there any other method to achieve my goal of detecting corrupted images without deleting each corrupted image manually?

Upvotes: 1

Views: 5932

Answers (1)

Kostas Charitidis
Kostas Charitidis

Reputation: 3103

You need to add a / after your path. Else your fullpath would seem something like .'batch1your_img.png

from os import listdir
from PIL import Image

for imageFolder in listdir('./batch1'):
    try:
        img = Image.open('./batch1/'+imageFolder)
        img.verify()     # to veify if its an img
        img.close()     #to close img and free memory space
    except (IOError, SyntaxError) as e:
        print('Bad file:', imageFolder)

Also make sure that your batch1 directory containes only images, else you'll get another error.

Upvotes: 1

Related Questions