参见英文答案 > how to copy numpy array value into higher dimensions 7个
我想将具有形状(高度,宽度)的灰度图像转换为具有形状(高度,宽度,n通道)的3通道图像.这项工作是通过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]]])
标签:python,numpy
来源: https://codeday.me/bug/20190928/1827559.html