我正在尝试创建一个 python 程序,它采用灰度、24*24 像素图像文件(我尚未决定类型,因此欢迎提出建议)并将其转换为从 0(白色)到 255 的像素值列表(黑色的)。
我计划使用这个数组来创建一个MNIST http://yann.lecun.com/exdb/mnist/-类似于图片的字节文件,可以被Tensor-Flow手写识别算法识别。
我已经找到了枕头库 http://pillow.readthedocs.io/通过迭代每个像素并将其值附加到数组中,成为此任务中最有用的
from PIL import Image
img = Image.open('eggs.png').convert('1')
rawData = img.load()
data = []
for y in range(24):
for x in range(24):
data.append(rawData[x,y])
然而这个解决方案有两个问题:
- 像素值不是存储为整数,而是存储为像素对象,无法进一步进行数学操作,因此无用。
- Even the Pillow docs https://pillow.readthedocs.io/en/latest/reference/PixelAccess.html#pixelaccess-class state that:
访问单个像素相当慢。如果您要循环遍历图像中的所有像素,则可能有一种使用 Pillow API 的其他部分更快的方法。
您可以将图像数据转换为 Python 列表(或列表列表),如下所示:
from PIL import Image
img = Image.open('eggs.png').convert('L') # convert image to 8-bit grayscale
WIDTH, HEIGHT = img.size
data = list(img.getdata()) # convert image data to a list of integers
# convert that to 2D list (list of lists of integers)
data = [data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]
# At this point the image's pixels are all in memory and can be accessed
# individually using data[row][col].
# For example:
for row in data:
print(' '.join('{:3}'.format(value) for value in row))
# Here's another more compact representation.
chars = '@%#*+=-:. ' # Change as desired.
scale = (len(chars)-1)/255.
print()
for row in data:
print(' '.join(chars[int(value*scale)] for value in row))
这是小型 24x24 RGB 的放大版本eggs.png https://i.stack.imgur.com/uEojM.png我用于测试的图像:
这是第一个访问示例的输出:
这是第二个示例的输出:
@ @ % * @ @ @ @ % - . * @ @ @ @ @ @ @ @ @ @ @ @
@ @ . . + @ # . = @ @ @ @ @ @ @ @ @ @ @ @
@ * . . * @ @ @ @ @ @ @ @ @ @ @ @
@ # . . . . + % % @ @ @ @ # = @ @ @ @
@ % . : - - - : % @ % : # @ @ @
@ # . = = - - - = - . . = = % @ @ @
@ = - = : - - : - = . . . : . % @ @ @
% . = - - - - : - = . . - = = = - @ @ @
= . - = - : : = + - : . - = - : - = : * %
- . . - = + = - . . - = : - - - = . -
= . : : . - - . : = - - - - - = . . %
% : : . . : - - . : = - - - : = : # @
@ # : . . = = - - = . = + - - = - . . @ @
@ @ # . - = : - : = - . - = = : . . # @
@ @ % : = - - - : = - : - . . . - @
@ @ * : = : - - - = . . - . . . + @
@ # . = - : - = : : : . - % @ @ @
* . . . : = = - : . . - . - @ @ @ @ @
* . . . : . . . - = . = @ @ @ @ @ @
@ : - - . . . . # @ @ @ @ @ @ @ @
@ @ = # @ @ * . . . - @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ . . . # @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ - . % @ @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ # . : % @ @ @ @ @ @ @ @ @ @ @ @ @
现在访问像素数据应该比使用对象更快img.load()
返回(并且值将是 0..255 范围内的整数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)