我想知道是否可以使用 Python 中的 OpenCV VideoWriter 类“流式传输”数据?

通常为了处理内存中的数据,否则我会使用 BytesIO(或 StringIO)。

我尝试使用 BytesIO 失败了:

import cv2
from io import BytesIO

stream = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('x264')

data = BytesIO()

# added these to try to make data appear more like a string
data.name = 'stream.{}'.format('av1')
data.__str__ = lambda x: x.name

try:
    video = cv2.VideoWriter(data, fourcc=fourcc, fps=30., frameSize=(640, 480))
    start = data.tell()

        # Check if camera opened successfully
        if (stream.isOpened() == False):
            print("Unable to read camera feed", file=sys.stderr)
            exit(1)

        # record loop
        while True:
            _, frame = stream.read()
            video.write(frame)
            data.seek(start)
            # do stuff with frame bytes
            # ...

            data.seek(start)

    finally:
        try:
            video.release()
        except:
            pass
finally:
    stream.release()

但是,我没有编写 BytesIO 对象,而是得到以下消息:
Traceback (most recent call last):
  File "video_server.py", line 54, in talk_to_client
    video = cv2.VideoWriter(data, fourcc=fourcc, fps=fps, frameSize=(width, height))
TypeError: Required argument 'apiPreference' (pos 2) not found

...因此,当我将 VideoWriter 调用修改为 cv2.VideoWriter(data, apiPreference=0, fourcc=fourcc, fps=30., frameSize=(640, 480)) (我读到 0 表示自动,但我也尝试过 cv2.CAP_FFMPEG )时,我反而收到以下错误:
Traceback (most recent call last):
  File "video_server.py", line 54, in talk_to_client
    video = cv2.VideoWriter(data, apiPreference=0, fourcc=fourcc, fps=fps, frameSize=(width, height))
TypeError: bad argument type for built-in operation

所以我的问题是,是否可以在内存中使用 cv2.VideoWriter 类编写编码视频,如果可以,它是如何完成的?

在这一点上,我没有任何想法,因此非常欢迎任何帮助:-)

最佳答案

不幸的是,OpenCV 不支持对内存进行编码(或解码)。您必须写入(或读取)磁盘才能让 VideoWriter(或 VideoCapture)工作。

关于python - 使用 OpenCV VideoWriter 和 Python BytesIO 在内存中流式传输视频,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51052268/

10-10 19:05