图像视频互转python 实现

备份下,总是用。
python-opencv实现

视频转图片

采样间隔可调

# coding:utf-8
# Copyright@hitzym
# video2img
# Dec,7,2017
import cv2
vc=cv2.VideoCapture("~/video.mp4")
c=1  
if vc.isOpened():  
    rval,frame=vc.read()  
else:  
    rval=False  
while rval:  
    rval,frame=vc.read()
    rows, cols, channel = frame.shape
    # frame2=cv2.resize(frame,(cols/3,rows/3),fx=0,fy=0,interpolation=cv2.INTER_AREA)
    if ( c%5 == 0):                            #every 5 fps write frame to img
        cv2.imwrite(('./yourImgPath/'+str(c)+'.jpg'),frame)
        # cropped001 = frame2[0:300,300:600]   #y change from 0 to 300 x change from 300 to 600
        # cv2.imwrite('./cropped/'+str(c)+'_001.jpg',cropped001)
    c=c+1  
    cv2.waitKey(1)  
vc.release()  

图片转视频

#coding:utf-8
import cv2
import os
import numpy as np
from PIL import Image, ImageDraw,ImageFont
fps = 2
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video_writer = cv2.VideoWriter(filename='./result.avi', fourcc=fourcc, fps=fps, frameSize=(1856,1056))
for i in range(0,6000):
    p = i
    # print(str(p)+'.png'+'233333')
    if os.path.exists('yourImgPath/'+str(p)+'.jpg'):    #判断图片是否存在
        img = cv2.imread(filename='yourImgPath/'+str(p)+'.jpg')
        cv2.waitKey(100)
        video_writer.write(img)
        print(str(p) + '.jpg' + ' done!')
video_writer.release()

恳请各位看官斧正!~
鞠躬!

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