如何在Python中从更新的numpy数组生成视频

2024-04-27 03:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个循环,它用float类型修改2dnumpy数组water_depth的元素。数组包含每个像素的水深,范围通常在0到1.5米之间。我想用这个不断变化的数组制作一个视频:每次迭代都可以是视频中的一个帧。我只发现this link解释了一个类似的问题,并建议使用cv2 VideoWriter。问题是我的numpy数组是一个浮点数,而不是整数。这是否意味着我需要在每次迭代中对数组进行某种预处理?在

import numpy as np

water_depth = np.zeros((500,700), dtype=float)

for i in range(1000):
    random_locations = np.random.random_integers(200,450, size=(200, 2))
    for item in random_locations:
        water_depth[item[0], item[1]] += 0.1
        #add this array to the video

Tags: innumpy元素类型for视频nprandom
1条回答
网友
1楼 · 发布于 2024-04-27 03:28:23

请注意,使用OpenCV进行视频I/O有时会很棘手。这个库并不是围绕着支持这些操作而构建的,它们只是作为一个很好的工具包含进来的。通常,OpenCV将基于ffmpeg支持而构建,您是否具有与其他人相同的编解码器来读/写视频,这在某种程度上取决于您的系统。话虽如此,以下是一个例子,让您了解您可能要做的预处理:

import numpy as np
import cv2

# initialize water image
height = 500
width = 700
water_depth = np.zeros((height, width), dtype=float)

# initialize video writer
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
fps = 30
video_filename = 'output.avi'
out = cv2.VideoWriter(video_filename, fourcc, fps, (width, height))

# new frame after each addition of water
for i in range(10):
    random_locations = np.random.random_integers(200,450, size=(200, 2))
    for item in random_locations:
        water_depth[item[0], item[1]] += 0.1
        #add this array to the video
        gray = cv2.normalize(water_depth, None, 255, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
        gray_3c = cv2.merge([gray, gray, gray])
        out.write(gray_3c)

# close out the video writer
out.release()

注意,我将迭代次数改为10次而不是1000次,只是为了确保它能正常工作。这里normalize(..., 255, 0, ...)缩放图像,使最大值为255(白色),最小值为0(黑色)。这意味着,当你的所有随机点开始点染所有东西时,它们会变成白色。然而,一旦一个点落在另一个点上,那将是最亮的——是其他所有点的两倍,所以它们会立即降为灰色。如果这不是你想要的,你必须考虑你是否有一个最大值,你的图像可能是,并假设你的图像不会改变亮度,否则。在

相关问题 更多 >