OpenCV-Python视频读取和文件保存

视频读取

opencv中使用cv2.VideoCapture()读取本机摄像头或者是读取本地视频文件,当其参数是0时,可以读取摄像头;当其参数时本地视频文件时,就是读取本地视频。

下面是具体代码,使用判断是否读取到视频帧来来显示,从而不至于读完视频报错。

代码示例:

# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2
 
 
def read_video(video_path: str):
    """
    OpenCV读视频小工具,解决视频读完报错的问题
    :param video_path: 输入需要读取的视频文件路径
    :return: 没有返回值
    """
    print('视频路径:', video_path)
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        # get a frame
        ret, frame = cap.read()
 
        cv2.imshow("capture", frame)
 
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('视频读完!')
    cap.release()
    cv2.destroyAllWindows()
 
 
if __name__ == '__main__':
    path = r'D:\multi_insect_videos\multi_object00.mp4'
    read_video(path)

视频保存

保存视频时,使用cv2.VideoWriter('images/video_save.mp4', fourcc, fps, (int(w), int(h)), True)函数。分别对应保存的视频文件名,编码格式,帧数,视频分辨率,是否彩色图像。

视频编码格式,常见的有两种,1、mp4格式;2、avi格式。

fourcc = cv.VideoWriter_fourcc(*'XVID')
fourcc = cv.VideoWriter_fourcc(*'mp4v')

示例代码是重新保存一下读取的视频:

# -*-coding:utf-8-*-
"""
File Name: video_operation.py
Program IDE: PyCharm
Date: 21:10
Create File By Author: Hong
"""
import cv2 as cv
import numpy as np


def read_video(video_path: str):
    cap = cv.VideoCapture(video_path)

    # 获取视频帧的宽和高
    w = cap.get(cv.CAP_PROP_FRAME_WIDTH)
    h = cap.get(cv.CAP_PROP_FRAME_HEIGHT)

    # 获取视频总帧数和fps
    count = cap.get(cv.CAP_PROP_FRAME_COUNT)
    fps = cap.get(cv.CAP_PROP_FPS)

    print('w: {}, h: {}, count: {}, fps: {}'.format(w, h, count, fps))

    # 视频保存
    # fourcc = cv.VideoWriter_fourcc('P', 'I', 'M', '1')
    # fourcc = cv.VideoWriter_fourcc(*'XVID')
    # 视频编码格式
    fourcc = cv.VideoWriter_fourcc(*'mp4v')

    out = cv.VideoWriter('images/video_save.mp4', fourcc, fps, (int(w), int(h)), True)

    while cap.isOpened():
        ret, frame = cap.read()
        # 调用本地摄像头时,需要左右翻转一下,若是视频文件则不需要翻转
        # frame = cv.flip(frame, 1)
        if not ret:
            break
        cv.imshow('frame', frame)
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        # 写入视频
        out.write(hsv)
        cv.imshow('hsv', hsv)

        c = cv.waitKey(1)
        if c == 27 or 0xFF == ord('q'):
            break

    cap.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    path = 'images/guangzhou.mp4'
    read_video(path)

更多计算机视觉内容,请关注微信公众号获取 “AI与计算机视觉”

你可能感兴趣的:(OpenCV-Python视频读取和文件保存)