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

查看:29
本文介绍了从 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)

消息解码后,出现错误:类型错误:您的输入类型不是 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天全站免登陆