| """ |
| Polygon seyreltme karşılaştırma testi. |
| |
| Kullanım: |
| python test_simplify.py |
| python test_simplify.py --epsilon 3.0 --max-points 30 |
| """ |
|
|
| import argparse |
| import json |
| import random |
| import sys |
| from pathlib import Path |
|
|
| import cv2 |
| import matplotlib.patches as mpatches |
| import matplotlib.pyplot as plt |
| import numpy as np |
| from matplotlib.patches import Polygon as MplPolygon |
| from scipy.ndimage import gaussian_filter1d |
| from scipy.signal import find_peaks |
|
|
| BASE = Path(__file__).parent / "SICAPv2" |
| MASKS_DIR = BASE / "masks" |
| IMGS_DIR = BASE / "images" |
|
|
| GRADE_RANGES = [(30, 80, "G3"), (80, 125, "G4"), (125, 256, "G5")] |
| GRADE_COLORS = {"G3": "#00cc44", "G4": "#ff8800", "G5": "#ff2222"} |
| MERGE_DIST = 20 |
| MIN_AREA = 100 |
|
|
|
|
| |
| |
| |
|
|
| def grade_for_value(val): |
| for lo, hi, grade in GRADE_RANGES: |
| if lo <= val < hi: |
| return grade |
| return None |
|
|
|
|
| def calibrate(gray): |
| hist = np.bincount(gray.ravel(), minlength=256).astype(float) |
| smooth = gaussian_filter1d(hist[8:], sigma=2) |
| min_h = max(smooth.max() * 0.02, 5) |
| idxs, _ = find_peaks(smooth, height=min_h, distance=10, prominence=min_h * 0.3) |
| peaks = sorted([(int(i + 8), int(hist[i + 8])) for i in idxs]) |
|
|
| merged = [] |
| for val, cnt in peaks: |
| if merged and val - merged[-1][0] <= MERGE_DIST: |
| merged[-1] = (val, cnt) if cnt > merged[-1][1] else merged[-1] |
| else: |
| merged.append((val, cnt)) |
|
|
| grade_map = {} |
| for val, _ in merged: |
| g = grade_for_value(val) |
| if g and g not in grade_map.values(): |
| grade_map[val] = g |
| return grade_map |
|
|
|
|
| def quantize(gray, centers): |
| q = np.zeros_like(gray, dtype=np.int32) |
| all_c = sorted([0] + list(centers)) |
| for i in range(1, len(all_c)): |
| c = all_c[i] |
| lo = (all_c[i - 1] + c) // 2 |
| hi = (all_c[i + 1] + c) // 2 if i + 1 < len(all_c) else 256 |
| q[(gray >= lo) & (gray < hi)] = c |
| return q |
|
|
|
|
| def remove_small(binary): |
| n, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8) |
| clean = np.zeros_like(binary) |
| for lid in range(1, n): |
| if stats[lid, cv2.CC_STAT_AREA] >= MIN_AREA: |
| clean[labels == lid] = 1 |
| return clean |
|
|
|
|
| |
| |
| |
|
|
| def extract_original(cnt): |
| """Mevcut yöntem: epsilon=0.5""" |
| approx = cv2.approxPolyDP(cnt, 0.5, closed=True) |
| if len(approx) < 3: |
| return None |
| pts = [[int(p[0][0]), int(p[0][1])] for p in approx] |
| pts.append(pts[0]) |
| return pts |
|
|
|
|
| def extract_simplified(cnt, epsilon_start=1.0, max_points=80): |
| """Yeni yöntem: başlangıç epsilon yüksek + adaptif seyreltme.""" |
| approx = cv2.approxPolyDP(cnt, epsilon_start, closed=True) |
| arr = approx.astype(np.float32) |
| eps = epsilon_start |
| while len(arr) > max_points and eps <= 20: |
| eps *= 1.5 |
| arr = cv2.approxPolyDP(arr, eps, closed=True).astype(np.float32) |
| if len(arr) < 3: |
| return None |
| pts = [[int(p[0][0]), int(p[0][1])] for p in arr] |
| pts.append(pts[0]) |
| return pts |
|
|
|
|
| |
| |
| |
|
|
| def process_mask(mask_path, epsilon_start, max_points): |
| gray = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) |
| if gray is None: |
| return None, None |
|
|
| gray_clean = cv2.medianBlur(gray, 5) |
| grade_map = calibrate(gray_clean) |
| if not grade_map: |
| return None, None |
|
|
| q = quantize(gray_clean, list(grade_map.keys())) |
|
|
| orig_polys, simp_polys = [], [] |
| for center, label in grade_map.items(): |
| binary = (q == center).astype(np.uint8) |
| binary = remove_small(binary) |
| if binary.sum() == 0: |
| continue |
| cnts, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| for cnt in cnts: |
| if cv2.contourArea(cnt) < MIN_AREA: |
| continue |
| op = extract_original(cnt) |
| sp = extract_simplified(cnt, epsilon_start, max_points) |
| if op: |
| orig_polys.append((label, op)) |
| if sp: |
| simp_polys.append((label, sp)) |
|
|
| return orig_polys, simp_polys |
|
|
|
|
| |
| |
| |
|
|
| def draw_polys(ax, image, polys, title, alpha=0.35): |
| ax.imshow(image) |
| ax.set_title(title, fontsize=9) |
| ax.axis("off") |
| legend = {} |
| for label, pts in polys: |
| color = GRADE_COLORS.get(label, "#ffffff") |
| arr = np.array(pts[:-1]) |
| patch = MplPolygon(arr, closed=True, facecolor=color, |
| alpha=alpha, edgecolor=color, linewidth=1.5) |
| ax.add_patch(patch) |
| if label not in legend: |
| legend[label] = mpatches.Patch(color=color, label=label) |
| if legend: |
| ax.legend(handles=list(legend.values()), loc="upper right", |
| fontsize=8, framealpha=0.7) |
|
|
|
|
| def compare_patch(mask_path, epsilon_start, max_points): |
| stem = mask_path.stem |
| img_path = IMGS_DIR / mask_path.name |
| image = cv2.cvtColor(cv2.imread(str(img_path)), cv2.COLOR_BGR2RGB) \ |
| if img_path.exists() else np.zeros((512, 512, 3), dtype=np.uint8) |
| mask_rgb = cv2.cvtColor(cv2.imread(str(mask_path)), cv2.COLOR_BGR2RGB) |
|
|
| orig_polys, simp_polys = process_mask(mask_path, epsilon_start, max_points) |
| if orig_polys is None: |
| print(f" Kalibrasyon başarısız: {stem}") |
| return |
|
|
| orig_pts = sum(len(p) - 1 for _, p in orig_polys) |
| simp_pts = sum(len(p) - 1 for _, p in simp_polys) |
| reduction = (1 - simp_pts / orig_pts) * 100 if orig_pts else 0 |
|
|
| fig, axes = plt.subplots(1, 4, figsize=(20, 5)) |
| fig.suptitle(stem, fontsize=8, y=1.01) |
|
|
| axes[0].imshow(mask_rgb) |
| axes[0].set_title("Mask (ham)") |
| axes[0].axis("off") |
|
|
| axes[1].imshow(image) |
| axes[1].set_title("Orijinal görüntü") |
| axes[1].axis("off") |
|
|
| draw_polys(axes[2], image, orig_polys, |
| f"Mevcut (eps=0.5)\n{len(orig_polys)} poly {orig_pts} nokta") |
|
|
| draw_polys(axes[3], image, simp_polys, |
| f"Seyrelmiş (eps={epsilon_start}, max={max_points})\n" |
| f"{len(simp_polys)} poly {simp_pts} nokta (-%{reduction:.0f})") |
|
|
| plt.tight_layout() |
| plt.savefig(f"simplify_test_{stem[:40]}.png", dpi=120, bbox_inches="tight") |
| plt.show() |
| print(f" {stem}") |
| print(f" Mevcut : {len(orig_polys):3d} polygon {orig_pts:5d} nokta") |
| print(f" Seyrelmiş: {len(simp_polys):3d} polygon {simp_pts:5d} nokta (-%{reduction:.1f})") |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--epsilon", type=float, default=1.0) |
| parser.add_argument("--max-points", type=int, default=50) |
| parser.add_argument("--n", type=int, default=3, |
| help="Kaç patch test edilsin") |
| parser.add_argument("--seed", type=int, default=42) |
| args = parser.parse_args() |
|
|
| masks = sorted(MASKS_DIR.glob("*.jpg")) |
| if not masks: |
| sys.exit(f"Mask bulunamadı: {MASKS_DIR}") |
|
|
| |
| |
| masks_by_size = sorted(masks, key=lambda p: p.stat().st_size, reverse=True) |
| candidates = masks_by_size[:50] |
| random.seed(args.seed) |
| selected = random.sample(candidates, min(args.n, len(candidates))) |
|
|
| print(f"Test parametreleri: epsilon={args.epsilon} max_points={args.max_points}") |
| print(f"Seçilen {len(selected)} patch:\n") |
| for mp in selected: |
| compare_patch(mp, args.epsilon, args.max_points) |
|
|
| print("\nGörüntüler simplify_test_*.png olarak kaydedildi.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|