File size: 5,021 Bytes
87f79e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
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

# ---------------------------------------------------------------------------
# Konfigürasyon
# ---------------------------------------------------------------------------

ORIGIN_DIR = Path("origin")
OUT_CSV    = Path("polygons.csv")

LABEL_MAP = {0: "Benign", 1: "G3", 2: "G4", 3: "G5"}  # 4 = unlabelled, atlanır

MIN_AREA      = 150   # piksel cinsinden minimum alan (küçük artefaktları at)
EPSILON_START = 2.0   # approxPolyDP başlangıç epsilonu
MAX_POINTS    = 50    # polygon başına maksimum köşe noktası

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$")),
]


# ---------------------------------------------------------------------------
# Yardımcı fonksiyonlar
# ---------------------------------------------------------------------------

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])   # kapanış noktası
    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


# ---------------------------------------------------------------------------
# Ana akış
# ---------------------------------------------------------------------------

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()