如何在Python中显示以字节数组表示的图像而不将其写入文件? [英] How can I display an image in Python that's represented as an array of bytes without writing it to a file?

查看:75
本文介绍了如何在Python中显示以字节数组表示的图像而不将其写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已成功通过套接字发送了一个图像,并且在接收端,我拥有与发送的图像文件完全相同的原始字节.这意味着,如果我将这些字节二进制写入文件,则将获得与发送文件相同的文件.我曾尝试在没有先保存的情况下显示 Python 中的图像,但我在这样做时遇到了麻烦.如果我理解正确,则 matplotlib.imread()需要文件的路径,然后将该文件解码为几个矩阵.做这样的事情很好:

I have successfully sent an image through a socket and, on the receiving end, I have the exact same raw bytes that the image file that was sent had. This means that if I binary write those bytes to a file, I'll obtain the same file as the one that was sent. I have tried showing the image from Python without saving it first, but I'm having trouble doing so. If I understand correctly, matplotlib.imread() requires the path to a file and then decodes that file into several matrices. Doing something like this works fine:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# data is the image data that was received from the socket

file = open("d:\\image.png", 'wb')
file.write(data)
file.close()

img = mpimg.imread("d:\\image.png")
plt.imshow(img)
plt.show()

显然我应该为此使用一个临时文件,但我只是为了示例而写的.有没有办法调用 imshow()show() 方法而无需事先调用 imread() ,前提是我已经有了这些字节?

Obviously I should use a temporary file for that, but I wrote that just for the sake of the example. Is there any way to call the imshow() and show() methods without having called imread() beforehand, provided I already have those bytes?

推荐答案

如果你可以直接从 socket 中读取,你可以使用 makefile() 将 socket 转换为文件对象,然后像普通文件一样提供 imread 的套接字.阅读时记得设置编解码器:

If it's OK for you to read from the socket directly, you can convert the socket to a file object using makefile(), then provide the socket to imread as you would with a regular file. Remember to set the codec when reading:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# don't read from your socket, instead, call this where you would call read
fp = your_socket.makefile()

with fp:
    img = mpimg.imread(fp, format='jpeg')
plt.imshow(img)
plt.show()

我已经搜索过,但是找不到直接从matplotlib中的字节解码图像的方法.如果因为你已经有了bytes数组所以用上面的方案不行,那就用BytesIO创建一个临时缓冲区:

I've searched and couldn't find a way to directly decode images from bytes in matplotlib. If it is not OK to use the above solution because you have already the bytes array, then use BytesIO to create a temporary buffer:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import io

fp = io.BytesIO(data)

with fp:
    img = mpimg.imread(fp, format='jpeg')
plt.imshow(img)
plt.show()

这篇关于如何在Python中显示以字节数组表示的图像而不将其写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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