I want to export tiff RGB images as a gif. Following code works but the images have very bad quality (lots of noise introduced).
import numpy as np
from PIL import Image
list_files = ["foo.tif", "bar.tif"]
# Create the frames
frames = []
for i in list_files:
tif = tifffile.TiffFile(i)
tif = tif.asarray()
tif = tif * 255 # Tiffs are actually floats, need to be converted to ints.
tif = tif[::3, ::3, :] # Downscale size
tif = tif.astype(np.uint8)
display(tif.shape)
frames.append(Image.fromarray(tif))
# Save into a GIF file that loops forever
frames[0].save('png_to_gif.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=0)
The resulting gif has distorted colours, presumably very low bit depth.

How do I save the gif with higher quality without the color distortions?
Since the pictures are floats <0, 1>, they don't render correctly here for preview (but are okay).


Similar issue was previously solved here: If you make a gif using Python Pillow, the color will disappear The trick is to extract the palette from the images before converting to gif. In my case all images have to merged first into one image, so that all colour values will be present in the subsequently extracted palette.