如何将 1d 数组转换为 3d 数组(将灰度图像转换为 rgb 格式)?
How to convert 1d array to 3d array (convert grayscale image so rgb format )?
我有一个 numpy 数组格式的图像,我编写代码时假定 rgb 图像作为输入,但我发现输入由黑白图像组成。
对于应该是 RGB 的图像,即 (256,256,3) 维图像,我将输入作为灰度 (256,256) 阵列图像,我想将其转换为 (256,256,3)
这是我在 numpy 数组中的内容:
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
(256, 256)
这就是我想要的:(上面数组中每个值的相同元素数组 3 次)
[[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
...
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]]
是否有任何 numpy 函数可以执行此操作?
如果没有,有没有办法在 python 数组中执行此操作并将其转换为 numpy?
您可以使用numpy.dstack
沿第三轴堆叠二维数组:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.dstack([a, a, a])
结果:
[[[1 1 1]
[2 2 2]]
[[3 3 3]
[4 4 4]]]
或者使用opencv merge
函数合并3个颜色通道
您可以通过两种方式完成:
- 您可以为此使用 opencv。要将图像从灰色转换为 RGB:
import cv2
import numpy as np
gray = np.random.rand(256, 256)
gary2rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
- 只使用numpy,可以通过以下方式实现:
import numpy as np
def convert_gray2rgb(image):
width, height = image.shape
out = np.empty((width, height, 3), dtype=np.uint8)
out[:, :, 0] = image
out[:, :, 1] = image
out[:, :, 2] = image
return out
gray = np.random.rand(256, 256) # gray scale image
gray2rgb = convert_gray2rgb(gray)
我有一个 numpy 数组格式的图像,我编写代码时假定 rgb 图像作为输入,但我发现输入由黑白图像组成。
对于应该是 RGB 的图像,即 (256,256,3) 维图像,我将输入作为灰度 (256,256) 阵列图像,我想将其转换为 (256,256,3)
这是我在 numpy 数组中的内容:
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
(256, 256)
这就是我想要的:(上面数组中每个值的相同元素数组 3 次)
[[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
...
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]]
是否有任何 numpy 函数可以执行此操作? 如果没有,有没有办法在 python 数组中执行此操作并将其转换为 numpy?
您可以使用numpy.dstack
沿第三轴堆叠二维数组:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.dstack([a, a, a])
结果:
[[[1 1 1]
[2 2 2]]
[[3 3 3]
[4 4 4]]]
或者使用opencv merge
函数合并3个颜色通道
您可以通过两种方式完成:
- 您可以为此使用 opencv。要将图像从灰色转换为 RGB:
import cv2 import numpy as np gray = np.random.rand(256, 256) gary2rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
- 只使用numpy,可以通过以下方式实现:
import numpy as np def convert_gray2rgb(image): width, height = image.shape out = np.empty((width, height, 3), dtype=np.uint8) out[:, :, 0] = image out[:, :, 1] = image out[:, :, 2] = image return out gray = np.random.rand(256, 256) # gray scale image gray2rgb = convert_gray2rgb(gray)