Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将灰度图像转换为3通道图像_Python_Numpy - Fatal编程技术网

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

Python 将灰度图像转换为3通道图像,python,numpy,Python,Numpy,我想将具有形状(高度、宽度)的灰度图像转换为具有形状(高度、宽度、通道)的三通道图像。这项工作是通过一个for循环来完成的,但必须有一个整洁的方法。这是程序中的一段代码,有人能给点提示吗。请给我一些建议 30 if img.shape == (height,width): # if img is grayscale, expand 31 print "convert 1-channel image to ", nchannels, " image."

我想将具有形状
(高度、宽度)
的灰度图像转换为具有形状
(高度、宽度、通道)
的三通道图像。这项工作是通过一个
for循环来完成的,但必须有一个整洁的方法。这是程序中的一段代码,有人能给点提示吗。请给我一些建议

 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

您可以使用
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]]])

这里的问题是什么?如果只想更改尺寸,只需执行简单的重塑操作。如果您想重新创建颜色,没有一些模型/假设是不可能的。你的灰度图像没有颜色信息,你所能做的一切就是猜测颜色(可能是简单的、不好的,也可能是更复杂的、没有那么坏的;没有限制)。@sascha我想复制灰度图像3次,因此它与彩色图像形状一致,然后我的程序可以将图像视为相同。但我希望有一个更好的实现,而不使用for loop。我认为OP希望
[[[1 1][2 2][[3 3][4 4]]]
@furas是的!使用
axis=-1
实现了这一点(制作3个通道),上面的代码得到了一个(w,h,1,3)的形状,这是错误的(Py 3.6),我需要叠加(np.stack((重新缩放,)*3,-1))使其回到(w,h,3)首先,它不是
(w,h…
,而是
(h,w…)
,它是
(h,w…)
。第二,OP的问题的图像是形状
(w,h)
,而不是
(w,h,1)
,因此发布的解决方案完全正确。第三,如果你有形状
(w,h,1)
,你可以使用
np.concatenate
而不是
np.stack
,你会得到你想要的结果,即
np.concatenate((img,)*3,axis=-1)
。你也可以使用np.tile来实现这一点。。。。。。np.tile(np.array([[1,2],[3,4]])[…,None],(1,1,1))