从JPG到b64encode到cv2.imread() [英] From JPG to b64encode to cv2.imread()

查看:94
本文介绍了从JPG到b64encode到cv2.imread()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在编写的程序,我正在使用base64.b64encode(f.read(image))从一台计算机传输图像,并尝试在接收脚本中读取它而不将其保存到硬盘驱动器中(在尽量减少处理时间).我很难弄清楚如何将图像读取到OpenCV中而不将其保存在本地.

For a program I am writing, I am transferring an image from one computer - using base64.b64encode(f.read(image)) - and trying to read it in the receiving script without saving it to hard drive (in an effort to minimize process time). I'm having a hard time figuring out how to read the image into OpenCV without saving it locally.

这是我发送图像的代码如下:

Here is what my code for sending the image looks like:

f = open(image.jpg)
sendthis = f.read()
f.close()
databeingsent = base64.b64encode(sendthis)
client.publish('/image',databeingsent,0) 
# this is an MQTT publish, details for SO shouldn't be relevant

同时,这是接收它的代码. (这在on_message函数中,因为我使用MQTT进行传输.)

Meanwhile, here is the code receiving it. (This is in an on_message function, since I'm using MQTT for the transfer.)

def on_message(client, userdata, msg): # msg.payload is incoming data
    img = base64.b64decode(msg.payload)
    source = cv2.imread(img)
    cv2.imshow("image", source)

消息解码后,出现错误: "TypeError:您的输入类型不是numpy数组".

After the message decodes, I have the error: "TypeError: Your input type is not a numpy array".

我已经进行了一些搜索,但似乎找不到相关的解决方案-存在一些有关使用b64从文本文件转换为numpy的解决方案,但是没有一个真正涉及使用图像并将立即将解码后的数据读取到OpenCV中无需将其保存到硬盘驱动器的中间步骤(使用用于读取发送"脚本中文件的逆过程).

I've done some searching, and I can't seem to find a relevant solution - some exist regarding converting from text files to numpy using b64, but none really relate to using an image and immediately reading that decoded data into OpenCV without the intermediary step of saving it to the harddrive (using the inverse process used to read the file in the "send" script).

我对Python和OpenCV还是很陌生,所以如果有更好的编码方法来发送图像-可以解决问题的任何方法.图像的发送方式无关紧要,只要我可以在接收端读取它而无需将其另存为.jpg即可.

I'm still pretty new to Python and OpenCV, so if there's a better encoding method to send the image - whatever solves the problem. How the image is sent is irrelevant, so long as I can read it in on the receiving end without saving it as a .jpg to disk.

谢谢!

推荐答案

您可以使用以下方法从解码的数据中获取一个numpy数组:

You can get a numpy array from you decoded data using:

import numpy as np
...
img = base64.b64decode(msg.payload)
npimg = np.fromstring(img, dtype=np.uint8)

然后,您需要 imdecode 才能阅读来自内存中缓冲区的图像. imread 旨在从文件.

Then you need imdecode to read the image from a buffer in memory. imread is meant to load an image from a file.

所以:

import numpy as np
...
def on_message(client, userdata, msg): # msg.payload is incoming data
    img = base64.b64decode(msg.payload); 
    npimg = np.fromstring(img, dtype=np.uint8); 
    source = cv2.imdecode(npimg, 1)

这篇关于从JPG到b64encode到cv2.imread()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆