首先,我要非常感谢微信公众号"菜鸟学Python"的作者,是他分享了用python做一个缩放自如的圣诞老人的想法及程序。
我按照作者分享的程序整理了一下,做了一个缩放自如的鸣人,这是我的源码,还请大家批评指正。
import os
import cv2
import numpy as np
import imageio
pic_path = 'C:/Users/ch/Desktop/luo/mingren.jpg'#原图路径
res_path = 'C:/Users/ch/Desktop/luo/li/'#缩放图存放路径
save_path = 'C:/Users/ch/Desktop/luo/ta/'#缩放图与空白板融合的存放路径
image = cv2.imread(pic_path)
#缩放图片从原图的1/30到39/30
for i in range(1, 40, 1):
img = cv2.resize(image, (0, 0), fx=i/30, fy=i/30)
cv2.imwrite(res_path+str(i)+'.jpg', img)
#根据最大的一张图片的高宽设计空白板的高宽
max = len(os.listdir(res_path))
image = cv2.imread(res_path+str(max)+'.jpg')
blankh,blankw = image.shape[0:2]
#将每张缩放的图片的底边中心与空白板底边中心重合
#并把缩放图片的像素值替换掉其覆盖的空白板区域像素值
def img_resize_and_merge(image):
blank = np.ones((blankh,blankw),dtype=np.uint8) * 255
ret = cv2.cvtColor(blank,cv2.COLOR_GRAY2BGR)
h = image.shape[0]
w = image.shape[1]
print(h,w)
exit()
halfw = w//2
centerw = blankw//2
for i in range(blankh):
for j in range(blankw):
if i >= blankh-h and j >= centerw-halfw and j < centerw+halfw:
for k in range(3):
ret[i,j,k] = image[h-blankh+i, j-centerw+halfw, k]
else:
for k in range(3):
ret[i,j,k] = 255
return ret
path = os.listdir(res_path)
for name in path:
path1 = os.path.join(res_path, name)
image1 = cv2.imread(path1)
ret = img_resize_and_merge(image1)
p = name.split('.')[0]
cv2.imwrite(save_path+str(p)+'.jpg',ret)
#按照1-39的顺序依次读取图片
list1 = []
imglist = os.listdir(save_path)
for a in imglist:
b = a.split('.')[0]
list1.append(int(b))
list1.sort()
list2 = []
for i in list1:
list2.append(os.path.join(save_path, str(i)+'.jpg'))
giflist = [imageio.imread(img) for img in list2]
imageio.mimwrite(save_path+'gif.gif', giflist, duration=0.15)#参数duration表示画面切换间隔,单位为秒
这是原图:
这是实现的效果图: