Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy 2D image to 3D

Tags:

python

numpy

I have a greyscale image represented as 2D numpy array and want to make it a 3D numpy array representing a color rgb image (which is obviously still grey).

img.shape       // (100, 100)
img[10, 10]     // e.g. 42

// do something

img.shape       // (100, 100, 3)
img[10, 10]     // e.g. [42, 42, 42]

I found this question which asked the opposite: numpy 3D-image array to 2D

like image 669
QuantumX Avatar asked Oct 28 '25 14:10

QuantumX


2 Answers

You can use Numpy's dstack() to stack three grey images depthwise:

RGB = np.dstack((grey, grey, grey))
like image 55
Mark Setchell Avatar answered Oct 30 '25 06:10

Mark Setchell


You could use an opencv function for this: image_color = cv2.cvtColor(image_gray, colorcode).

See the available colorcodes in documentation https://docs.opencv.org/3.4/d8/d01/group__imgproc__color__conversions.html

The right one for you could be cv2.COLOR_GRAY2RGB.

import cv2
image_color = cv2.cvtColor(image_gray, cv2.COLOR_GRAY2RGB)

That would give you the grayscale image as 3 channel rgb array.

Using numpy you could look at https://stackoverflow.com/a/40119878/14997346

like image 44
chillking Avatar answered Oct 30 '25 05:10

chillking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!