【问题标题】:How to write videos with half of duration using OpenCV?如何使用 OpenCV 编写时长减半的视频?
【发布时间】:2023-01-05 22:12:28
【问题描述】:
我有一个 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}")
【问题讨论】:
标签:
python
python-3.x
opencv
【解决方案1】:
从捕获中读取帧,跟踪您已读取的帧数,并仅写入第 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
for frame_num in count(0):
ret, frame = in_video.read()
if not ret: # out of frames
break
if frame_num % 2 == 0:
out_video.write(frame)
frames_written += 1
print(f"{frames_written=}")
【解决方案2】:
..................................................... ..................................................... ..................................................... ..................................................... ...................................