gpt4 book ai didi

python - cv2中的可变fps(每秒帧数)

转载 作者:行者123 更新时间:2023-12-02 01:27:58 25 4
gpt4 key购买 nike

我使用 cv2 从我拥有的不同帧创建视频。创建视频时,我无法更改 fps(每秒帧数)。我希望视频开始时速度慢但结束时速度快,这意味着开始时 fps 小但结束时 fps 大。但是,当我实例化 cv2.VideoWriter 时,我无法再更改 fps。我该怎么办?

可复制代码

import numpy as np
import cv2, os
import matplotlib

image_size = 200
def create_image_array(image_size):
image_array = np.random.randn(image_size, image_size)
row = np.random.randint(0, image_size)
image_array[row, :] = 100
return image_array

frame_numbers = 200
for i in range(frame_numbers):
image_array = create_image_array(image_size)
matplotlib.image.imsave(f'./shots/frame_{i:03d}.png', image_array)

def make_a_video(shots_folder, video_path):

shots_folder = 'shots'
fps = 25
images = [img for img in os.listdir(shots_folder) if img.endswith(".png")]

images = sorted(images)[:]
frame = cv2.imread(os.path.join(shots_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))

for image in images:
video.write(cv2.imread(os.path.join(shots_folder, image)))

cv2.destroyAllWindows()
video.release()

shots_folder = 'shots'
video_path = 'video.mp4'
make_a_video(shots_folder, video_path)

最佳答案

将其想象成将一个视频复制到另一个视频。在执行此操作时,您实际上不想更改输出帧速率,而是更改输入帧速率。这是一个非常基本的示例,说明如何在写入恒定帧速率的流时连续更改读取帧速率。

示例生成200帧的样本视频,写入320帧的视频。前 100 帧以 5 fps 读取,接下来的 100 帧以从 5 到 25 fps 的递增速率读取,最后 120 帧以 25 fps 读取。

import math
import numpy as np
import cv2

image_size = 200
src_fps = 25
dst_fps = 25


# create sample frame with four rotating balls
def create_sample_frame(size, frame_no, fps):
img = np.zeros((size, size, 3), dtype=np.uint8)
ctr = size // 2

for i in range(1, 5):
phi = -frame_no / fps * i
r = size * (0.5 - 0.1 * i)
cv2.circle(img, (round(math.sin(phi) * r + ctr), round(math.cos(phi) * r + ctr)), size // 30, (0, 255, 0), -1)

return img


frames = [create_sample_frame(image_size, i, src_fps) for i in range(200)]
height, width, layers = frames[0].shape
video = cv2.VideoWriter('video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), dst_fps, (width, height))

# ramp array with number of destination frames, start fps of source, end fps of source
fps_ramp = [[100, 5, 5], [100, 5, 25], [120, 25, 25]]

src_pos = 0
dst_pos = 0

for n, start_src_fps, end_src_fps in fps_ramp:
for i in range(n):
print(f"writing source frame {int(src_pos)} to destination frame {dst_pos}")
video.write(frames[round(src_pos)])
dst_pos += 1
cur_fps = (end_src_fps - start_src_fps) * (i / n) + start_src_fps
src_pos += cur_fps / src_fps

video.release()

结果:

enter image description here

关于python - cv2中的可变fps(每秒帧数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73998961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com