Uzzal Podder
Uzzal Podder

Reputation: 3215

Correct way for converting RGB heatmap image to Grayscale heatmap

I am trying to convert a RGB heatmap image to grayscale heatmap image. First I thought It was a simple rgb to grayscale conversion. But it isn't.

For example, blue color may represent soft things and red color may represent hard things.

RGB heatmap

Using commonly used simple rgb to grayscale conversion method, I found red and blue color has converted to save gray color although they had very different nature of representation.

enter image description here

But What I want something like this where blue is deep gray, and red is bright gray.

enter image description here

I had searched a lot. Unfortunately I did't find (or maybe I couldn't understand). After reading some article on rgb color model, I have found a way to generate grayscale image. My code is

import colorsys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('input_image/abnormal_hi_res.png')
img = img[ : , : , 0:3] # keep only r, g, b channels  

new_image = np.zeros((img.shape[0], img.shape[1]))

for y_pos in range(img.shape[0]):
    for x_pos in range (img.shape[1]):

        color = img[y_pos, x_pos]
        r,g,b = color
        h, _, _ = colorsys.rgb_to_hls(r, g, b) 
        new_image[y_pos, x_pos] = 1.0 - h

plt.imshow(new_image, cmap='gray')
plt.show()

But I believe there should exists a good method backed by proven mathematics.
Please help me to find out the correct one for this problem.

Upvotes: 2

Views: 4672

Answers (1)

Fahim Sikder
Fahim Sikder

Reputation: 31

You can follow these links. They have got some good notes on heatmaps and grayscale

https://docs.opencv.org/3.1.0/de/d25/imgproc_color_conversions.html https://matplotlib.org/users/colormaps.html

*UPDATE

First, you need to convert your BGR image to LUV then convert it to a grayscale image. Use opencv.

Code for converting BGR to LUV in opencv.

gray = cv2.cvtColor(img, cv2.COLOR_BGR2LUV)

I think it what you are looking for

Upvotes: 2

Related Questions