| """ |
| Gleason_CNN masklerinden polygon CSV'si üretir → polygons.csv |
| |
| Maske değer sözlüğü (palette PNG, tam sayı indeks): |
| 0 = Benign |
| 1 = Gleason_3 → G3 |
| 2 = Gleason_4 → G4 |
| 3 = Gleason_5 → G5 |
| 4 = unlabelled → atlanır |
| |
| Üç kaynak klasör ve karşılık gelen creator: |
| Gleason_masks_train → "train" |
| Gleason_masks_test_pathologist1 → "test_pathologist1" |
| Gleason_masks_test_pathologist2 → "test_pathologist2" |
| |
| Her polygon seyreltilir (approxPolyDP, epsilon_start=2.0, max_points=50). |
| """ |
|
|
| import csv |
| import json |
| import os |
| import re |
| from pathlib import Path |
|
|
| import cv2 |
| import numpy as np |
| from PIL import Image |
|
|
| |
| |
| |
|
|
| ORIGIN_DIR = Path("origin") |
| OUT_CSV = Path("polygons.csv") |
|
|
| LABEL_MAP = {0: "Benign", 1: "G3", 2: "G4", 3: "G5"} |
|
|
| MIN_AREA = 150 |
| EPSILON_START = 2.0 |
| MAX_POINTS = 50 |
|
|
| SOURCES = [ |
| ("Gleason_masks_train", "train", re.compile(r"^mask_(.+)\.png$")), |
| ("Gleason_masks_test_pathologist1", "test_pathologist1", re.compile(r"^mask1_(.+)\.png$")), |
| ("Gleason_masks_test_pathologist2", "test_pathologist2", re.compile(r"^mask2_(.+)\.png$")), |
| ] |
|
|
|
|
| |
| |
| |
|
|
| def simplify_contour(contour) -> list[list[int]] | None: |
| """Kontur → basitleştirilmiş kapalı polygon noktaları [[x, y], ...].""" |
| approx = cv2.approxPolyDP(contour, EPSILON_START, closed=True) |
| eps = EPSILON_START |
| while len(approx) > MAX_POINTS and eps <= 20.0: |
| eps *= 1.5 |
| approx = cv2.approxPolyDP(approx.astype(np.float32), eps, 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 remove_small_components(binary: np.ndarray) -> np.ndarray: |
| 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 process_mask(mask_path: Path, creator: str, image_name: str) -> list[dict]: |
| """Maskten polygon satırlarını üretir.""" |
| try: |
| arr = np.array(Image.open(mask_path)) |
| except Exception as e: |
| print(f" UYARI okuma hatası ({mask_path.name}): {e}") |
| return [] |
|
|
| rows = [] |
| for class_idx, label in LABEL_MAP.items(): |
| binary = (arr == class_idx).astype(np.uint8) |
| if binary.sum() == 0: |
| continue |
|
|
| binary = remove_small_components(binary) |
| if binary.sum() == 0: |
| continue |
|
|
| contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| for cnt in contours: |
| if cv2.contourArea(cnt) < MIN_AREA: |
| continue |
| pts = simplify_contour(cnt) |
| if pts is None: |
| continue |
| rows.append({ |
| "image_name": image_name, |
| "label": label, |
| "polygon": json.dumps(pts), |
| "creator": creator, |
| }) |
| return rows |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| all_rows: list[dict] = [] |
|
|
| for folder_name, creator, name_re in SOURCES: |
| folder = ORIGIN_DIR / folder_name |
| if not folder.exists(): |
| print(f"UYARI: klasör bulunamadı → {folder}") |
| continue |
|
|
| mask_files = sorted( |
| p for p in folder.glob("*.png") |
| if not p.name.startswith("._") |
| ) |
| print(f"\n{folder_name} ({len(mask_files)} maske) creator='{creator}'") |
|
|
| skipped = 0 |
| for mf in mask_files: |
| m = name_re.match(mf.name) |
| if not m: |
| skipped += 1 |
| continue |
| image_name = m.group(1) |
| rows = process_mask(mf, creator, image_name) |
| all_rows.extend(rows) |
|
|
| if skipped: |
| print(f" {skipped} dosya isim kalıbına uymadı, atlandı.") |
|
|
| print(f"\nToplam {len(all_rows)} polygon satırı → {OUT_CSV}") |
| with open(OUT_CSV, "w", newline="") as f: |
| writer = csv.DictWriter( |
| f, fieldnames=["image_name", "label", "polygon", "creator"] |
| ) |
| writer.writeheader() |
| writer.writerows(all_rows) |
|
|
| print("Tamamlandı.") |
|
|
|
|
| if __name__ == "__main__": |
| os.chdir(Path(__file__).parent) |
| main() |
|
|