Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Grayscale image to RGB

I have a grayscale image as a numpy array with the following properties

shape = ( 3524, 3022), dtype = float32, min = 0.0, max = 1068.16

The gray image plotted as plt.imshow( gray, cmap = 'gray, vmin = 0, vmax = 80) looks like that,

enter image description here

and I want to convert it to RGB. I tried several ways e.g. np.stack, cv2.merge, cv2.color creating a 3D np.zeros image and assign to each channel the grayscale image. When I plot the 3D image I am getting a very dim image and the 'blobs' cannot be seen at all. I tried also, to transform its range to [ 0, 1] or [ 0, 255] range to non avail.

Using np.stack plt.imshow( np.stack(( new,)*3, axis = 2)), I am getting this,

enter image description here

What should I do? Thanks in advance!

like image 589
vpap Avatar asked Apr 17 '26 13:04

vpap


2 Answers

One way to normalize an image is using cv2.normalize with norm_type=cv2.NORM_MINMAX. It will stretch or compress your data to the range 0 to 255 (using alpha and beta arguments) and save as 8-bit type.

# normalize
norm = cv2.normalize(gray, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
print(norm.shape, norm.dtype)

# convert to 3 channel
norm = cv2.cvtColor(norm, cv2.COLOR_GRAY2BGR)
print(norm.shape, norm.dtype)
print(np.amin(norm),np.amax(norm))
like image 179
fmw42 Avatar answered Apr 20 '26 03:04

fmw42


By passing vmin=0,vmax=80 to plt.imshow you basically clip the image and rescale. So you can just do that:

gray_normalized = gray.clip(0,80)/80 * 255

# stack:
rgb = np.stack([gray_normalized]*3, axis=2)

cv2.imwrite('output.png', gray_normalized)
like image 39
Quang Hoang Avatar answered Apr 20 '26 02:04

Quang Hoang