opencv—python语言视频与图片之间的转化
(1)实现视频拆分成单帧图片的功能
#/usr/bin/env python
import cv2
vc=cv2.VideoCapture("MVI_1287.mp4")
c=1
if vc.isOpened():
rval,frame=vc.read()
else:
rval=False
while rval:
rval,frame=vc.read()
cv2.imwrite('v_p/'+str(c)+'.jpg',frame)
c=c+1
cv2.waitKey(1)
vc.release()
(2)多张图片串成一个完整的视频,两种写法
第一种方法:
# /usr/bin/env python
import cv2
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
import os
img_root = "v_p/"
# Edit each frame's appearing time!
fps = 100
fourcc = VideoWriter_fourcc(*"MJPG")
#此处的图片size设置一定要和原图的大小相一致,否则视频无法输出
videoWriter = cv2.VideoWriter("1.avi", fourcc, fps, (1920, 1080))
im_names = os.listdir(img_root)
for im_name in range(len(im_names)):
frame = cv2.imread(img_root + str(im_name) + '.jpg')
print(im_name)
print(videoWriter.write(frame))
videoWriter.release()
第二种方法:
import cv2
fps = 50
#尺寸必须与与原图一样,不然无法转换为视频
size = (1920, 1080)
videowriter = cv2.VideoWriter("a.avi", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, size)
for i in range(1, 200):
img = cv2.imread('v_p/'+str(i)+'.jpg')
videowriter.write(img)
videowriter.release()