2012-05-04 119 views
23

所以我有一組數據,我可以將它們轉換成R,G,B波段的單獨numpy數組。現在我需要將它們組合起來形成一個RGB圖像。在Python中將3個單獨的numpy數組組合爲一個RGB圖像

我嘗試'圖像'來完成這項工作,但它需要'模式'來歸因。

我試圖做一個把戲。我將使用Image.fromarray()將數組轉換爲圖像,但當Image.merge需要「L」模式圖像合併時,默認情況下會獲得'F'模式。如果我首先將fromarray()中的數組屬性聲明爲'L',則所有R G B圖像都會變形。

但是,如果我保存圖像,然後打開它們,然後合併,它工作正常。圖像以'L'模式讀取圖像。

現在我有兩個問題。

首先,我不認爲這是一個完美的工作方式。所以如果有人知道更好的方法,請告訴

其次,Image.SAVE無法正常工作。以下是我面對的錯誤:

In [7]: Image.SAVE(imagefile, 'JPEG') 
---------------------------------------------------------------------------------- 

TypeError         Traceback (most recent call last) 

/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>() 

TypeError: 'dict' object is not callable 

請建議解決方案。

並請注意,圖像大約是4000x4000大小的陣列。

回答

30

我真的不明白你的問題,但這裏是一個類似的例子,我最近做這似乎是它可以幫助:

# r, g, and b are 512x512 float arrays with values >= 0 and < 1. 
from PIL import Image 
import numpy as np 
rgbArray = np.zeros((512,512,3), 'uint8') 
rgbArray[..., 0] = r*256 
rgbArray[..., 1] = g*256 
rgbArray[..., 2] = b*256 
img = Image.fromarray(rgbArray) 
img.save('myimg.jpeg') 

我希望幫助

+0

非常感謝! This works –

+8

@IshanTomar - 如果有幫助,您可能希望接受該答案。 – Bach

+0

如果您想將陣列保存爲圖像,應該是「toimage」 – icypy

3

轉換的numpy的陣列到uint8然後再將它們傳遞給Image.fromarray

例如,如果您有浮動的範圍是[0..1]:

r = Image.fromarray(numpy.uint8(r_array*255.999)) 
29
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3 

要轉換也花車0。1至UINT8 S,

rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256 
1

你的失真,我相信是造成你將原始圖像分割成單獨的樂隊,然後再重新調整大小,然後再合併;

` 
image=Image.open("your image") 

print(image.size) #size is inverted i.e columns first rows second eg: 500,250 

#convert to array 
li_r=list(image.getdata(band=0)) 
arr_r=np.array(li_r,dtype="uint8") 
li_g=list(image.getdata(band=1)) 
arr_g=np.array(li_g,dtype="uint8") 
li_b=list(image.getdata(band=2)) 
arr_b=np.array(li_b,dtype="uint8") 

# reshape 
reshaper=arr_r.reshape(250,500) #size flipped so it reshapes correctly 
reshapeb=arr_b.reshape(250,500) 
reshapeg=arr_g.reshape(250,500) 

imr=Image.fromarray(reshaper,mode=None) # mode I 
imb=Image.fromarray(reshapeb,mode=None) 
img=Image.fromarray(reshapeg,mode=None) 

#merge 
merged=Image.merge("RGB",(imr,img,imb)) 
merged.show() 
` 

這個效果很好!

相關問題