猿问

字节数组从Java中的Mat转换为Python中从Socket的图像

我在应用程序上工作时,是从Java客户端中的网络摄像头获取Opencv Mat格式的图像,并且必须在python服务器上处理该图像。


因此,我正在将一个字节数组发送到python服务器。我使用Java对图像进行编码,如下所示:


private VideoCapture capture = new VideoCapture();


...


this.capture.read(frame);

    if (!frame.empty()) {

      byte[] return_buff = new byte[(int) (frame.total() *

                frame.channels())];

      frame.get(0, 0, return_buff);

...

之后,我使用DataOutputStream通过套接字将其发送。当我将其回显给Java Client时,字节数据似乎已正确完整地传输。然后在Python中,我尝试使用PIL对其进行解码


img = Image.open(BytesIO(data))

是的,我已经像这里建议的那样导入了PIL:PIL:将Bytearray转换为图像


但是我仍然收到此错误:


img = Image.open(BytesIO(data))

File "/root/.local/lib/python2.7/site-packages/PIL/Image.py", line 2590, in 

open % (filename if filename else fp))

IOError: cannot identify image file

我是否需要更改我组装bytearra的方式,还是必须以其他方式对其进行编码?


犯罪嫌疑人X
浏览 224回答 1
1回答

杨魅力

问题是Image.open(BytesIO(data))显然希望数据具有某种描述图像类型的标头,因此不适合转换为字节的Mat,因为Mat似乎没有集成任何标头,只是普通图像数据。在python中,可以使用以下方法从Mat字节数组中获取图像:img = cv2.imdecode(bytearray, flag)标志是代表图片cvtype的数字。
随时随地看视频慕课网APP

相关分类

Python
我要回答