如何用腳本裁切GIF?

2024-09-27 00:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一个脚本可以在python中裁剪gif,比如这个页面:https://www.iloveimg.com/crop-image?在

不久前,我发现了Image Cropping using Python,但问题是需要用光标绘制矩形。在

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

ILOVEIMG

请看https://www.iloveimg.com/crop-image将GIF裁剪成新的动画。并且Image Cropping using Python只裁剪GIF的第一帧。在

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

  • Tkinter(最好)
  • 游戏
  • 枕头/枕头
  • 其他

Tags: httpscropimage脚本comwww页面gif
1条回答
网友
1楼 · 发布于 2024-09-27 00:18:52

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

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,而不是小部件

相关问题 更多 >

    热门问题