简体   繁体   中英

Reading a video directly into Numpy with PyAV (no iterations)

Is it possible to read a video directly into a 3D Numpy with PyAV? Currently, I am looping through each frame:

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

The first frame defines a 2D Numpy array (i=0); each subsequent frame (i>0) is stacked onto the first array using np.dstack . Ideally, I would like to read the entire video into a 3D Numpy array of grayscale frames, all at once.

I couldn't find a solution using PyAV, and uses ffmpeg-python instead.

ffmpeg-python is a Pythonic binding for FFmpeg like PyAV .

The code reads the entire video into a 3D Numpy array of grayscale frames, all at once.

The solution performs the following steps:

  • Creates an input video file (for testing).
  • Gets resolution of video file using "probe".
  • Streams the video into byte array.
  • Reshape the byte array into nx height x width numpy array.
  • Displays the first frame (for testing).

Here is the code (please read the comments):

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

Output:
在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM