#zhanghu 2020-2-26
#今天朋友让做一个小工具,修改图的RGB值 ,变成一个动态图或视频,通过百度学习了一波,代码如下
import os
from PIL import Image
import imageio
#1 生成线性集合
def z_createLine(Rng):
RTList=[]
tns=(Rng/127)
for index in range(256):
v=(index+ (127-abs(127-index))*tns)
#print(v)
RTList.append(int(v))
return RTList
#2 修改RGB 中 B的值保存为新的图
# oldimgname:输入的原始的图片名
# rng :线性波动值
# newimgname: 生成新的图片名
def z_newImage(oldimgname,rng,newimgname):
#
RGBLineList=z_createLine(rng)
curpath = os.path.dirname(os.path.realpath(__file__)) # 当前文件路径
imgpath = os.path.join(curpath, oldimgname)
#im = Image.open('C:\\Users\\msi\\Desktop\\20200226115734.jpg')
im = Image.open(imgpath)
width = im.size[0]
height = im.size[1]
im = im.convert('RGB')
newimg = Image.new("RGB",(width,height))#创建图片
for x in range(width):
for y in range(height):
r, g, b = im.getpixel((x,y))
rgb = (r, g, RGBLineList[b]) #修改B值
newimg.putpixel((x,y),rgb)
newimg.save(newimgname)
#3 生成系列图
#oldimgname 输入的原始的图片名
#minV 负差值
#maxV 正差值
#mstep 步长
def createImgSr(oldimgname,minV=-100,maxV=100,mstep=10):
imageInc=0
curpath = os.path.dirname(os.path.realpath(__file__))
for index in range(minV,maxV,mstep):
print("save imageing......"+str(imageInc))
newimgname= str(imageInc)+".jpg"
newimgpath = os.path.join(curpath, newimgname)
z_newImage(oldimgname,index,newimgpath)
imageInc+=1
print("save image complete")
#4 系列图合成视频
# 安装imageio支持: pip install imageio
# param image_list: 这个列表用于存放生成动图的图片
# param gif_name: 字符串,所生成gif文件名,带.gif后缀
# param duration: 图像间隔时间
# return:
def create_gif(image_list, gif_name, duration = 0.1):
frames = []
for image_name in image_list:
frames.append(imageio.imread(image_name))
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
return
#---------------main------------------
if __name__ == '__main__':
createImgSr("20200226115734.jpg")
curpath = os.path.dirname(os.path.realpath(__file__))
imagelist=[]
for index in range(20):
imagelist.append(os.path.join(curpath,str(index)+".jpg"))
create_gif(imagelist,os.path.join(curpath,"test_gif.gif"),0.05)
print("scripte complete!...................")