【问题标题】:Convert an array directly to an image (each cell becomes one pixel) in python在python中将数组直接转换为图像(每个单元格变成一个像素)
【发布时间】:2016-08-11 16:09:02
【问题描述】:

我想将 64x64 单元阵列转换为 64x64 像素图像。使用 matplotlib 和 pylab 我最终得到了大约 900x900 的图像,额外的像素被混合在一起。

py.figure(1)
py.clf()
py.imshow( final_image , cmap='Greys_r' )

如何以 1:1 的比例从单元格转换为像素? (如果你还不能说,我对此很陌生)。

【问题讨论】:

  • 你能提供一个更好的例子来说明你已经尝试过的东西吗?
  • 元胞数组的内容是什么?

标签: python data-representation


【解决方案1】:

这是使用 PIL 创建图像 2x2 的示例。 a 是大小为 4(平面)的颜色数组

from PIL import Image

a = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255)]

#  Create RGB image with size 2x2
img = Image.new("RGB", (2, 2))
#  Save it to the new function
img.putdata(a)
#  Save to the file
img.save('1.png')

当然,如果数据不平坦,您应该将其调整为数据格式。不过这应该很容易。例如,此脚本将二维列表中的数据展平:

a = [[[1, 2, 3], [2, 3, 4]], [[5, 6, 7], [8, 9, 10]]]
a = [tuple(color) for row in a for color in row]
print a

如果你处理的是 numpy 数组而不是列表,你应该使用函数 fromarray(以下列方式):

#  data is numpy array
img = Image.fromarray(data, 'RGB')
#  Save to the file
img.save('1.png')

请注意,强烈建议使用 numpy 数组,因为它只是包装了 C 数组,因此它们速度更快。

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2018-09-13
    • 2019-03-24
    • 2021-12-07
    • 2013-08-01
    相关资源
    最近更新 更多