I have a huge Zip file with hundreds of thousands of images. I am trying to read those images in memory and extract the pixel data into an array. The idea is to use the flattened image array in model building. PIL.Image is not able to read a few files and it raises UnidenfitiedImageError in such cases. I want to catch this in try-except and take the path of all the problem images into a separate list. I am new to python & programming. I tried with a try-except clause but it does not work. Please help:
with ZipFile('/XXXXX/YYYYY/ZZZZZ/AI_ML/Project2/words.zip') as myzip:
contents = myzip.namelist()
for i in range(0,len(contents)-1):
text = str(contents[i])
if '.png' in text:
if 'MACOSX' not in text:
file_paths.append(contents[i])
for path in file_paths:
img = myzip.read(path)
try:
img_data = Image.open(BytesIO(img))
except UnidentifiedImageError:
problem_files.append(path)
img_data = img_data.convert('L') # 2
image_as_array = np.array(img_data, np.uint8) # 3
img_list.append(image_as_array)
This gives an error -
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f63ef5154c0>
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call last)
<ipython-input-8-23281c9e5d49> in <module>()
16 try:
17 img_data = Image.open(BytesIO(img))
---> 18 except UnidentifiedImageError:
19 problem_files.append(path)
20 img_data = img_data.convert('L') # 2
NameError: name 'UnidentifiedImageError' is not defined