如何将MKV字节读取为视频? [英] How to read MKV bytes as video?

查看:261
本文介绍了如何将MKV字节读取为视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在接收MKV视频片段(以字节为单位).我需要将其第一帧用于以后的处理,而无需将视频保存在磁盘中.对于图像的类似问题,我使用OpenCV或PIL,并且一切正常,但是,我无法对视频数据执行相同的操作.关于如何将字节中的视频读取到内存对象的任何技巧,我可以将它们用于以后使用OpenCV或其他库进行处理?

I am receiving fragment of MKV video in bytes. I need to take 1st frame of it for later processing without saving video in disk. For similar problem with image I use OpenCV or PIL and everything works fine, however, I am not able to do the same with video data. Any tips how to read video from bytes to memory object that I could use for later processing with OpenCV or some other library?

推荐答案

由于我没有您的bytes缓冲区,因此我使用ffmpeg创建了一个MKV视频文件,如下所示:

As I don't have your bytes buffer, I just created an MKV video file with ffmpeg like this:

ffmpeg -i SomeVideo.avi -f matroska -vcodec libx264 video.mkv

然后我将imageio安装为:

pip install imageio

然后,我将整个MKV视频加载到内存中,因此我所看到的东西必须与存储在变量content中的bytes对象几乎相同:

Then I loaded the entire MKV video into memory so I have something that must look pretty much the same as the bytes object you receive stored in my variable content:

import imageio

# Get bytes of MKV video
with open('video.mkv', 'rb') as file: 
    content = file.read()

现在,我应该被设置为与您一样的外观.仅供参考,content的前几个字节如下:

Now I should be set up and looking the same as you. Just for reference, the first few bytes of content look like this:

b'\x1aE\xdf\xa3\x01\x00\x00\x00\x00\x00\x00#B\x86\x81\x01B\xf7\x81\x01'

所以,让我们继续.

# Wrap the content in a BytesIO and get an ffmpeg reader to read it 
vid = imageio.get_reader(BytesIO(content),  'ffmpeg')

我现在可以像这样打印每帧的均值:

I can now print the mean of each frame like this:

for num, image in enumerate(vid.iter_data()): 
    print(image.mean())

或者获取元数据并像这样打印它:

Or get the metadata and print it like this:

metadata = vid.get_meta_data()                                                             

print(metadata)

{'plugin': 'ffmpeg',
 'nframes': 750,
 'ffmpeg_version': '4.1 built with Apple LLVM version 10.0.0 (clang-1000.11.45.5)',
 'fps': 25.0,
 'source_size': (1280, 720),
 'size': (1280, 720),
 'duration': 30.0}

关键字:Python,视频,帧,单个帧,FFmpeg,imageio,单帧,BytesIO,字节,MKV,Matroska.

Keywords: Python, video, frame, individual frame, FFmpeg, imageio, single frame, BytesIO, bytes, MKV, Matroska.

这篇关于如何将MKV字节读取为视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆