[英]How to, given a 2D numpy arrayMatrix that contains “triplets” of RGB values generate an image?
您会看到,大多数讨论图像创建的帖子都涉及3D矩阵[0] [1] [2],该矩阵有效包含直接应用的必要信息
img = Image.fromarray(Matrix, 'RGB')
但是,我坚持使用具有“ 3n”列和“ n”行的大型矩阵。 如您所见,“图像”的编码方式使我想起了P3 / P6格式:
[ 0 0 0 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0
255 255 255 0 0 0 255 255 255]
上面的2D矩阵表示3x3“像素”,并使用Image.fromarray生成充满孔的图像。 我想它分裂为三个(!)2个维数组,然后使用np.dstack但声音非常低效的代码生成dinamically数千矩阵的大尺寸(700x2100)需要被呈现为图像。
我正在想做的是,顺便说一句:
R = np.zeros((Y, X), dtype = np.uint8) # Same for G & B
for Row in range(Y):
for Column in range(3*X):
if Column % 3 == 0: # With Column-1 for G and -2 for B
R[Row][Column/3] = 2DMatrix[Row][Column]
#After populating R, G, B
RGB0 = np.dstack([R, G, B])
img = Image.fromarray(RGB0, 'RGB')
谢谢!
numpy.reshape
应该适用于此。 颜色值必须是8位无符号的,这一点也很重要:
>>> import numpy as np
>>> a = [[0, 0, 0, 255, 255, 255, 0, 0, 0],
... [0, 0, 0, 255, 255, 255, 0, 0, 0],
... [255, 255, 255, 0, 0, 0, 255, 255, 255]]
>>> a = np.array(a)
>>> a.astype('u1').reshape((3,3,3))
array([[[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]],
[[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]],
[[255, 255, 255],
[ 0, 0, 0],
[255, 255, 255]]], dtype=uint8)
>>> import PIL.Image
>>> i = PIL.Image.fromarray(a.astype('u1').reshape((3,3,3)), 'RGB')
这似乎按照我们期望的方式工作:
>>> i.size
(3, 3)
>>> i.getpixel((0,0))
(0, 0, 0)
>>> i.getpixel((1,0))
(255, 255, 255)
>>> i.getpixel((2,0))
(0, 0, 0)
>>> i.getpixel((0,1))
(0, 0, 0)
>>> i.getpixel((1,1))
(255, 255, 255)
>>> i.getpixel((2,1))
(0, 0, 0)
>>> i.getpixel((0,2))
(255, 255, 255)
>>> i.getpixel((1,2))
(0, 0, 0)
>>> i.getpixel((2,2))
(255, 255, 255)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.