Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make gif from circular masked images?

Download Zip with Images

I have a folder with circular masked png images:

enter image description here enter image description here enter image description here

Usually I use this code to make gifs:

import imageio
import os

imglist = []
images = []
path = ('\\').join(__file__.split('\\')[:-1]) + '\\' + 'images\\'
for r, _, f in os.walk(path):
    for i in f:
        imglist.append(r + i)

for filename in imglist:
    if filename.endswith('.png'):
        images.append(imageio.imread(filename))

frames_per_second = 24
gifpath = ('\\').join(__file__.split('\\')[:-1]) + '\\' + 'GIF.gif'
imageio.mimsave(gifpath, images, duration = 1/frames_per_second)

This works fine for ordinary images but it seems to ignore masked images. The gif looks like this:

enter image description here

Any idea how to make a circular gif?

like image 448
Artur Müller Romanov Avatar asked Nov 07 '22 12:11

Artur Müller Romanov


1 Answers

Your png files uses transparency, as it is true that GIF kind of support transparency, it is not the case of the imageio library.

If it is okay to have the masked area being white, you can do this inside your loop. Just replace :

for filename in imglist:
if filename.endswith('.png'):
    images.append(imageio.imread(filename))

With :

for filename in imglist:
if filename.endswith('.png'):
    tmp_image = imageio.imread(filename)
    mask = (tmp_image[:,:,3] == 0) #where transparency channel is 0
    tmp_image[mask] = [255,255,255,255] #Set those pixels to white (other color if you prefer)
    images.append(tmp_image)

GIF transparency is a bit special, you set one of the color to be render as transparent. If you want to do it in Python this thread should help.

I would also recommend to learn a bit how to make gif directly with ffmpeg. It is a bit hard to learn at first but it is what all the video/gif libraries uses behind the scene.

Best, R.

like image 163
rponthieu dev Avatar answered Nov 09 '22 07:11

rponthieu dev