如何在python中将字节数组转换为图像 [英] How to convert byte array to image in python

查看:787
本文介绍了如何在python中将字节数组转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将长度为64372(w = 242,h = 266)的原始数据转换为图像,原始数据采用字节数组的格式,我想将此字节数组转换为图像,

I am trying to convert raw data of length 64372(w= 242, h=266) to the image, the raw data is in the format of the byte array, I want to convert this byte array into image, can you help me with that?

推荐答案

您可以生成一个 bytearray 的虚拟对象表示这样的渐变的数据:

You can generate a bytearray of dummy data representing a gradient like this:

import numpy as np

# Generate a left-right gradient 242 px wide by 266 pixels tall
ba = bytearray((np.arange(242) + np.zeros((266,1))).astype(np.uint8)) 

作为参考,该数组将包含以下数据:

For reference, that array will contain data like this:

array([[  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       ...,
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.]])

然后制作成如下所示的PIL /枕头图像:

And then make into a PIL/Pillow image like this:

from PIL import Image

# Convert bytearray "ba" to PIL Image, 'L' just means greyscale/lightness
im = Image.frombuffer('L', (242,266), ba, 'raw', 'L', 0, 1)

然后,您可以像这样保存图像:

Then you can save the image like this:

im.save('result.png')

文档在此处

这篇关于如何在python中将字节数组转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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