Convert grayscale image to three-channel image

I want to convert a grayscale image with a shape (height,width) to a 3-channel image with a shape (height,width,nchannels) . Work is done using for-loop , but there should be a neat way. Here is a piece of code in the program, can someone give a hint. Please advise.

  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 
+5
source share
2 answers

You can use np.stack to do this much more succinctly:

 img = np.array([[1, 2], [3, 4]]) stacked_img = np.stack((img,)*3, -1) print(stacked_img) # array([[[1, 1, 1], # [2, 2, 2]], # [[3, 3, 3], # [4, 4, 4]]]) 
+15
source
 height, width = 256, 256 img = np.zeros((height,width)) nchannels = 3 new_img = np.resize(img, (height, width, nchannels)) 

Here you go. Used by np.resize .

+2
source

Source: https://habr.com/ru/post/1258435/


All Articles