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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Image preprocessing pipeline for infrared thermal images.
|
| 3 |
+
|
| 4 |
+
Implements: resize, bilateral denoising, CLAHE enhancement,
|
| 5 |
+
normalization, and ROI extraction.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Tuple, Optional
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ThermalImageProcessor:
|
| 15 |
+
"""
|
| 16 |
+
Preprocessing pipeline for infrared thermal images.
|
| 17 |
+
|
| 18 |
+
Pipeline steps (in order):
|
| 19 |
+
1. Load image (grayscale)
|
| 20 |
+
2. Resize to target dimensions
|
| 21 |
+
3. Bilateral filter denoising
|
| 22 |
+
4. CLAHE contrast enhancement
|
| 23 |
+
5. Min-Max normalization to [0, 1]
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
image_size: Tuple[int, int] = (224, 224),
|
| 29 |
+
bilateral_d: int = 9,
|
| 30 |
+
bilateral_sigma_color: float = 75.0,
|
| 31 |
+
bilateral_sigma_space: float = 75.0,
|
| 32 |
+
clahe_clip_limit: float = 2.0,
|
| 33 |
+
clahe_tile_grid_size: Tuple[int, int] = (8, 8),
|
| 34 |
+
normalize: bool = True,
|
| 35 |
+
):
|
| 36 |
+
self.image_size = image_size
|
| 37 |
+
self.bilateral_d = bilateral_d
|
| 38 |
+
self.bilateral_sigma_color = bilateral_sigma_color
|
| 39 |
+
self.bilateral_sigma_space = bilateral_sigma_space
|
| 40 |
+
self.clahe_clip_limit = clahe_clip_limit
|
| 41 |
+
self.clahe_tile_grid_size = clahe_tile_grid_size
|
| 42 |
+
self.normalize = normalize
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_config(cls, config) -> "ThermalImageProcessor":
|
| 46 |
+
"""Create processor from a Config object."""
|
| 47 |
+
img_size = tuple(config.data.image_size)
|
| 48 |
+
pp = config.preprocessing
|
| 49 |
+
return cls(
|
| 50 |
+
image_size=img_size,
|
| 51 |
+
bilateral_d=pp.bilateral_filter.d,
|
| 52 |
+
bilateral_sigma_color=pp.bilateral_filter.sigma_color,
|
| 53 |
+
bilateral_sigma_space=pp.bilateral_filter.sigma_space,
|
| 54 |
+
clahe_clip_limit=pp.clahe.clip_limit,
|
| 55 |
+
clahe_tile_grid_size=tuple(pp.clahe.tile_grid_size),
|
| 56 |
+
normalize=pp.normalize,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# ------------------------------------------------------------------
|
| 60 |
+
# Core pipeline
|
| 61 |
+
# ------------------------------------------------------------------
|
| 62 |
+
|
| 63 |
+
def load_image(self, image_path: str) -> np.ndarray:
|
| 64 |
+
"""Load an image as grayscale. Raises if file not found."""
|
| 65 |
+
path = Path(image_path)
|
| 66 |
+
if not path.exists():
|
| 67 |
+
raise FileNotFoundError(f"Image not found: {path}")
|
| 68 |
+
|
| 69 |
+
img = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
|
| 70 |
+
if img is None:
|
| 71 |
+
raise ValueError(f"Failed to decode image: {path}")
|
| 72 |
+
return img
|
| 73 |
+
|
| 74 |
+
def resize(self, image: np.ndarray) -> np.ndarray:
|
| 75 |
+
"""Resize to the configured target size."""
|
| 76 |
+
return cv2.resize(image, self.image_size, interpolation=cv2.INTER_LINEAR)
|
| 77 |
+
|
| 78 |
+
def denoise(self, image: np.ndarray) -> np.ndarray:
|
| 79 |
+
"""Apply bilateral filter for edge-preserving noise removal."""
|
| 80 |
+
return cv2.bilateralFilter(
|
| 81 |
+
image,
|
| 82 |
+
self.bilateral_d,
|
| 83 |
+
self.bilateral_sigma_color,
|
| 84 |
+
self.bilateral_sigma_space,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def enhance_contrast(self, image: np.ndarray) -> np.ndarray:
|
| 88 |
+
"""Apply CLAHE for adaptive contrast enhancement."""
|
| 89 |
+
clahe = cv2.createCLAHE(
|
| 90 |
+
clipLimit=self.clahe_clip_limit,
|
| 91 |
+
tileGridSize=self.clahe_tile_grid_size,
|
| 92 |
+
)
|
| 93 |
+
return clahe.apply(image)
|
| 94 |
+
|
| 95 |
+
def normalize_image(self, image: np.ndarray) -> np.ndarray:
|
| 96 |
+
"""Min-Max normalization to [0, 1] float32."""
|
| 97 |
+
img = image.astype(np.float32)
|
| 98 |
+
min_val, max_val = img.min(), img.max()
|
| 99 |
+
if max_val - min_val > 0:
|
| 100 |
+
img = (img - min_val) / (max_val - min_val)
|
| 101 |
+
else:
|
| 102 |
+
img = np.zeros_like(img)
|
| 103 |
+
return img
|
| 104 |
+
|
| 105 |
+
def process(self, image_path: str) -> np.ndarray:
|
| 106 |
+
"""
|
| 107 |
+
Run the full preprocessing pipeline on an image file.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
image_path: Path to a thermal image.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
Preprocessed image as a float32 array in [0, 1], shape (H, W).
|
| 114 |
+
"""
|
| 115 |
+
img = self.load_image(image_path)
|
| 116 |
+
img = self.resize(img)
|
| 117 |
+
img = self.denoise(img)
|
| 118 |
+
img = self.enhance_contrast(img)
|
| 119 |
+
if self.normalize:
|
| 120 |
+
img = self.normalize_image(img)
|
| 121 |
+
return img
|
| 122 |
+
|
| 123 |
+
def process_array(self, image: np.ndarray) -> np.ndarray:
|
| 124 |
+
"""
|
| 125 |
+
Run the pipeline on an already-loaded numpy array (grayscale).
|
| 126 |
+
"""
|
| 127 |
+
img = self.resize(image)
|
| 128 |
+
img = self.denoise(img)
|
| 129 |
+
img = self.enhance_contrast(img)
|
| 130 |
+
if self.normalize:
|
| 131 |
+
img = self.normalize_image(img)
|
| 132 |
+
return img
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------
|
| 135 |
+
# Utility helpers
|
| 136 |
+
# ------------------------------------------------------------------
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
def extract_roi(
|
| 140 |
+
image: np.ndarray,
|
| 141 |
+
bbox: Optional[Tuple[int, int, int, int]] = None,
|
| 142 |
+
) -> np.ndarray:
|
| 143 |
+
"""
|
| 144 |
+
Extract a region of interest.
|
| 145 |
+
|
| 146 |
+
If *bbox* is None, auto-detect via thresholding + contours.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
image: Grayscale image.
|
| 150 |
+
bbox: (x, y, w, h) or None for auto-detect.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
Cropped image of the ROI.
|
| 154 |
+
"""
|
| 155 |
+
if bbox is not None:
|
| 156 |
+
x, y, w, h = bbox
|
| 157 |
+
return image[y : y + h, x : x + w]
|
| 158 |
+
|
| 159 |
+
# Auto-detect: threshold → largest contour
|
| 160 |
+
if image.dtype == np.float32 or image.dtype == np.float64:
|
| 161 |
+
img_uint8 = (image * 255).astype(np.uint8)
|
| 162 |
+
else:
|
| 163 |
+
img_uint8 = image.copy()
|
| 164 |
+
|
| 165 |
+
_, thresh = cv2.threshold(img_uint8, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 166 |
+
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 167 |
+
|
| 168 |
+
if not contours:
|
| 169 |
+
return image # fallback: return full image
|
| 170 |
+
|
| 171 |
+
largest = max(contours, key=cv2.contourArea)
|
| 172 |
+
x, y, w, h = cv2.boundingRect(largest)
|
| 173 |
+
return image[y : y + h, x : x + w]
|
| 174 |
+
|
| 175 |
+
@staticmethod
|
| 176 |
+
def compute_thermal_stats(image: np.ndarray) -> dict:
|
| 177 |
+
"""Compute basic thermal statistics of an image."""
|
| 178 |
+
return {
|
| 179 |
+
"mean": float(np.mean(image)),
|
| 180 |
+
"std": float(np.std(image)),
|
| 181 |
+
"min": float(np.min(image)),
|
| 182 |
+
"max": float(np.max(image)),
|
| 183 |
+
"median": float(np.median(image)),
|
| 184 |
+
}
|