2017-07-03 522 views

回答

1

matplotlib對於像這樣的任務很有用,儘管還有其他方法。 下面是一個例子:

import numpy as np 
import matplotlib.image 

src = np.zeros((200,200)) 
print src.shape 

rgb = np.zeros((200,200,3)) 
print rgb.shape 

src[10,10] = 1 
src[20,20] = 2 
src[30,30] = 3 

for i in range(src.shape[0]): 
    for j in range(src.shape[1]): 
    rgb[i,j,0] = 255 if src[i,j]==1 else 0 # R 
    rgb[i,j,1] = 255 if src[i,j]==2 else 0 # G 
    rgb[i,j,2] = 255 if src[i,j]==3 else 0 # B 

matplotlib.image.imsave('test.png', rgb.astype(np.uint8)) 

訣竅是將其轉換爲形狀(x, y, 3)的RGB陣列。您可以使用任何想要生成每像素RGB值的公式。

此外,請注意將其轉換爲uint8陣列。

+1

謝謝先生......我已經這樣做了。 –

+1

不是問題!你能接受我的回答嗎? – keredson

+1

先生,我是在stackoverflow.com上新註冊的。只要我的聲望超過15,我已經接受了你的回答。我的接受將會出現。再次感謝你幫助我 –

1

你可以使用PIL.Image來做到這一點,但首先轉換你的數組。

可以說,例如,認爲:

  1. 1.0應該是紅色,表示爲(255,0,0)
  2. 2.0應該是綠色 - >(0,255,0)
  3. 3.0應爲藍色 - >(0,0,255)
  4. 4.0應該是黑色的 - >(0,0,0)
  5. 5.0應該是白色 - >(255,255,255)

當然,您可以將這些值更改爲您選擇的任何顏色,但這僅用於演示。話雖如此,你的二維數組也需要被「扁平化」爲1-d,以便PIL.Image將其作爲數據接受。

from PIL import Image 
import numpy as np 
your_2d_array = np.something() # Replace this line, obviously 
img_array = [] 
for x in your_2d_array.reshape(2000*2000): 
    if x == 1.0: 
     img_array.append((255,0,0)) # RED 
    elif x == 2.0: 
     img_array.append((0,255,0)) # GREEN 
    elif x == 3.0: 
     img_array.append((0,0,255)) # BLUE 
    elif x == 4.0: 
     img_array.append((0,0,0)) # BLACK 
    elif x == 5.0: 
     img_array.append((255,255,255)) # WHITE 

img = Image.new('RGB',(2000,2000)) 
img.putdata(img_array) 
img.save('somefile.png') 

雖然這應該工作,我覺得有更有效的方式來做到這一點,我不知道,所以,如果有人編輯這個答案有更好的例子,我會很高興。但如果它是一個小應用程序,並且最大的效率不會打擾你,那麼就是這樣。

+1

謝謝Ofer Sadan ... –

相關問題