简体   繁体   中英

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,

在此处输入图像描述

and I want to convert it to RGB. I tried several ways eg 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,

在此处输入图像描述

What should I do? Thanks in advance!

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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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