python将数组转化为图片,如何在python中将字节数组转换为图像

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?

解决方案

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.]])

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')

NHJYk.png

Documentation is here.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值