赞
踩
之前写了一个转gif格式的代码= = 。
- import os
- import cv2
- from PIL import Image
-
- def to_gif(video_path,save_path,name,start,time,timeF=1,end=-9999,ratio = 1,loop=0):
- '''
- parameter:
- video_path:视频路径
- save_path:gif保存路径
- name:保存gif的名字
- start:希望开始的时间
- end:希望结束的时间
- time:图片切换的时间
- timeF:隔多久拆帧,默认为1
- ratio:缩放比率,默认为1,原图大小
- loop:播放模式,默认为0,循环播放,1为只播放一次
- return:
- None
-
- '''
- capture = cv2.VideoCapture(video_path) #生成视频读取对象
- width = int(capture.get(3)) #获取视频的长度
- height = int(capture.get(4)) #获取视频的宽度
- fps = int(capture.get(5)) #获取视频的帧速率
- number = int(capture.get(7)) #获取视频的总帧数
- times = 0
- img_list = [] #构建用于存放帧数组的空列表
-
- while 1:
- ret,frame = capture.read() #读取视频
- if not ret:
- break
- if end == -9999:
- frame = cv2.resize(frame,(int(width*ratio),int(height*ratio))) #图像缩放
- frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) #数组转为PIL image
- img_list.append(frame) #列表中添加数组
-
- else:
- if start >= end:
- raise Exception('Starting time must be samller than ending time!')
- if int(start*fps) < times < int(end*fps):
- if (times % timeF == 0):
- frame = cv2.resize(frame,(int(width*ratio),int(height*ratio)))
- frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
- img_list.append(frame)
- times += 1
- img_list[0].save(os.path.join(save_path,'{}.gif'.format(name)),save_all=True, append_images = img_list,duration=time*timeF, loop=0) #合成gif
- capture.release()
- return
-
- if __name__ == '__main__':
- video_path = '视频路径'
- save_path = 'gif存储路径'
- name = 're1'
- start = 1
- end = 6
- time = 1
- to_gif(video_path,save_path,name,start,end,time,ratio = 0.15)
代码经过调试了滴,可以直接用~
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。