Home > Mobile >  how to localize red regions in heatmap using opencv?
how to localize red regions in heatmap using opencv?

Time:12-15

I am generating a heat map using an anomaly detection framework, and the output is something like this image.

the output is like this:

enter image description here

How can I mark the red regions on the original images? like a circle around the red part on the original image.

CodePudding user response:

So let's say you have this heatmap.

Heatmap

It was actually generated from some intensity data, some prediction you obtained from your algorithm. That's what we need, not the heatmap itself. It is usually a "grayscale image", it has no color, only intensity values. Usually it is from 0.0 to 1.0 (could be also from 0 to 255) and if you were to plot it, it would like that.

Prediction

So now to obtain "red" areas you just need regions with high intensity. We must do "thresholding" to obtain them.

max_val = 1.0             # could be 255 in your case, you must check
prediction /= max_val     # normalize
mask = prediction > 0.9

Threshold in this case is 0.9, you can make it smaller to make "red" regions larger. We will get the following mask:

Thresholded mask

Now we can either blend this mask with our original image:

alpha = 0.5    
original[mask] = original[mask] * (1 - alpha)   np.array([0, 0, 255]) * alpha

... and get this:

Masked image

Or we can find some contours on the mask and encircle them:

contours, _ = cv2.findContours(mask.astype(np.uint8), 
                               cv2.RETR_EXTERNAL, 
                               cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    center = np.average(cnt, axis=0)
    radius = np.max(np.linalg.norm((cnt - center)[:, 0], axis=1))
    radius = max(radius, 10.0)
    cv2.circle(original, center[0].astype(np.int32), int(radius), (0, 0, 255), 2)

... to get this:

Circled

  • Related