Python 将灰度图像转换为 3 通道图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40119743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:11:01  来源:igfitidea点击:

convert a grayscale image to a 3-channel image

pythonnumpy

提问by Dylan

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.

我想将具有 shape 的灰度图像转换为具有 shape(height,width)的 3 通道图像(height,width,nchannels)。工作是用 完成的for-loop,但必须有一个整洁的方式。这是程序中的一段代码,有人可以给出提示。请指教。

 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

回答by Chris Mueller

You can use np.stackto accomplish this much more concisely:

您可以使用np.stack更简洁地完成此操作:

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