You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

裁剪GIF去除空白区域后生成静态图的问题求助

裁剪GIF去除空白区域后生成静态图的问题求助

大家好,我最近在处理GIF裁剪的需求:想识别GIF里的对象,把没有对象的空白区域去掉,只保留有内容的部分。我写了一段代码,会拆分GIF的每一帧来处理,但不知道为什么,最后生成的不是动态GIF,而是一张静态图片。麻烦各位帮忙看看问题出在哪?

下面是我的代码:

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}")

这是我要处理的原GIF:
待裁剪的GIF

谢谢大家的帮助!

备注:内容来源于stack exchange,提问作者Ushay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:19:52