简体   繁体   English

OpenCV VideoCapture 能否接受 Python 文件,如 object?

[英]Can OpenCV VideoCapture accept a Python file-like object?

This works fine:这工作正常:

import cv2
cv2.VideoCapture('somevideo.mp4').isOpened()

> True

This throws an exception:这会引发异常:

import cv2
f = open('somevideo.mp4', 'rb')
cv2.VideoCapture(f)

> TypeError: an integer is required (got type _io.BufferedReader)

I would like the latter example to work because I have a Python file-like object that abstracts the location of the file (not a standard OS filesystem).我希望后一个示例能够工作,因为我有一个 Python 文件,类似于 object,它抽象了文件的位置(不是标准的 OS 文件系统)。

Can OpenCV be coaxed into accepting a standard python file-like object? OpenCV 是否可以被哄骗接受一个标准的 python 文件,如 object? From this exception it looks like it will only support a file descriptor or filename string.从这个异常看来,它只支持文件描述符或文件名字符串。

OpenCV is a C++ library with Python bindings auto-generated. OpenCV 是一个 C++ 库,带有自动生成的 Python 绑定。 Partly because of that, in general, the Python library is not really extensible or flexible at all.部分原因是,一般来说,Python 库根本不是真正可扩展或灵活的。 The parameter you send into the function gets sent to C++, and you will get an error on anything it's not expecting.您发送到 function 的参数被发送到 C++,您将收到任何意外的错误。 From the latest docs , the available constructors for a VideoCapture object are:最新的文档中, VideoCapture object 的可用构造函数是:

VideoCapture ()
Default constructor. More...

VideoCapture (const String &filename, int apiPreference=CAP_ANY)
Opens a video file or a capturing device or an IP video stream for video capturing with API Preference. More...

VideoCapture (int index, int apiPreference=CAP_ANY)
Opens a camera for video capturing. More...

So you can see the only valid signatures contain either an integer index for the device number, or a string which is expected to be a filename.因此,您可以看到唯一有效的签名包含设备编号的 integer 索引或预期为文件名的字符串。 The open() method has the same expectations on signatures. open()方法对签名有相同的期望。

OpenCV doesn't really provide first class support for video; OpenCV 并没有真正为视频提供第一个 class 支持; instead it relies on a number of possible backend libraries.相反,它依赖于许多可能的后端库。 Your best bet if you want swap-ability is just to copy the API and use some other library (perhaps ffmpeg ) to decode the raw binary stream.如果您想要交换能力,最好的选择就是复制 API 并使用其他一些库(可能是ffmpeg )来解码原始二进制 stream。

Another idea would be to create a webserver and serve the data.另一个想法是创建一个网络服务器并提供数据。 OpenCV accepts URLs in addition to filenames. OpenCV 除了文件名之外还接受 URL。 This introduces latency though, even when serving locally, so it's not a great option (but if the video is remote anyways, then maybe it's not a bad idea).虽然这会引入延迟,即使在本地服务时也是如此,所以这不是一个好的选择(但如果视频是远程的,那么也许这不是一个坏主意)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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