gpt4 book ai didi

python - 给定包含 "triplets"RGB 值的 2D numpy arrayMatrix,如何生成图像?

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:10 28 4
gpt4 key购买 nike

你看,大多数讨论图像创建的帖子都涉及 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 会生成一个充满孔洞的图像。我正在考虑将它分成三个(!!!)二维数组,然后使用 np.dstack 但这听起来非常效率低下,因为代码动态生成了数千个需要以图像形式呈现的大尺寸 (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)

关于python - 给定包含 "triplets"RGB 值的 2D numpy arrayMatrix,如何生成图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40530282/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com