python - 如何使用脚本裁剪 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 的第一帧。
我可以使用的一些模块是:
- Tkinter(最好)
- 游戏
- 枕头 / PIL
- 其他
解决方案
在阅读了一些教程后,我想出了这个解决方案:
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
推荐阅读
- mysql - 从不同的表中选择 COUNT
- javascript - 即使属性已更改,视图也不会更新
- wpf - 在 wrapPanel 中调整视图框的大小
- ios - 通过 Instagram oAuth 登录 Facebook
- python - 如何在没有扩展名的情况下复制到目录文件 - 仅在名称本身之后
- python - 为什么从终端和 Atom 调用 python 的版本不同
- django - Django - DEBUG = True 时未找到静态文件;根据文档,所有设置都是正确的
- javascript - Dojo domClass.add() 和 dojo.addClass() 的区别
- terraform - Terraform 列表需要额外的方括号
- c# - ASP.NET Core 处理方法不允许 405