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


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 =, 'r')
            back.paste(fore, (0, 0), fore)
            # for OpenCV to add it to video
            frame_to_write = cv2.imread(frame_path)

            last_frame = frame_to_write
            total_frames -= 1
            frame_index = frame_index + 1
    while total_frames:
        total_frames -= 1



In particular detail that indicates the issue is now gone:


Happy as I can be.

Leave a Reply

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

You are commenting using your 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.