如何解码视频(内存文件/字节字符串)并在python中逐帧遍历?

2024-05-16 10:47:53 发布

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

我正在使用python进行一些基本的图像处理,并希望将其扩展为逐帧处理视频

我从服务器以blob的形式获取视频-.webm encoded-,并在python中以字节字符串(b'\x1aE\xdf\xa3\xa3B\x86\x81\x01B\xf7\x81\x01B\xf2\x81\x04B\xf3\x81\x08B\x82\x88matroskaB\x87\x81\x04B\x85\x81\x02\x18S\x80g\x01\xff\xff\xff\xff\xff\xff\xff\x15I\xa9f\x99*\xd7\xb1\x83\x0fB@M\x80\x86ChromeWA\x86Chrome\x16T\xaek\xad\xae\xab\xd7\x81\x01s\xc5\x87\x04\xe8\xfc\x16\t^\x8c\x83\x81\x01\x86\x8fV_MPEG4/ISO/AVC\xe0\x88\xb0\x82\x02\x80\xba\x82\x01\xe0\x1fC\xb6u\x01\xff\xff\xff\xff\xff\xff ...)的形式获取视频

我知道有cv.VideoCapture,它几乎可以满足我的需要。问题是,我必须首先将文件写入磁盘,然后再次加载。将字符串包装(例如)到IOStream中,并将其提供给执行解码的某个函数似乎要干净得多

在python中有没有一种干净的方法可以做到这一点,或者是写入磁盘并再次加载它


Tags: 字符串视频x86形式x82x01x02xff
1条回答
网友
1楼 · 发布于 2024-05-16 10:47:53

根据thispost,您不能在内存流中使用cv.VideoCapture进行解码。
您可以通过“管道”到FFmpeg来解码流

解决方案有点复杂,写入磁盘要简单得多,而且可能是更干净的解决方案

我正在发布一个使用FFmpeg(和FFprobe)的解决方案。
FFmpeg有Python绑定,但解决方案是使用subprocess模块作为外部应用程序执行FFmpeg。
(Python绑定与FFmpeg配合使用效果良好,但与FFprobe的管道连接效果不佳)。
我使用的是Windows 10,我将ffmpeg.exeffprobe.exe放在执行文件夹中(您也可以设置执行路径)。
对于Windows,请下载最新(静态喜欢)稳定版本

我创建了一个执行以下操作的独立示例:

  • 生成合成视频,并将其保存到WebM文件(用作测试的输入)
  • 将文件作为二进制数据读入内存(将其替换为服务器上的blob)
  • 将二进制流传输到FFprobe,以查找视频分辨率。
    如果事先知道解决方案,您可以跳过此部分。
    连接FFprobe的管道使解决方案比它应有的更复杂
  • 通过管道将二进制流传输到FFmpegstdin进行解码,并从stdout管道读取解码的原始帧。
    stdin的写入是使用Python线程分块完成的。
    (使用stdinstdout代替命名管道的原因是为了Windows兼容性)

管道结构:

             Encoded          -  Decoded            
| Input WebM encoded | data        | ffmpeg  | raw frames  | reshape to |
| stream (VP9 codec) |      > | process |      > | NumPy array|
             stdin PIPE       -  stdout PIPE        -

代码如下:

import numpy as np
import cv2
import io
import subprocess as sp
import threading
import json
from functools import partial
import shlex

# Build synthetic video and read binary data into memory (for testing):
#########################################################################
width, height = 640, 480
sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=size={}x{}:rate=1 -vcodec vp9 -crf 23 -t 50 test.webm'.format(width, height)))

with open('test.webm', 'rb') as binary_file:
    in_bytes = binary_file.read()
#########################################################################


# https://stackoverflow.com/questions/5911362/pipe-large-amount-of-data-to-stdin-while-using-subprocess-popen/14026178
# https://stackoverflow.com/questions/15599639/what-is-the-perfect-counterpart-in-python-for-while-not-eof
# Write to stdin in chunks of 1024 bytes.
def writer():
    for chunk in iter(partial(stream.read, 1024), b''):
        process.stdin.write(chunk)
    try:
        process.stdin.close()
    except (BrokenPipeError):
        pass  # For unknown reason there is a Broken Pipe Error when executing FFprobe.


# Get resolution of video frames using FFprobe
# (in case resolution is know, skip this part):
################################################################################
# Open In-memory binary streams
stream = io.BytesIO(in_bytes)

process = sp.Popen(shlex.split('ffprobe -v error -i pipe: -select_streams v -print_format json -show_streams'), stdin=sp.PIPE, stdout=sp.PIPE, bufsize=10**8)

pthread = threading.Thread(target=writer)
pthread.start()

pthread.join()

in_bytes = process.stdout.read()

process.wait()

p = json.loads(in_bytes)

width = (p['streams'][0])['width']
height = (p['streams'][0])['height']
################################################################################


# Decoding the video using FFmpeg:
################################################################################
stream.seek(0)

# FFmpeg input PIPE: WebM encoded data as stream of bytes.
# FFmpeg output PIPE: decoded video frames in BGR format.
process = sp.Popen(shlex.split('ffmpeg -i pipe: -f rawvideo -pix_fmt bgr24 -an -sn pipe:'), stdin=sp.PIPE, stdout=sp.PIPE, bufsize=10**8)

thread = threading.Thread(target=writer)
thread.start()


# Read decoded video (frame by frame), and display each frame (using cv2.imshow)
while True:
    # Read raw video frame from stdout as bytes array.
    in_bytes = process.stdout.read(width * height * 3)

    if not in_bytes:
        break  # Break loop if no more bytes.

    # Transform the byte read into a NumPy array
    in_frame = (np.frombuffer(in_bytes, np.uint8).reshape([height, width, 3]))

    # Display the frame (for testing)
    cv2.imshow('in_frame', in_frame)

    if cv2.waitKey(100) & 0xFF == ord('q'):
        break

if not in_bytes:
    # Wait for thread to end only if not exit loop by pressing 'q'
    thread.join()

try:
    process.wait(1)
except (sp.TimeoutExpired):
    process.kill()  # In case 'q' is pressed.
################################################################################

cv2.destroyAllWindows()

备注:

  • 如果您遇到类似“未找到文件:ffmpeg…”的错误,请尝试使用完整路径。
    例如(在Linux中):'/usr/bin/ffmpeg -i pipe: -f rawvideo -pix_fmt bgr24 -an -sn pipe:'

相关问题 更多 >