gpt4 book ai didi

python - 将灰度图像转换为 3 channel 图像

转载 作者:IT老高 更新时间:2023-10-28 22:17:18 24 4
gpt4 key购买 nike

我想将形状为 (height,width) 的灰度图像转换为形状为 (height,width,nchannels) 的 3 channel 图像。这项工作是通过 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

最佳答案

您可以使用 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 - 将灰度图像转换为 3 channel 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com