![](/img/trans.png)
[英]improve image quality in video with opencv videowriter python
[英]Streaming video in memory with OpenCV VideoWriter and Python BytesIO
我想知道是否可以使用 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)工作。
如果你使用 Linux,你可以创建一个 ramdisk 并写入它。
mount -t tmpfs -o size=512m tmpfs /mnt/ramdisk
如果您想方便地加载已经在内存中的视频,请使用临时文件: https : //docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
import tempfile
import cv2
my_video_bytes = download_video_in_memory()
with tempfile.NamedTemporaryFile() as temp:
temp.write(my_video_bytes)
video_stream = cv2.VideoCapture(temp.name)
# do your stuff.
不幸的是,这仍然会在磁盘上创建一个文件。 但是,嘿,至少你不必自己管理。 有一个SpooledTemporaryFile()
实现将保留在内存中,但不幸的是,它不会创建 OpenCV 可以引用的文件系统名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.