使用opencv-python对视频与图像进行相互转换

读取视频文件转成图像转

# 全局变量
VIDEO_PATH = './demo.mp4'  # 视频地址
EXTRACT_FOLDER = './img'  # 存放帧图片的位置
EXTRACT_FREQUENCY = 10  # 帧提取频率


def extract_frames(video_path, dst_folder, index):
    # 主操作
    import cv2
    video = cv2.VideoCapture()
    if not video.open(video_path):
        print("can not open the video")
        exit(1)
    count = 1
    while True:
        _, frame = video.read()
        if frame is None:
            break
        if count % EXTRACT_FREQUENCY == 0:
            save_path = "{}/{:>03d}.jpg".format(dst_folder, index)
            cv2.imwrite(save_path, frame)
            index += 1
        count += 1
    video.release()
    # 打印出所提取帧的总数
    print("Totally save {:d} pics".format(index - 1))


def main():
    # 递归删除之前存放帧图片的文件夹,并新建一个
    import shutil
    try:
        shutil.rmtree(EXTRACT_FOLDER)
    except OSError:
        pass
    import os
    os.mkdir(EXTRACT_FOLDER)
    # 抽取帧图片,并保存到指定路径
    extract_frames(VIDEO_PATH, EXTRACT_FOLDER, 1)


if __name__ == '__main__':
    main()
  1. 程序中cv2.VideoCapture参数可以为0,表示打开笔记本的内置摄像头;参数如果为视频文件路径则打开视频;如果参数为空,则需要使用open方法来打开视频
  2. retval, frame=video.read()
    vedio.read()按帧读取视频, retval,frame是read的两个返回值。其中,retval是布尔值,如果读取到帧则返回true,如果读取到视频末尾则返回false,程序中也可以使用retval进行判断是否到视频文件末尾;

将图像保存为视频文件

import cv2
import glob
import os
from datetime import datetime


def frames_to_video(fps, save_path, frames_path):
    max_index = len(os.listdir(frames_path))
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    imgs = glob.glob(frames_path + "/*.jpg")
    shape_i = cv2.imread(imgs[0]).shape
    videoWriter = cv2.VideoWriter(save_path, fourcc, fps, (shape_i[1], shape_i[0]))

    for i in range(max_index):
        if os.path.isfile("%s/%d.jpg" % (frames_path, i)):
            frame = cv2.imread("%s/%d.jpg" % (frames_path, i))
            videoWriter.write(frame)
    videoWriter.release()
    return


if __name__ == '__main__':
    t1 = datetime.now()
    frames_to_video(25, "video.mp4", 'img/')
    t2 = datetime.now()
    print("Time cost = ", (t2 - t1))
    print("SUCCEED !!!")
  1. 程序中cv2.VideoWriter_fourcc(*‘mp4v’) 使用mp4的编码格式生成mp4文件
    当然了,也可以使用XVID替换mp4v生成avi文件。

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