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

Write numpy array to buffer as jpeg

我有一个程序 returns np.uin8 数组流。我现在想将这些广播到该计算机托管的网站。

我计划通过将 camera.start_recording(output, format='mjpeg') 行替换为 output.write(<numpy_array_but_jpeg>) 来注入 this 文档中的代码。 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'\xff\xd8'):
        # 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])

允许您将数组写入内存缓冲区。

这里的 example 显示了我所说内容的基本实现。