Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a grayscale image to a 3-channel image [duplicate]

Tags:

python

numpy

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 
like image 532
Dylan Avatar asked Oct 18 '16 23:10

Dylan


People also ask

Can grayscale image have 3 channels?

A grayscale image has just one channel.

How do you convert gray to RGB?

Conversion of a grayscale to RGB is simple. Simply use R = G = B = gray value. The basic idea is that color (as viewed on a monitor in terms of RGB) is an additive system. Thus adding red to green yields yellow.

Why do we convert grayscale in image processing?

Grayscale is a range of gray shades from white to black, as used in a monochrome display or printout. Grayscale images are most commonly used in image processing because smaller data enables developers to do more complex operations in a shorter time.


1 Answers

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]]]) 
like image 140
Chris Mueller Avatar answered Sep 30 '22 10:09

Chris Mueller