利用opencv-python实现视频转图片, 和图片转视频互转

关键点
视频–>图片
cap = cv2.VideoCapture(video_path)
success, frame = cap.read()
图片–>视频
video = cv2.VideoWriter(videoPath, fourcc, fps, size)
video.write(img)

完整代码

import cv2
import os
import shutil

def video2imgs(videoPath, imgPath, interval=1):
    if not os.path.exists(imgPath):
        os.makedirs(imgPath)
    else:
        shutil.rmtree(imgPath)
        os.makedirs(imgPath)
        print('path of %s already exist and rebuild!' % imgPath)
    
    cap = cv2.VideoCapture(videoPath)
    
    judge = cap.isOpened() #judge whether video can be opened
    print(judge)
    
    i = 0
    while True:
        success, frame = cap.read()
        if success:
            i += 1
            if i % interval == 0:
                #create the save path of img
                img_name = str(i) + '.jpg'
                img_path = os.path.join(imgPath, img_name)

                cv2.imwrite(img_path, frame)
                print('image of %s is saved!' % img_name)
        else:
            print('video is all read!')
            break
    
    cap.release()

def imgs2video(imgPath, videoPath):
    if not videoPath.endswith('.mp4'):
        print('Warning: the videoPath is not valid, please correct it which ends with \'.mp4\'')
        return 0
    
    #get the all properties of cap
    #cap = cv2.VideoCapture(videoPath)
    # height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    # width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    # fps = cap.get(cv2.CAP_PROP_FPS)
    # total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    
    #get imgs url
    filelist = os.listdir(imgPath)
    img_url = [os.path.join(imgPath, file) for file in filelist]
    
    #set the properties of video
    ImgSizeInfo = cv2.imread(img_url[0]).shape #height, width
    size = (ImgSizeInfo[1], ImgSizeInfo[0]) #width, height
    fps = 15
    fourcc = cv2.VideoWriter_fourcc(*'XVID') #.mp4

    video = cv2.VideoWriter(videoPath, fourcc, fps, size)
    # VideoWriter 中指定的尺寸要和 write() 中写进去的一样,不然视频会存储失败
    for url in img_url:
        if url.endswith('.jpg') or url.endswith('.JPG'):
            img = cv2.imread(url)
            video.write(img)
    print('the video has been maked successfully!')
    video.release()

if __name__ == '__main__':
    video_path = './read.mp4'
    imgs_path = './imgs'
    video_name = './write.mp4'

    video2imgs(video_path, imgs_path, 15)
    input('Now starting to use imgs transfer to video......')
    imgs2video(imgs_path, video_name)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值