[Python] cropping a gif file by removing the white spaces

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to crop the gif by identifying the objects within the file and eliminating the spaces where there are no objects. I have a code which splits the gif by processing each frame of the gif. But it is somehow generating the static picture. Below is the code.

    from PIL import Image

    import numpy as np
    import cv2 as cv


    def process_frame(frame):
    frame = np.array(frame)


    if len(frame.shape) == 3 and frame.shape[2] == 4: # Check if it's RGBA (with alpha channel)
    frame = cv.cvtColor(frame, cv.COLOR_RGBA2RGB)
    elif len(frame.shape) == 2: # If the frame is grayscale (1 channel)
    frame = cv.cvtColor(frame, cv.COLOR_GRAY2RGB)


    gray = cv.cvtColor(frame, cv.COLOR_RGB2GRAY)

    th = 240
    (th, mask) = cv.threshold(gray, th, 255, cv.THRESH_BINARY_INV)

    contours, _ = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    if contours:
    x, y, w, h = cv.boundingRect(contours[0])
    cropped_frame = frame[y:y + h, x:x + w]
    return cropped_frame
    else:
    return frame

    gif_path = 'Animation.gif'
    gif = Image.open(gif_path)

    processed_frames = []

    for frame_idx in range(gif.n_frames):
    gif.seek(frame_idx)
    frame = gif.copy() # Copy the frame to process it
    cropped_frame = process_frame(frame)
    processed_frames.append(cropped_frame)

    # Now, save the processed frames as a new GIF
    output_gif_path = 'output_cropped.gif'

    # Convert frames back to PIL format (as gif.save() expects a list of PIL frames)
    pil_frames = [Image.fromarray(f) for f in processed_frames]
    pil_frames[0].save(output_gif_path, save_all=True, append_images=pil_frames[1:],
    loop=0, duration=gif.info['duration'])

    print(f"GIF saved to {output_gif_path}")


    Thanks for your help!

    [​IMG]

    Continue reading...

Compartilhe esta Página