| """ |
| Gleason_CNN polygon CSV'sini doğrular ve görsel karşılaştırma üretir. |
| |
| Kullanım: |
| python validate_polygons.py # 3 rastgele patch |
| python validate_polygons.py --n 5 --seed 7 |
| python validate_polygons.py --creator test_pathologist1 --n 2 |
| |
| Çıktılar: |
| - Konsol: istatistikler (label dağılımı, creator dağılımı, nokta sayıları) |
| - PNG: validate_<image_name>.png (maske + orijinal + polygon overlay) |
| """ |
|
|
| 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 |
| import pandas as pd |
| from matplotlib.patches import Polygon as MplPolygon |
| from PIL import Image |
|
|
| ORIGIN_DIR = Path("origin") |
| CSV_PATH = Path("polygons.csv") |
|
|
| |
| CLASS_COLORS = { |
| "Benign": "#00cc44", |
| "G3": "#4488ff", |
| "G4": "#ffdd00", |
| "G5": "#ff2222", |
| } |
|
|
| |
| SOURCE_INFO = { |
| "train": ("Gleason_masks_train", "mask_"), |
| "test_pathologist1": ("Gleason_masks_test_pathologist1", "mask1_"), |
| "test_pathologist2": ("Gleason_masks_test_pathologist2", "mask2_"), |
| } |
|
|
| |
| MASK_LABEL = {0: "Benign", 1: "G3", 2: "G4", 3: "G5"} |
|
|
| |
| def find_image_path(image_name: str) -> Path | None: |
| parts = image_name.split("_") |
| for n in range(len(parts), 0, -1): |
| tma_id = "_".join(parts[:n]) |
| candidate = ORIGIN_DIR / tma_id / f"{image_name}.jpg" |
| if candidate.exists(): |
| return candidate |
| return None |
|
|
|
|
| def find_mask_path(image_name: str, creator: str) -> Path | None: |
| folder_name, prefix = SOURCE_INFO[creator] |
| candidate = ORIGIN_DIR / folder_name / f"{prefix}{image_name}.png" |
| return candidate if candidate.exists() else None |
|
|
|
|
| |
| |
| |
|
|
| def print_stats(df: pd.DataFrame): |
| print(f"\n{'='*60}") |
| print(f"Toplam polygon satırı : {len(df):,}") |
| print(f"\nLabel dağılımı:") |
| for label, cnt in df["label"].value_counts().items(): |
| print(f" {label:8s}: {cnt:6,}") |
| print(f"\nCreator dağılımı:") |
| for creator, cnt in df["creator"].value_counts().items(): |
| print(f" {creator:25s}: {cnt:6,}") |
| lengths = df["polygon"].apply(lambda s: len(json.loads(s)) - 1) |
| print(f"\nPolygon nokta sayısı (kapanış hariç):") |
| print(f" min={lengths.min()} max={lengths.max()} " |
| f"medyan={lengths.median():.0f} ort={lengths.mean():.1f}") |
| print(f"{'='*60}\n") |
|
|
|
|
| |
| |
| |
|
|
| def draw_polygons(ax, image_rgb, polys: list[tuple[str, list]], title: str): |
| ax.imshow(image_rgb) |
| ax.set_title(title, fontsize=8) |
| ax.axis("off") |
| legend = {} |
| for label, pts in polys: |
| color = CLASS_COLORS.get(label, "#ffffff") |
| arr = np.array(pts[:-1]) |
| patch = MplPolygon(arr, closed=True, facecolor=color, |
| alpha=0.35, 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=7, framealpha=0.7) |
|
|
|
|
| def visualize_sample(image_name: str, creator: str, df: pd.DataFrame): |
| mask_path = find_mask_path(image_name, creator) |
| img_path = find_image_path(image_name) |
|
|
| mask_rgb = ( |
| np.array(Image.open(mask_path).convert("RGB")) |
| if mask_path else np.zeros((200, 200, 3), dtype=np.uint8) |
| ) |
| image_rgb = ( |
| cv2.cvtColor(cv2.imread(str(img_path)), cv2.COLOR_BGR2RGB) |
| if img_path else np.zeros_like(mask_rgb) |
| ) |
|
|
| rows = df[(df["image_name"] == image_name) & (df["creator"] == creator)] |
| polys = [(r["label"], json.loads(r["polygon"])) for _, r in rows.iterrows()] |
| n_pts = sum(len(p) - 1 for _, p in polys) |
|
|
| fig, axes = plt.subplots(1, 3, figsize=(18, 6)) |
| fig.suptitle(f"{image_name} [creator={creator}]", fontsize=9) |
|
|
| axes[0].imshow(mask_rgb) |
| axes[0].set_title("Maske (palette → RGB)") |
| axes[0].axis("off") |
|
|
| axes[1].imshow(image_rgb) |
| axes[1].set_title("Orijinal görüntü") |
| axes[1].axis("off") |
|
|
| draw_polygons( |
| axes[2], image_rgb, polys, |
| f"Polygonlar ({len(polys)} adet / {n_pts} nokta)" |
| ) |
|
|
| plt.tight_layout() |
| out_path = f"validate_{image_name[:50]}.png" |
| plt.savefig(out_path, dpi=110, bbox_inches="tight") |
| plt.close(fig) |
| print(f" Kaydedildi: {out_path} " |
| f"({len(polys)} polygon, {n_pts} nokta)") |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--csv", default=str(CSV_PATH)) |
| parser.add_argument("--n", type=int, default=3, |
| help="Gösterilecek örnek sayısı") |
| parser.add_argument("--seed", type=int, default=42) |
| parser.add_argument("--creator", default=None, |
| help="Filtrele: train / test_pathologist1 / test_pathologist2") |
| args = parser.parse_args() |
|
|
| csv_path = Path(args.csv) |
| if not csv_path.exists(): |
| sys.exit(f"CSV bulunamadı: {csv_path}") |
|
|
| df = pd.read_csv(csv_path) |
|
|
| |
| required = {"image_name", "label", "polygon", "creator"} |
| missing = required - set(df.columns) |
| if missing: |
| sys.exit(f"CSV'de eksik kolonlar: {missing}") |
|
|
| invalid_labels = set(df["label"].unique()) - {"Benign", "G3", "G4", "G5"} |
| if invalid_labels: |
| print(f"UYARI: Beklenmeyen label değerleri: {invalid_labels}") |
|
|
| invalid_creators = set(df["creator"].unique()) - set(SOURCE_INFO.keys()) |
| if invalid_creators: |
| print(f"UYARI: Beklenmeyen creator değerleri: {invalid_creators}") |
|
|
| print_stats(df) |
|
|
| subset = df if args.creator is None else df[df["creator"] == args.creator] |
| unique_images = subset["image_name"].unique().tolist() |
|
|
| if not unique_images: |
| sys.exit("Görselleştirme için uygun görüntü bulunamadı.") |
|
|
| |
| by_count = ( |
| subset.groupby("image_name") |
| .size() |
| .sort_values(ascending=False) |
| ) |
| candidates = by_count.head(50).index.tolist() |
| random.seed(args.seed) |
| selected = random.sample(candidates, min(args.n, len(candidates))) |
|
|
| print(f"Görselleştirilen {len(selected)} örnek:\n") |
| for img_name in selected: |
| creator = df.loc[df["image_name"] == img_name, "creator"].iloc[0] |
| visualize_sample(img_name, creator, df) |
|
|
| print("\nGörüntüler validate_*.png olarak kaydedildi.") |
|
|
|
|
| if __name__ == "__main__": |
| import os |
| os.chdir(Path(__file__).parent) |
| main() |
|
|