将numpy数组写入jpeg

问题描述

我有一个返回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显示了我所谈论的内容的基本实现。