Arm*_*min 3 python image mnist pillow
我正在尝试创建一个python程序,它采用灰度,24*24像素图像文件(我还没有决定类型,所以欢迎建议)并将其转换为从0(白色)到255的像素值列表(黑色).
我计划使用这个数组来创建一个类似 MNIST的图像字节文件,可以通过Tensor-Flow手写识别算法识别.
通过迭代每个像素并将其值附加到PIL导入图像中的数组,我发现Pillow库在此任务中最有用.
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])
Run Code Online (Sandbox Code Playgroud)
然而,该解决方案存在两个问题(1)像素值不是作为整数存储,而是像素对象不能进一步在数学上被操纵并因此是无用的.(2)即使Pillow文件说明:
访问单个像素相当慢.如果您循环遍历图像中的所有像素,则使用> Pillow API的其他部分可能会更快.
mar*_*eau 11
您可以将图像数据转换为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))
Run Code Online (Sandbox Code Playgroud)
这是eggs.png我用于测试的小型24x24 RGB 图像的放大版本:
这是第一个访问示例的输出:
这里是第二个例子的输出:
@ @ % * @ @ @ @ % - . * @ @ @ @ @ @ @ @ @ @ @ @
@ @ . . + @ # . = @ @ @ @ @ @ @ @ @ @ @ @
@ * . . * @ @ @ @ @ @ @ @ @ @ @ @
@ # . . . . + % % @ @ @ @ # = @ @ @ @
@ % . : - - - : % @ % : # @ @ @
@ # . = = - - - = - . . = = % @ @ @
@ = - = : - - : - = . . . : . % @ @ @
% . = - - - - : - = . . - = = = - @ @ @
= . - = - : : = + - : . - = - : - = : * %
- . . - = + = - . . - = : - - - = . -
= . : : . - - . : = - - - - - = . . %
% : : . . : - - . : = - - - : = : # @
@ # : . . = = - - = . = + - - = - . . @ @
@ @ # . - = : - : = - . - = = : . . # @
@ @ % : = - - - : = - : - . . . - @
@ @ * : = : - - - = . . - . . . + @
@ # . = - : - = : : : . - % @ @ @
* . . . : = = - : . . - . - @ @ @ @ @
* . . . : . . . - = . = @ @ @ @ @ @
@ : - - . . . . # @ @ @ @ @ @ @ @
@ @ = # @ @ * . . . - @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ . . . # @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ - . % @ @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ # . : % @ @ @ @ @ @ @ @ @ @ @ @ @
Run Code Online (Sandbox Code Playgroud)
现在访问像素数据应该比使用对象img.load()返回更快(并且值将是0..255范围内的整数).
| 归档时间: |
|
| 查看次数: |
16332 次 |
| 最近记录: |