Here's a detailed approach with complete code for detecting hotspots in heatmaps and drawing bounding boxes around them:
Method 1: Intensity-Based Thresholding (Most Common)
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from skimage.measure import label, regionprops
def detect_hotspots_intensity(image_path, threshold_percentile=85, min_area=100):
"""
Detect hotspots based on intensity thresholding
Args:
image_path: Path to heatmap image
threshold_percentile: Percentile for thresholding (85 means top 15% brightest pixels)
min_area: Minimum area for a hotspot to be considered valid
"""
# Read image
img = cv2.imread(image_path)
original = img.copy()
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Calculate threshold based on percentile
threshold_value = np.percentile(gray, threshold_percentile)
# Create binary mask
_, binary = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_BINARY)
# Remove noise with morphological operations
kernel = np.ones((3,3), np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
# Find connected components
labeled = label(binary)
regions = regionprops(labeled)
bboxes = []
for region in regions:
if region.area >= min_area:
# Get bounding box coordinates
minr, minc, maxr, maxc = region.bbox
bboxes.append((minc, minr, maxc, maxr)) # (x1, y1, x2, y2)
# Draw rectangle on original image
cv2.rectangle(original, (minc, minr), (maxc, maxr), (0, 255, 0), 2)
return original, bboxes, binary
# Usage
result_img, bboxes, binary_mask = detect_hotspots_intensity('heatmap.jpg')
cv2.imshow('Detected Hotspots', result_img)
cv2.imshow('Binary Mask', binary_mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
Method 2: Color-Based Detection (For Colored Heatmaps)
def detect_hotspots_color(image_path, color_range='red', min_area=100):
"""
Detect hotspots based on color (useful for red/yellow hotspots)
Args:
image_path: Path to heatmap image
color_range: 'red', 'yellow', or 'custom'
min_area: Minimum area for detection
"""
img = cv2.imread(image_path)
original = img.copy()
# Convert to HSV color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define color ranges
if color_range == 'red':
# Red color range (covers both red hues)
lower1 = np.array([0, 50, 50])
upper1 = np.array([10, 255, 255])
lower2 = np.array([170, 50, 50])
upper2 = np.array([180, 255, 255])
mask1 = cv2.inRange(hsv, lower1, upper1)
mask2 = cv2.inRange(hsv, lower2, upper2)
mask = mask1 + mask2
elif color_range == 'yellow':
lower = np.array([20, 50, 50])
upper = np.array([30, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
# Clean up mask
kernel = np.ones((5,5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
bboxes = []
for contour in contours:
area = cv2.contourArea(contour)
if area >= min_area:
x, y, w, h = cv2.boundingRect(contour)
bboxes.append((x, y, x+w, y+h))
cv2.rectangle(original, (x, y), (x+w, y+h), (0, 255, 0), 2)
return original, bboxes, mask
# Usage
result_img, bboxes, color_mask = detect_hotspots_color('heatmap.jpg', 'red')