plt.savefig('image1.png', bbox_inches='tight',pad_inches = 0) 一般图片的边框是白色,可以通过将图像反转来找到图像中非空白区域的最小矩形边界坐标
from PIL import Image, ImageOps
def crop_margin(img_fileobj, out, padding=(0, 0, 0, 0)):
image = Image.open(img_fileobj).convert('RGB')
ivt_image = ImageOps.invert(image)
bbox = ivt_image.getbbox()
left = bbox[0] - padding[0]
top = bbox[1] - padding[1]
right = bbox[2] + padding[2]
bottom = bbox[3] + padding[3]
cropped_image = image.crop([left, top, right, bottom])
cropped_image.save(out)
return 如果边框是其他颜色,可以通过对比像素RGB确定需要选择的范围:
from PIL import Image
import numpy as np
def trim_frame(image):
# 获取图像矩阵
img_array = np.array(image.convert('RGB'))
ny,nx,_ = img_array.shape
# 设定边框颜色
border_color = [255, 255, 255]
# 找到不是边框颜色的第一个像素
matrix = img_array.reshape(-1,3)
mask = np.all(matrix == np.array(border_color), axis=1)
row_mask = np.all(mask.reshape(ny,nx) , axis=1)
col_mask = np.all(mask.reshape(ny,nx) , axis=0)
top, bottom = np.where(row_mask == False)[0][[0, -1]]
left, right = np.where(col_mask == False)[0][[0, -1]]
# 裁剪图像并返回
return image.crop((left, top, right, bottom))
img = Image.open('example.png')
img_trimmed = trim_frame(img)
img_trimmed.save('example_trimmed.png')from PIL import Image
import numpy as np
# 打开所有PNG图片并裁剪
frames = []
for i in range(1, 10):
filename = f"img{i}.png"
image = Image.open(filename)
trimmed = trim_frame(image)
frames.append(trimmed)
# 保存GIF动图
frames[0].save("result.gif", save_all=True, append_images=frames[1:], duration=100, loop=0) imageio库简化了GIF动态图的制作过程,可以直接读取所有PNG文件,并输出为一个GIF动态图。这是实现代码:
import imageio
# 打开所有PNG图片
frames = []
for i in range(1, 10):
filename = f"img{i}.png"
frames.append(imageio.imread(filename))
# 保存GIF动图
imageio.mimsave("result.gif", frames, duration=0.1) 除了前面提到的Pillow和imageio库,还有一些其他的库可以用于快速制作GIF动图,下面列出其中的几个: