How to add GIF to a static background (PIL + imageio) V.2 – The Better One

My previous version has flaws. It works well for opaque GIFs, but OpenCV is famous for not being good with transparent images. So instead of OpenCV I use imageio for GIF iteration and PIL for adding GIF frames to the static background.

Why do more?

The original algorithm left these artifacts, look at the cyan block on the intersection of GIF frame and a darker abstract part:

The artefact in question

Solution

The code is pretty much the same as here How to add GIF to a static background (Python + OpenCV). Video Generation series (Part 1), except for the loop itself:

    frame_index = 1
    while True:
        if frame_index < gif_length:

            # get a frame with imageio
            foreground = gif_reader.get_data(frame_index)
            
            # convert it to PIL.Image
            fore = Image.fromarray(foreground)
            
            # making a new image - background + GIF frame
            frame_path = f'temp/{frame_index}.png'
            back = Image.open(background_image, 'r')
            back.paste(fore, (0, 0), fore)
            back.save(frame_path)
            
            # for OpenCV to add it to video
            frame_to_write = cv2.imread(frame_path)

            video.write(frame_to_write)
            last_frame = frame_to_write
            
            total_frames -= 1
            frame_index = frame_index + 1
        else:
            break
    while total_frames:
        video.write(last_frame)
        total_frames -= 1

Comparison

Before
After

In particular detail that indicates the issue is now gone:

Before
After

Happy as I can be.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.