简体   繁体   English

如何将1d数组转换为3d数组(将灰度图像转换为rgb格式)?

[英]How to convert 1d array to 3d array (convert grayscale image so rgb format )?

I have an image in the numpy array format, I wrote the code assuming rgb image as input but I have found that the input consists of black and white image. 我有一个numpy数组格式的图像,我编写的代码假定rgb图像作为输入,但是我发现输入包含黑白图像。

for what should have been a RGB ie (256,256,3) dimension image, I got the input as Grayscale (256,256) array image and I want to convert it to (256,256,3) 对于应该是RGB即(256,256,3)尺寸的图像,我将输入作为灰度(256,256)阵列图像,并将其转换为(256,256,3)

This is what I have in numpy array: 这是我在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)

This is what I want:(an array of same elements 3 times for every value in the array above) 这就是我想要的:(相同元素的数组为上面数组中的每个值重复3次)

[[[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  ...
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]]

Is there any numpy function that does this? 是否有任何numpy函数可以做到这一点? If not is there any way to do this in python array and convert it to numpy? 如果没有,有什么办法可以在python数组中将其转换为numpy吗?

You can use numpy.dstack to stack the 2D arrays along the third axis: 您可以使用numpy.dstack沿第三轴堆叠2D数组:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.dstack([a, a, a])

results: 结果:

[[[1 1 1]
  [2 2 2]]
 [[3 3 3]
  [4 4 4]]]

or use opencv merge function to merge 3 color channels. 或使用opencv merge功能合并3个颜色通道。

You can do it in two ways: 您可以通过两种方式进行操作:

  1. You can use opencv for this. 您可以为此使用opencv。 To converts the image from Gray to RGB: 要将图像从灰度转换为RGB:
 import cv2 import numpy as np gray = np.random.rand(256, 256) gary2rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) 
  1. Using only numpy, you can do it in the following way: 仅使用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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM