首页 > 解决方案 > 如何使用脚本裁剪 GIF?

问题描述

有没有像这个页面一样在 python 中裁剪 gif 的脚本:https ://www.iloveimg.com/crop-image ?

前段时间,我发现了使用 Python 进行图像裁剪,但问题是你需要用光标绘制矩形。

我需要一个像https://www.iloveimg.com/crop-image这样的 GUI ,它有一个可以移动到我想要的任何地方的矩形:

爱洛威

看到https://www.iloveimg.com/crop-image将 GIF 裁剪成一个新的动画。而使用 Python 的图像裁剪仅裁剪 GIF 的第一帧。

我可以使用的一些模块是:

标签: pythonpython-3.xuser-interfacecropgif

解决方案


在阅读了一些教程后,我想出了这个解决方案:

import numpy as np
import matplotlib.pyplot as plt

from PIL import Image, ImageSequence
from matplotlib.widgets import RectangleSelector

class ImageCutter:
    def __init__(self, file):
        self.file = file
        self.img = Image.open(file)
        self.frames = [np.array(frame.copy().convert("RGB"))
                        for frame in ImageSequence.Iterator(self.img)]

        self.pos = np.array([0,0,0,0])


    def crop(self):
        self.pos = self.pos.astype(int)
        self.cropped_imgs =  [frame[self.pos[1]:self.pos[3], self.pos[0]:self.pos[2]]
                for frame in self.frames]
        self.save()

    def save(self):
        self.imgs_pil = [Image.fromarray(np.uint8(img))
                         for img in self.cropped_imgs]
        self.imgs_pil[0].save(self.file+"_cropped.gif",
                     save_all=True,
                     append_images=self.imgs_pil[1:],
                     duration=16,
                     loop=0)


data = ImageCutter("final.gif")

fig, ax = plt.subplots(1)
ax.axis("off")

plt.imshow(data.frames[0])

def onselect(eclick, erelease):
    "eclick and erelease are matplotlib events at press and release."
    data.pos = np.array([eclick.xdata, eclick.ydata, erelease.xdata, erelease.ydata])

def onrelease(event):
    data.crop()

cid = fig.canvas.mpl_connect('button_release_event', onrelease)
RS = RectangleSelector(ax, onselect, drawtype='box')

你把你的文件名放在一个ImageCutter实例中,它会绘制第一帧,让你用鼠标选择一个框,它定义了要裁剪的区域。定义区域后,单击图像中的某个位置,程序会将裁剪后的 gif 保存在您的工作文件夹中。

然后,您可以使用自己的而不是小部件Rectangle


推荐阅读