Add PCD v2 preprocessing helper for inference
Browse files- inference.py +110 -0
inference.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
from skimage.feature import graycomatrix, graycoprops, local_binary_pattern
|
| 4 |
+
|
| 5 |
+
GLCM_PROPS = ["contrast", "dissimilarity", "homogeneity", "energy", "correlation", "ASM"]
|
| 6 |
+
|
| 7 |
+
FEATURE_COLS = [
|
| 8 |
+
"H_mean", "H_std", "S_mean", "S_std", "V_mean", "V_std",
|
| 9 |
+
"L_mean", "L_std", "a_mean", "a_std", "b_mean", "b_std",
|
| 10 |
+
"GLCM_contrast", "GLCM_dissimilarity", "GLCM_homogeneity",
|
| 11 |
+
"GLCM_energy", "GLCM_correlation", "GLCM_ASM",
|
| 12 |
+
*[f"LBP_bin_{i}" for i in range(10)],
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def preprocess(image_path: str, feature_cols: list[str] | None = None, target_l: float = 0.716) -> np.ndarray:
|
| 17 |
+
"""Preprocess a raw leaf image (PCD v2) and extract 28 features for RF inference."""
|
| 18 |
+
img_bgr = cv2.imread(str(image_path))
|
| 19 |
+
if img_bgr is None:
|
| 20 |
+
raise FileNotFoundError(f"Could not read image: {image_path}")
|
| 21 |
+
|
| 22 |
+
# 1. Aspect-ratio resize (long_side=800)
|
| 23 |
+
h, w = img_bgr.shape[:2]
|
| 24 |
+
s = 800 / max(h, w)
|
| 25 |
+
img_work = cv2.resize(img_bgr, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
|
| 26 |
+
|
| 27 |
+
# 2. Adaptive Gamma on CIE-LAB L*
|
| 28 |
+
lab = cv2.cvtColor(img_work, cv2.COLOR_BGR2LAB)
|
| 29 |
+
m = float(np.clip(lab[:, :, 0].mean() / 255.0, 0.05, 0.95))
|
| 30 |
+
g = float(np.clip(np.log(target_l) / np.log(m), 0.8, 1.25))
|
| 31 |
+
if abs(g - 1.0) >= 1e-6:
|
| 32 |
+
lut = (((np.arange(256) / 255.0) ** g) * 255).astype(np.uint8)
|
| 33 |
+
lab[:, :, 0] = cv2.LUT(lab[:, :, 0], lut)
|
| 34 |
+
img_work = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
| 35 |
+
|
| 36 |
+
# 3. Bilateral filter + CLAHE
|
| 37 |
+
img_bilat = cv2.bilateralFilter(img_work, d=9, sigmaColor=75, sigmaSpace=75)
|
| 38 |
+
lab = cv2.cvtColor(img_bilat, cv2.COLOR_BGR2LAB)
|
| 39 |
+
l, a, b = cv2.split(lab)
|
| 40 |
+
l_clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l)
|
| 41 |
+
img_c1 = cv2.cvtColor(cv2.merge([l_clahe, a, b]), cv2.COLOR_LAB2BGR)
|
| 42 |
+
|
| 43 |
+
# 4. Leaf ROI segmentation (Otsu on LAB-b & HSV-S + morphology)
|
| 44 |
+
_, _, b_ch = cv2.split(cv2.cvtColor(img_c1, cv2.COLOR_BGR2LAB))
|
| 45 |
+
_, s_ch, _ = cv2.split(cv2.cvtColor(img_c1, cv2.COLOR_BGR2HSV))
|
| 46 |
+
_, mask_b = cv2.threshold(b_ch, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 47 |
+
_, mask_s = cv2.threshold(s_ch, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 48 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
|
| 49 |
+
mask = cv2.morphologyEx(cv2.bitwise_or(mask_b, mask_s), cv2.MORPH_OPEN, kernel, iterations=1)
|
| 50 |
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
|
| 51 |
+
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
|
| 52 |
+
if num_labels > 1:
|
| 53 |
+
mask = np.where(labels == 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]), 255, 0).astype(np.uint8)
|
| 54 |
+
|
| 55 |
+
# 5. Crop & pad ROI to 224x224
|
| 56 |
+
ys, xs = np.where(mask > 0)
|
| 57 |
+
if len(xs) == 0 or len(ys) == 0:
|
| 58 |
+
roi_224 = cv2.resize(img_c1, (224, 224))
|
| 59 |
+
mask_224 = cv2.resize(mask, (224, 224), interpolation=cv2.INTER_NEAREST)
|
| 60 |
+
else:
|
| 61 |
+
x1, x2, y1, y2 = np.min(xs), np.max(xs), np.min(ys), np.max(ys)
|
| 62 |
+
max_side = int(max(y2 - y1, x2 - x1) * 1.16)
|
| 63 |
+
cx, cy, half = (x1 + x2) // 2, (y1 + y2) // 2, max_side // 2
|
| 64 |
+
img_masked = cv2.bitwise_and(img_c1, img_c1, mask=mask)
|
| 65 |
+
h_img, w_img = img_c1.shape[:2]
|
| 66 |
+
canvas_img = np.zeros((max_side, max_side, 3), dtype=np.uint8)
|
| 67 |
+
canvas_mask = np.zeros((max_side, max_side), dtype=np.uint8)
|
| 68 |
+
sx1, sy1 = max(0, cx - half), max(0, cy - half)
|
| 69 |
+
sx2, sy2 = min(w_img, cx - half + max_side), min(h_img, cy - half + max_side)
|
| 70 |
+
dx1, dy1 = sx1 - (cx - half), sy1 - (cy - half)
|
| 71 |
+
canvas_img[dy1:dy1 + (sy2 - sy1), dx1:dx1 + (sx2 - sx1)] = img_masked[sy1:sy2, sx1:sx2]
|
| 72 |
+
canvas_mask[dy1:dy1 + (sy2 - sy1), dx1:dx1 + (sx2 - sx1)] = mask[sy1:sy2, sx1:sx2]
|
| 73 |
+
roi = cv2.resize(canvas_img, (224, 224), interpolation=cv2.INTER_AREA)
|
| 74 |
+
mask_224 = cv2.resize(canvas_mask, (224, 224), interpolation=cv2.INTER_NEAREST)
|
| 75 |
+
roi_224 = cv2.bitwise_and(roi, roi, mask=mask_224)
|
| 76 |
+
|
| 77 |
+
# 6. Extract 28 handcrafted features (12 Color + 6 GLCM + 10 LBP)
|
| 78 |
+
hsv = cv2.cvtColor(roi_224, cv2.COLOR_BGR2HSV).astype(np.float32)
|
| 79 |
+
lab = cv2.cvtColor(roi_224, cv2.COLOR_BGR2LAB).astype(np.float32)
|
| 80 |
+
gray = cv2.cvtColor(roi_224, cv2.COLOR_BGR2GRAY)
|
| 81 |
+
valid = (mask_224 > 0) if np.sum(mask_224 > 0) > 50 else np.ones(gray.shape, dtype=bool)
|
| 82 |
+
|
| 83 |
+
feats = {}
|
| 84 |
+
for idx, ch in enumerate(["H", "S", "V"]):
|
| 85 |
+
vals = hsv[:, :, idx][valid]
|
| 86 |
+
feats[f"{ch}_mean"], feats[f"{ch}_std"] = float(np.mean(vals)), float(np.std(vals))
|
| 87 |
+
for idx, ch in enumerate(["L", "a", "b"]):
|
| 88 |
+
vals = lab[:, :, idx][valid]
|
| 89 |
+
feats[f"{ch}_mean"], feats[f"{ch}_std"] = float(np.mean(vals)), float(np.std(vals))
|
| 90 |
+
|
| 91 |
+
gray_glcm = np.where(valid, np.clip(gray, 1, 255), 0).astype(np.uint8)
|
| 92 |
+
glcm = graycomatrix(
|
| 93 |
+
gray_glcm, distances=[1, 2],
|
| 94 |
+
angles=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],
|
| 95 |
+
levels=256, symmetric=True, normed=False,
|
| 96 |
+
)
|
| 97 |
+
glcm[0, :, :, :] = 0
|
| 98 |
+
glcm[:, 0, :, :] = 0
|
| 99 |
+
glcm_sum = np.sum(glcm, axis=(0, 1), keepdims=True)
|
| 100 |
+
glcm_norm = np.divide(glcm.astype(np.float64), glcm_sum, out=np.zeros_like(glcm, dtype=np.float64), where=glcm_sum > 0)
|
| 101 |
+
for prop in GLCM_PROPS:
|
| 102 |
+
feats[f"GLCM_{prop}"] = float(np.mean(graycoprops(glcm_norm, prop)))
|
| 103 |
+
|
| 104 |
+
lbp = local_binary_pattern(gray, P=8, R=1, method="uniform")
|
| 105 |
+
hist, _ = np.histogram(lbp[valid], bins=np.arange(0, 11), density=True)
|
| 106 |
+
for i in range(10):
|
| 107 |
+
feats[f"LBP_bin_{i}"] = float(hist[i])
|
| 108 |
+
|
| 109 |
+
cols = feature_cols or FEATURE_COLS
|
| 110 |
+
return np.array([[feats[c] for c in cols]], dtype=np.float64)
|