python 读取图片成为一维数组,如何在Python中将一维图像数组转换为PIL图像

My question is related to a Kaggle data science competition. I'm trying to read an image from a one-dimensional array containing 1-bit grayscale pixel information (0 to 255) for an 28x28 image. So the array is from 0 to 783 where each pixel is encoded as x = i * 28 + j.

Converted into a two-dimensional 28x28 matrix this:

000 001 002 003 ... 026 027

028 029 030 031 ... 054 055

056 057 058 059 ... 082 083

| | | | ... | |

728 729 730 731 ... 754 755

756 757 758 759 ... 782 783

For reasons of image manipulation (resizing, skewing) I would like to read that array into an in-memory PIL image. I did some research on the Matplotlib image function, which I think is most promising. Another idea is the Numpy image functions.

What I'm looking for, is a code example that shows me how to load that 1-dimensional array via Numpy or Matplotlib or anything else. Or how to convert that array into a 2-dimensional image using for instance Numpy.vstack and then read it as an image.

解决方案

You can convert a NumPy array to PIL image using Image.fromarray:

import numpy as np

from PIL import Image

arr = np.random.randint(255, size=(28*28))

img = Image.fromarray(arr.reshape(28,28), 'L')

L mode indicates the array values represent luminance. The result will be a gray-scale image.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值