2015-05-04 102 views
0

我想通過使用pypng合併三個灰度png圖像來創建RGB png圖像。我讀過的PNG文件導入到numpy的數組如下用三個灰度PNG文件創建RGB圖像 - pypng

pngFile1 = png.Reader("file1.png").read() 
pngFile2 = png.Reader("file2.png").read() 
pngFile3 = png.Reader("file3.png").read() 

pngArray1 = np.array(list(pngFile1[2])) 
pngArray2 = np.array(list(pngFile2[2])) 
pngArray3 = np.array(list(pngFile3[2])) 

如何結合這三個陣列/圖像重建的RGB png圖片?

+0

您確定PNG可以灰度嗎?我認爲它的RGB只有(索引或平原)。 –

回答

1

爲簡單起見讓我們假設你有3x3尺寸的3個灰度級圖像,並讓這些3個灰度圖像被表示爲:

import numpy as np 

R = np.array([[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]]) 
G = np.array([[[2], [2], [2]], [[2], [2], [2]], [[2], [2], [2]]]) 
B = np.array([[[3], [3], [3]], [[3], [3], [3]], [[3], [3], [3]]]) 
RGB = np.concatenate((R,G,B), axis = 2) 

print RGB 

>>> [[[1 2 3] 
     [1 2 3] 
     [1 2 3]] 

    [[1 2 3] 
     [1 2 3] 
     [1 2 3]] 

    [[1 2 3] 
     [1 2 3] 
     [1 2 3]]] 
+0

我假設numpy數組的格式,因爲您沒有在問題中指定正確的格式,告訴我如果格式有問題,您可以隨時使用'axis'值來獲得各種結果。 – ZdaR

+0

灰度圖像很少具有(3,3,1)的形狀 - 相反,它們通常具有(3,3)的形狀。這種解決方案在這種情況下不起作用,因爲第三軸(軸= 2)還不存在。 – Ben

0

我應創建一個二維陣列的每一行是3*width和含有連續RGB值

pngFile1 = png.Reader("file1.png").read() 
pngFile2 = png.Reader("file2.png").read() 
pngFile3 = png.Reader("file3.png").read() 

pngArray1 = np.array(list(pngFile1[2])) 
pngArray2 = np.array(list(pngFile2[2])) 
pngArray3 = np.array(list(pngFile3[2])) 

//get dimension, assuming they are the same for all three images 
width = pngArray1[0] 
height = pngArray1[1] 

//create a 2D array to use on the png.Writer 
pngArray = np.zeros([height, 3*width]) 

for i in range(height) 
    for j in range(width) 
     pngArray[i][j*3 + 0] = pngArray1[i][j] 
     pngArray[i][j*3 + 1] = pngArray2[i][j] 
     pngArray[i][j*3 + 2] = pngArray3[i][j] 

fileStream = open("pngFileRGB.png", "wb") 
writer = png.Writer(width, height) 
writer.write(fileStream, pngArray) 
fileStream.close() 
1

我發現scipy可以直接讀取灰度png到數組。

from scipy import misc 
import numpy 

R = misc.imread("r.png") 
G = misc.imread("g.png") 
B = misc.imread("b.png") 

RGB = numpy.zeros((R.shape[0], R.shape[1], 3), "uint8") 
RGB [:,:,0] = R 
RGB [:,:,1] = G 
RGB [:,:,2] = B 

misc.imsave("rgb.png", RGB)