在此记录一下python实现图片转视频的方法,opencv速度还是比较块的,1300张400x400图片只花了1.5s
1. 安装Opencv包
在Python命令行输入如下命令(如果你使用的Anaconda,直接进入Anaconda Prompt键入命令即可。如果你不知道Anaconda是什么,可以参考王树义老师的文章和视频:如何安装Python运行环境Anaconda)
$ pip install opvencv-python
2. 实现代码
import os
import cv2
import numpy as np
path = \'需要调用的图片路径 例如:C:/picture/\'
filelist = os.listdir(path)
fps = 24 #视频每秒24帧
size = (640, 480) #需要转为视频的图片的尺寸
#可以使用cv2.resize()进行修改
video = cv2.VideoWriter("VideoTest1.avi", cv2.VideoWriter_fourcc(\'I\', \'4\', \'2\', \'0\'), fps, size)
#视频保存在当前目录下
for item in filelist:
if item.endswith(\'.png\'):
#找到路径中所有后缀名为.png的文件,可以更换为.jpg或其它
item = path + item
img = cv2.imread(item)
video.write(img)
video.release()
cv2.destroyAllWindows()
3. VideoWriter()函数的使用
依据OpenCV3.4.1版本文档中对VideoWriter()函数的描述,使用方法如下:
<VideoWriter object> = VideoWriter(const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
VideoWriter()的参数有filename, fourcc, fps, frameSize, isColor。下面我们就来逐个的解释:
- filename:需要生成的视频的名字
- fourcc:用于压缩框架的解码器的4位编码(four code of codec),你在这个链接里可以查找到可用的4位码(http://www.fourcc.org/codecs.php)
- fps:每秒的视频帧数(framrate persecond)
- frameSize:视频画面的尺寸(这里需要与用于合成视频的图片尺寸一致)
- isColor:如果该位值为Ture,解码器会进行颜色框架的解码,否则会使用灰度进行颜色架构(该功能仅支持在Windows系统中使用)
VideoWriter()的返回的是一个VideoWrtier类型的对象。可以继承的函数有:
retval = cv.VideoWriter_fourcc(c1, c2, c3, c4)
#构建一个可识别的fourcc码
retval = cv.VideoWriter.get(propId)
#Value for the specified property. Value 0 is returned when querying a property that is not supported by the backend used by the VideoWriter instance.
#propId: https://docs.opencv.org/3.4.1/d4/d15/group__videoio__flags__base.html#ga41c5cfa7859ae542b71b1d33bbd4d2b4
retval = cv.VideoWriter.isOpened()
#Returns true if video writer has been successfully initialized.
retval = cv.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor])
#Returns true if video writer has been successfully initialized.
None = cv.VideoWriter.release()
#No return. Close the VideoWriter.
None = cv.VideoWriter.write(image)
#向视频写入图片,无返回值
参考链接:
把图片存成视频 python: https://blog.csdn.net/jqw11/article/details/71703050
Python Code:图片和视频互相转换:https://blog.csdn.net/errors_in_life/article/details/72809580
OpenCV Documentation:https://docs.opencv.org/3.4.1/dd/d9e/classcv_1_1VideoWriter.html#a0901c353cd5ea05bba455317dab81130