簡體   English   中英

將 3 個單獨的 numpy 數組組合成 Python 中的 RGB 圖像

[英]Combine 3 separate numpy arrays to an RGB image in Python

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

我試過“圖像”來完成這項工作,但它需要歸因於“模式”。

我試着做一個把戲。 我會使用 Image.fromarray() 將數組轉換為圖像,但當 Image.merge 需要“L”模式圖像合並時,它默認達到“F”模式。 如果我首先將 fromarray() 中的數組屬性聲明為“L”,則所有 RGB 圖像都會失真。

但是,如果我保存圖像然后打開它們然后合並,它工作正常。 圖像以“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 大小的數組。

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

我不太明白你的問題,但這里有一個我最近做過的類似事情的例子,看起來可能會有所幫助:

# 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')

我希望有幫助

rgb = np.dstack((r,g,b))  # stacks 3 h x w arrays -> h x w x 3

如果您傳遞 3 個通道,此代碼不會創建 3d 數組。 保留 2 個通道。

在將 numpy 數組傳遞給Image.fromarray之前將它們轉換為uint8

例如。 如果您在 [0..1] 范圍內有浮點數:

r = Image.fromarray(numpy.uint8(r_array*255.999))

我認為您的失真是由於您將原始圖像分成單獨的波段,然后在將其合並之前再次調整大小的方式造成的;

`
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()
`

這很好用!

如果使用 PIL Image 將其轉換為數組,然后繼續下面的操作,否則使用 matplotlib 或 cv2 直接執行。

image = cv2.imread('')[:,:,::-1]
image_2 = image[10:150,10:100]
print(image_2.shape)

img_r = image_2[:,:,0]
img_g = image_2[:,:,1]
img_b = image_2[:,:,2]

image_2 = img_r*0.2989 + 0.587*img_g + 0.114*img_b 

image[10:150,10:100,0] = image_2
image[10:150,10:100,1] = image_2
image[10:150,10:100,2] = image_2

plt.imshow(image,cmap='gray')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM