I have written a function to load images (jpg, JPEG, png, gif etc.) and convert it to jpg. The code looks like this:
def jpg_image_open(file_path, fill_color=(255, 255, 255)):
image = PIL.Image.open(file_path)
print(file_path, image.mode)
if file_path.endswith('.gif'):
# print(image.is_animated, image.n_frames)
for im_frame in PIL.ImageSequence.Iterator(image):
# Converting it to RGB to ensure that it has 3 dimensions as requested
im_frame = im_frame.convert('RGB')
image = im_frame
break
elif file_path.endswith('.png'):
image.load()
if image.mode in ('P', 'L'):
image.convert("RGB")
elif image.mode in ('RGBA', 'LA'):
# https://stackoverflow.com/a/9459208/2049763
print(file_path, " has transparency layer")
# image.load() # required for png.split()
background = PIL.Image.new(image.mode[:-1], image.size, fill_color)
background.paste(image, image.split()[-1])
image = background
return image, np.array(image)
I usually call it from other files without error.
# read input image as numpy array
loaded_img, in_image = create_my_tf_record_util.jpg_image_open(img_file)
PIL.Image.fromarray(in_image, 'RGB').save(out_img_file)
It works great for all images except, if the image is in mode 'P', 'L'.
Traceback (most recent call last):
File "dataset_tools/create_my_tf_record_coco.py", line 322, in thread_cube_map_annotation_png
PIL.Image.fromarray(in_image, 'RGB').save(out_img_file)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2554, in fromarray
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2497, in frombuffer
return frombytes(mode, size, data, decoder_name, args)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2430, in frombytes
im.frombytes(data, decoder_name, args)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 812, in frombytes
raise ValueError("not enough image data")
ValueError: not enough image data