convert a grayscale image to a 3-channel image

PythonNumpy

Python Problem Overview


I want to convert a gray-scale image with shape (height,width) to a 3 channels image with shape (height,width,nchannels). The work is done with a for-loop, but there must be a neat way. Here is a piece code in program, can someone give a hint. please advice.

 30         if img.shape == (height,width): # if img is grayscale, expand
 31             print "convert 1-channel image to ", nchannels, " image."
 32             new_img = np.zeros((height,width,nchannels))
 33             for ch in range(nchannels):
 34                 for xx in range(height):
 35                     for yy in range(width):
 36                         new_img[xx,yy,ch] = img[xx,yy]
 37             img = new_img

Python Solutions


Solution 1 - Python

You can use np.stack to accomplish this much more concisely:

img = np.array([[1, 2], [3, 4]])
stacked_img = np.stack((img,)*3, axis=-1)
print(stacked_img)
 # array([[[1, 1, 1],
 #         [2, 2, 2]],
 #        [[3, 3, 3],
 #         [4, 4, 4]]])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDylanView Question on Stackoverflow
Solution 1 - PythonChris MuellerView Answer on Stackoverflow