将numpy数组以jpeg格式写入缓冲区



我有一个程序,它返回np.uin8数组流。我现在想把这些广播到一个由那台电脑托管的网站上。

我计划通过将camera.start_recording(output, format='mjpeg')行替换为output.write(<numpy_array_but_jpeg>)来在本文档中注入代码。start_recording的文档指出,如果存在write()方法,它将以请求的格式将数据写入该缓冲区。我可以在网上找到很多关于如何将np.uint8保存为jpeg的内容,但在我的情况下,我想将数据写入内存中的缓冲区,我不想将图像保存到文件中,然后将该文件读取到缓冲区中。

不幸的是,在流的早期更改np.uint8的输出格式不是一个选项。

感谢您的帮助。为了简单起见,我复制了下面的重要代码位

class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b'xffxd8'):
# New frame, copy the existing buffer's content and notify all
# clients it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
output = StreamingOutput()
camera.start_recording(output, format='mjpeg')

OpenCV具有执行的功能

retval, buf = cv.imencode(ext,img[, params])

可以将数组写入内存缓冲区。

这里的这个例子展示了我所说内容的一个基本实现。

img_encode = cv.imencode('.png', img)[1]

# Converting the image into numpy array
data_encode = np.array(img_encode)

# Converting the array to bytes.
byte_encode = data_encode.tobytes()

最新更新