使用Python opencv实现视频与图片的相互转换
时间:2020-10-17 10:49:48|栏目:Python代码|点击: 次
因为最近要经常转换数据集进行实验,因此记录一下。
1、视频转图片
即为将视频解析为一帧一帧的图片:
import cv2 vc=cv2.VideoCapture("/home/hqd/PycharmProjects/1/1/19.MOV") c=1 if vc.isOpened(): rval,frame=vc.read() else: rval=False while rval: rval,frame=vc.read() cv2.imwrite('/home/hqd/PycharmProjects/1/1/19/'+str(c)+'.jpg',frame) c=c+1 cv2.waitKey(1) vc.release()
2、图片转视频
即为将图片转为视频,这里采用的帧率为30帧/秒:
import cv2import os fps = 30 fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') video_writer = cv2.VideoWriter(filename='./result.avi', fourcc=fourcc, fps=fps, frameSize=(1920, 1080)) for i in range(0,6000): p = i if os.path.exists('/home/hqd/PycharmProjects/1/qqqq/'+str(p)+'.jpg'): #判断图片是否存在 img = cv2.imread(filename='/home/hqd/PycharmProjects/1/qqqq/'+str(p)+'.jpg') cv2.waitKey(100) video_writer.write(img) print(str(p) + '.jpg' + ' done!') video_writer.release()
总结