我在想是否可能使用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
类在内存中编写编码视频,如果可以的话,如何实现?
目前我已经没有更多的想法了,所以任何帮助都将不胜感激 :-)