Olayinka
Olayinka

Reputation: 2845

Create RGB image with three grayscale png files - pypng

I'm trying to create an RGB png image by merging three grayscale png images using pypng. I've read the png files into numpy arrays as below

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]))

How do I combine these three arrays/images to recreate an RGB png image?

Upvotes: 0

Views: 1586

Answers (3)

Mikhail V
Mikhail V

Reputation: 1521

I've found out that scipy can read grayscale png directly to array.

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)

Upvotes: 2

Olayinka
Olayinka

Reputation: 2845

I should be creating a 2D array with each line being 3*width and containing contiguous RGB values

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

Upvotes: 0

ZdaR
ZdaR

Reputation: 22954

For simplicity let us assume that you have 3 grayscale images of 3x3 dimensions and let these 3 grayscale images be represented as :

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]]]

Upvotes: 1

Related Questions