[英]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.