python-3.x 如何使用OpenCV编写持续时间只有一半的视频?

3xiyfsfu  于 2023-01-06  发布在  Python
关注(0)|答案(2)|浏览(136)

我有一个mp4/avi视频,持续时间为10分钟,FPS为30。我想将持续时间减少到5分钟,但FPS仍为30。这意味着新视频将减少一半的帧(例如,f0 f2 f4与原始视频f0 f1 f2 f3 f4相比)。我如何在opencv上做到这一点?这是当前代码,以获得视频的持续时间和FPS。

# import module
import cv2
import datetime
  
# create video capture object
data = cv2.VideoCapture('C:/Users/Asus/Documents/videoDuration.mp4')
  
# count the number of frames
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = data.get(cv2.CAP_PROP_FPS)
  
# calculate duration of the video
seconds = round(frames / fps)
video_time = datetime.timedelta(seconds=seconds)
print(f"duration in seconds: {seconds}")
print(f"video time: {video_time}")
ar7v8xwq

ar7v8xwq1#

从捕获中读取帧,记录已读取的帧数,并每隔N帧写入一次,如下所示:

from itertools import count

import cv2

in_video = cv2.VideoCapture("example.mp4")
frames = int(in_video.get(cv2.CAP_PROP_FRAME_COUNT))
fps = in_video.get(cv2.CAP_PROP_FPS)
w = int(in_video.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(in_video.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{frames=}, {fps=}, {w=}, {h=}")
out_video = cv2.VideoWriter("out.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
frames_written = 0
every_nth = 2

for frame_num in count(0):
    ret, frame = in_video.read()
    if not ret:  # out of frames
        break
    if frame_num % every_nth == 0:
        out_video.write(frame)
        frames_written += 1
print(f"{frames_written=}")
hiz5n14c

hiz5n14c2#

此代码将逐帧读取输入视频文件,并每隔一帧将其写入输出视频文件。因此,输出视频的帧数将是输入视频的一半,持续时间也将是输入视频的一半。

import cv2 

# Open the input video file
cap = cv2.VideoCapture("input.mp4")

# Check if the video is opened successfully
if not cap.isOpened():
    print("Error opening video file")

# Read the video's width, height, and frame rate
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))

# Create the output video file
out = cv2.VideoWriter("output.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))

# Read the frames from the input video and write them to the output video,
# skipping every other frame
while True:
    ret, frame = cap.read()
    if not ret:
        break
    cap.grab()
    out.write(frame)

# Release the video capture and video write objects
cap.release()
out.release()

相关问题