使用PyAV将视频直接读取到Numpy中(无迭代)

2024-05-18 11:41:02 发布

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

是否可以使用PyAV将视频直接读取到3D Numpy中?目前,我正在每个帧中循环:

i = 0
container = av.open('myvideo.avi')
for frame in container.decode(video=0):
    if i == 0: V = np.array(frame.to_ndarray(format='gray'))
    else: V = np.dstack((V, np.array(frame.to_ndarray(format='gray'))))
    i += 1

第一帧定义2D Numpy数组(i=0);每个后续帧(i>;0)使用np.dstack堆叠到第一个数组上。理想情况下,我希望将整个视频一次读入一个由灰度帧组成的3D Numpy阵列


Tags: tonumpyformat视频containernp数组open
1条回答
网友
1楼 · 发布于 2024-05-18 11:41:02

我无法使用PyAV找到解决方案,而是使用ffmpeg-python

ffmpeg-python是类似于PyAV的FFmpeg的Pythonic绑定

代码一次将整个视频读取到灰度帧的3D Numpy数组中

该解决方案执行以下步骤:

  • 创建输入视频文件(用于测试)
  • 使用“probe”获取视频文件的分辨率
  • 将视频流到字节数组中
  • 将字节数组重塑为n x height x widthnumpy数组
  • 显示第一帧(用于测试)

以下是代码(请阅读注释):

import ffmpeg
import numpy as np
from PIL import Image

in_filename = 'in.avi'

"""Build synthetic video, for testing begins:"""
# ffmpeg -y -r 10 -f lavfi -i testsrc=size=160x120:rate=1 -c:v libx264 -t 5 in.mp4
width, height = 160, 120

(
    ffmpeg
    .input('testsrc=size={}x{}:rate=1'.format(width, height), r=10, f='lavfi')
    .output(in_filename, vcodec='libx264', t=5)
    .overwrite_output()
    .run()
)
"""Build synthetic video ends"""


# Use ffprobe to get video frames resolution
p = ffmpeg.probe(in_filename, select_streams='v');
width = p['streams'][0]['width']
height = p['streams'][0]['height']

# https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md
# Stream the entire video as one large array of bytes
in_bytes, _ = (
    ffmpeg
    .input(in_filename)
    .video # Video only (no audio).
    .output('pipe:', format='rawvideo', pix_fmt='gray')  # Set the output format to raw video in 8 bit grayscale
    .run(capture_stdout=True)
)

n_frames = len(in_bytes) // (height*width)  # Compute the number of frames.
frames = np.frombuffer(in_bytes, np.uint8).reshape(n_frames, height, width) # Reshape buffer to array of n_frames frames (shape of each frame is (height, width)).

im = Image.fromarray(frames[0, :, :])  # Convert first frame to image object
im.show()  # Display the image

输出:
enter image description here

相关问题 更多 >