opencv3 + python 视频 与 帧/图像的相互转换和提取

1. 从视频中提取帧/图像

import cv2
import os
#要提取视频的文件名,隐藏后缀
sourceFileName='myvideo'
#在这里把后缀接上
video_path = os.path.join("", "data", sourceFileName+'.avi')
times=0
#提取视频的频率,每1帧提取一个
frameFrequency=1
#输出图片到当前目录vedio文件夹下
outPutDirName='vedio/'+sourceFileName+'/'
if not os.path.exists(outPutDirName):
    #如果文件目录不存在则创建目录
    os.makedirs(outPutDirName) 
camera = cv2.VideoCapture(video_path)
while True:
    times+=1
    res, image = camera.read()
    if not res:
        print('not res , not image')
        break
    if times%frameFrequency==0:
        cv2.imwrite(outPutDirName + str(times)+'.jpg', image)
        print(outPutDirName + str(times)+'.jpg')
print('图片提取结束')
camera.release()

2. 将帧/图片 转换 是视频

import os
import cv2
import numpy as np
 
path = os.path.join("", "vedio",'SR-images', 'bigjpg')
filelist = os.listdir(path)

img = cv2.imread(path+'/'+'1.jpg')
print(img.shape)   # 2216, 2928, 3 
   
fps = 24 #视频每秒24帧
size = (img.shape[1], img.shape[0]) #需要转为视频的图片的尺寸
video_dir = "./data/big.avi"

fourcc = cv2.VideoWriter_fourcc('M','J','P','G') #opencv3.0
videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, size)

for i in range(1, len(filelist), 1):
    im_name = path +'/'+ str(i)+ '.jpg'
    frame = cv2.imread(im_name)
    videoWriter.write(frame)
    print (im_name)

videoWriter.release()
print ('finish')

 

你可能感兴趣的:(图像处理)