Reputation: 388
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.
for what should have been a RGB i.e (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)
This is what I have in numpy array:
[[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)
[[[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? If not is there any way to do this in python array and convert it to numpy?
Upvotes: 2
Views: 9039
Reputation: 553
You can do it in two ways:
import cv2 import numpy as np gray = np.random.rand(256, 256) gary2rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
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)
Upvotes: 3
Reputation: 1280
You can use numpy.dstack
to stack the 2D arrays along the third axis:
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.
Upvotes: 6