📜  保存视频 cv2 - Python (1)

📅  最后修改于: 2023-12-03 14:50:00.182000             🧑  作者: Mango

保存视频 cv2 - Python

在Python语言中使用OpenCV库(cv2)可以实现许多图像和视频处理的任务。在视频处理过程中,保存视频是一项非常重要的任务。在本文中,我们将介绍如何使用cv2来保存一段视频。

准备工作

在保存视频之前,我们需要先安装并导入cv2库,并加载要保存的视频文件。请注意,我们需要确保已将视频文件放置在正确的位置,并使用正确的文件名和扩展名加载它。

import cv2

# Load video file
video_capture = cv2.VideoCapture('video.mp4')
如何保存视频

一旦视频文件被加载到内存中,我们可以开始保存视频了。为了保存视频,我们需要创建一个VideoWriter对象,并指定输出的视频文件的路径、编解码器、帧速率和帧大小。

# Get video properties
fps = int(video_capture.get(cv2.CAP_PROP_FPS))
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

在创建VideoWriter对象之后,我们可以开始从input视频对象读取每一帧,并将其保存到output视频对象中。

while True:
    # Read frame from video
    ret, frame = video_capture.read()
    
    # Check if frame was successfully read
    if not ret:
        break
    
    # Write frame to output video
    out.write(frame)
    
    # Display frame
    cv2.imshow('frame', frame)
    
    # Exit on 'q' key press
    if cv2.waitKey(1) == ord('q'):
        break

要退出保存并退出程序,请按“q”键。一旦视频保存成功,我们可以释放资源并关闭所有打开的窗口。

# Release resources
video_capture.release()
out.release()
cv2.destroyAllWindows()
完整代码演示
import cv2

# Load video file
video_capture = cv2.VideoCapture('video.mp4')

# Get video properties
fps = int(video_capture.get(cv2.CAP_PROP_FPS))
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

while True:
    # Read frame from video
    ret, frame = video_capture.read()
    
    # Check if frame was successfully read
    if not ret:
        break
    
    # Write frame to output video
    out.write(frame)
    
    # Display frame
    cv2.imshow('frame', frame)
    
    # Exit on 'q' key press
    if cv2.waitKey(1) == ord('q'):
        break

# Release resources
video_capture.release()
out.release()
cv2.destroyAllWindows()

最终输出为保存的视频文件“output.mp4”。