2015-05-04 49 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)