python+opencv视频图像相互转换

ffmpeg缩小视频尺寸

images to video(不建议使用,生成的视频大,压缩率不够,推荐ffmpeg)

import cv2
import glob

fps = 10    #保存视频的FPS,可以适当调整

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
videoWriter = cv2.VideoWriter('saveVideo.avi',fourcc,fps,(480,360))#最后一个是保存图片的尺寸
imgs=glob.glob('D:/experiment/ViBE/image_to_video/val/*.png')
for imgname in imgs:
    frame = cv2.imread(imgname)
    videoWriter.write(frame)
videoWriter.release()

或者安装ffmpeg,参考

图像名为"in000000.jpg"等,转成视频:ffmpeg -f image2 -i in%6d.jpg -vcodec libx264 -r 25 -b 200k test.mp4

-r 25 表示每秒播放25帧

-b 200k 指定码率为200k

图片的文件名从0开始依次递增


video to images

import cv2
vc = cv2.VideoCapture('driveway-320x240.avi') #读入视频文件
c=0
rval=vc.isOpened()
#timeF = 1  #视频帧计数间隔频率
while rval:   #循环读取视频帧
    c = c + 1
    rval, frame = vc.read()
#    if(c%timeF == 0): #每隔timeF帧进行存储操作
#        cv2.imwrite('smallVideo/smallVideo'+str(c) + '.jpg', frame) #存储为图像
    if rval:
        cv2.imwrite('driveway-320x240/driveway-320x240'+str(c).zfill(8) + '.jpg', frame) #存储为图像
        cv2.waitKey(1)
    else:
        break
vc.release()

cv2.imread按BGR顺序读图片,cv2.imwrite按RGB顺序写图片。

若图片看成数组[:,:,[0,1,2]],则imread时变量存为[:,:,[2,1,0]],imwrite时[:,:,[0,1,2]],总是从后往前操作变量。

参考各类图像库的图片读写方式总结



你可能感兴趣的:(tools)