如何用Python快速作出一张渐变GIF动图
步骤如下:
找到两张图片
比如一张黑白的 dcmall_grey.jpg
一张利用VGAN可视化后的彩色图像 dcmall_vgan.jpg Spectral Image Visualization Using Generative Adversarial Network
开始编程
我们需要的包如下
import numpy as np
import imageio
写一个渐变函数
def trans(start,end,n):
"""
start: the image in the first frame
end: the image that the Gif will end with
n: number of frames in this gif
"""
start = np.array(start)
end = np.array(end)
N=n-1
h,w,c = start.shape
dw = w//N
yield np.array(start)
for i in range(N-1):
start[:,i*dw:i*dw+dw,:] = end[:,i*dw:i*dw+dw,:]
yield np.array(start)
yield end
该函数会返回一系列的 numpy.ndarray
图像,用于生成一个Gif。
先读取灰度图像和彩色图像
g = imageio.imread('dcmall_grey.jpg')
c = imageio.imread('dcmall_vgan.jpg')
print(g.shape)
(305, 1280)
灰度图像变成RGB 24位灰度
g = np.stack([g]*3,2)
print(g.shape)
(305, 1280, 3)
拉伸图像 使得两张图象尺寸一致
- 注意: 其实两张图像尺寸关系并不如此,这里只是为了展示,仅当作灰度图像高度为305
彩色图像高度为 307
print(c.shape)
(307, 1280, 3)
使用 opencv 包
import cv2
g = cv2.resize(g,(1280,307),cv2.INTER_CUBIC)
print(g.shape)
(307, 1280, 3)
生成帧
series = [i for i in trans(g,c,10)]
len(series)
10
保存gif
帧间距 0.1 秒
imageio.mimsave('vgan.gif',series,duration=0.1)