| """ |
| Mask patchlerinden G3/G4/G5 polygonları çıkarır → polygons.csv |
| |
| Algoritma: |
| Pass 1 - Slide kalibrasyonu (dış bilgi gerekmez): |
| * Slide'daki tüm masklerin histogramını birleştir |
| * Peak tespiti → birbirine yakın peak'leri (≤20 değer farkı) birleştir |
| * Her peak'i değer aralığına göre grade'e ata: |
| 30-80 → G3 (dataset genelinde 50 veya 65 civarı) |
| 80-125 → G4 (85 veya 100 civarı) |
| 125+ → G5 (150-200 arası) |
| |
| Pass 2 - Patch işleme: |
| * medianBlur(5) → JPEG gradient artifact'larını temizle |
| * Slide'a özel midpoint threshold'larla quantize |
| * Connected component cleanup → JPEG artifact bileşenlerini at |
| * Contour → patch-local koordinatlar → CSV satırı |
| """ |
|
|
| import csv |
| import cv2 |
| import numpy as np |
| import json |
| import openpyxl |
| import re |
| import os |
| from pathlib import Path |
| from scipy.signal import find_peaks |
| from scipy.ndimage import gaussian_filter1d |
|
|
| RESOURCE_ROOT = Path("") |
|
|
| if RESOURCE_ROOT == Path(""): |
| print("UYARI: RESOURCE_ROOT boş bırakılmış, set edilmesi gerekiyor!") |
| MASKS_DIR = Path(RESOURCE_ROOT / "masks") |
| PARTITION_DIR = Path(RESOURCE_ROOT / "partition") |
| OUT_CSV = Path(RESOURCE_ROOT / "polygons.csv") |
|
|
| FILENAME_RE = re.compile( |
| r"^(?P<slide>[^_]+)_.*_xini_(?P<xini>\d+)_yini_(?P<yini>\d+)\.jpg$" |
| ) |
|
|
| GRADE_RANGES = [ |
| (30, 80, "G3"), |
| (80, 125, "G4"), |
| (125, 256, "G5"), |
| ] |
|
|
| MERGE_DIST = 20 |
| MIN_AREA = 100 |
|
|
|
|
| |
| |
| |
|
|
| def grade_for_value(val: int) -> str | None: |
| for lo, hi, grade in GRADE_RANGES: |
| if lo <= val < hi: |
| return grade |
| return None |
|
|
|
|
| def detect_peaks(hist: np.ndarray) -> list[tuple[int, int]]: |
| data = hist[8:].astype(float) |
| smooth = gaussian_filter1d(data, sigma=2) |
| min_h = max(smooth.max() * 0.02, 5) |
| idxs, _ = find_peaks(smooth, height=min_h, distance=10, prominence=min_h * 0.3) |
| return [(int(i + 8), int(hist[i + 8])) for i in idxs] |
|
|
|
|
| def merge_nearby_peaks(peaks: list[tuple[int, int]]) -> list[tuple[int, int]]: |
| if not peaks: |
| return [] |
| sorted_p = sorted(peaks) |
| merged = [sorted_p[0]] |
| for val, cnt in sorted_p[1:]: |
| pval, pcnt = merged[-1] |
| if val - pval <= MERGE_DIST: |
| merged[-1] = (val, cnt) if cnt > pcnt else (pval, pcnt) |
| else: |
| merged.append((val, cnt)) |
| return merged |
|
|
|
|
| def calibrate_slide(hist: np.ndarray) -> dict[int, str]: |
| peaks = detect_peaks(hist) |
| peaks = merge_nearby_peaks(peaks) |
| grade_map: dict[int, str] = {} |
| for val, _ in peaks: |
| grade = grade_for_value(val) |
| if grade and grade not in grade_map.values(): |
| grade_map[val] = grade |
| return grade_map |
|
|
|
|
| def build_slide_grade_maps(mask_files: list[Path]) -> dict[str, dict[int, str]]: |
| hists: dict[str, np.ndarray] = {} |
| for mf in mask_files: |
| m = FILENAME_RE.match(mf.name) |
| if not m: |
| continue |
| slide = m.group("slide") |
| gray = cv2.imread(str(mf), cv2.IMREAD_GRAYSCALE) |
| if gray is None: |
| continue |
| if slide not in hists: |
| hists[slide] = np.zeros(256, dtype=np.int64) |
| vals, cnts = np.unique(gray, return_counts=True) |
| for v, c in zip(vals, cnts): |
| hists[slide][int(v)] += int(c) |
|
|
| return {slide: calibrate_slide(hist) for slide, hist in hists.items()} |
|
|
|
|
| |
| |
| |
|
|
| def quantize(gray_clean: np.ndarray, class_centers: list[int]) -> np.ndarray: |
| q = np.zeros(gray_clean.shape, dtype=np.int32) |
| all_centers = sorted([0] + class_centers) |
| for i in range(1, len(all_centers)): |
| center = all_centers[i] |
| lower = (all_centers[i - 1] + center) // 2 |
| upper = (all_centers[i + 1] + center) // 2 if i + 1 < len(all_centers) else 256 |
| q[(gray_clean >= lower) & (gray_clean < upper)] = center |
| return q |
|
|
|
|
| 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 contours_to_polygons(contours) -> list[str]: |
| """Patch-local koordinatlarda polygon listesi döndürür (JSON string olarak).""" |
| polygons = [] |
| for cnt in contours: |
| if cv2.contourArea(cnt) < MIN_AREA: |
| continue |
| approx = cv2.approxPolyDP(cnt, 0.5, closed=True) |
| if len(approx) < 3: |
| continue |
| pts = [[int(p[0][0]), int(p[0][1])] for p in approx] |
| pts.append(pts[0]) |
| polygons.append(json.dumps(pts)) |
| return polygons |
|
|
|
|
| def process_mask(mask_path: Path, grade_map: dict[int, str]) -> list[dict]: |
| """Her polygon için image_name/label/polygon içeren satır listesi döndürür.""" |
| if not FILENAME_RE.match(mask_path.name): |
| return [] |
|
|
| gray = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) |
| if gray is None: |
| return [] |
|
|
| gray_clean = cv2.medianBlur(gray, 5) |
| q = quantize(gray_clean, list(grade_map.keys())) |
|
|
| rows = [] |
| for center, label in grade_map.items(): |
| binary = (q == center).astype(np.uint8) |
| if binary.sum() == 0: |
| continue |
| binary = remove_small_components(binary) |
| if binary.sum() == 0: |
| continue |
| cnts, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| for poly_str in contours_to_polygons(cnts): |
| rows.append({ |
| "image_name": mask_path.stem, |
| "label": label, |
| "polygon": poly_str, |
| }) |
| return rows |
|
|
|
|
| |
| |
| |
|
|
| def collect_nc_patches() -> set[str]: |
| """partition/ altındaki tüm xlsx'lerde NC=1 olan benzersiz image_name stem'lerini döndürür.""" |
| nc: set[str] = set() |
| for xlsx in PARTITION_DIR.rglob("*.xlsx"): |
| wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) |
| ws = wb.active |
| rows = ws.iter_rows(values_only=True) |
| header = next(rows) |
| if "NC" not in header: |
| wb.close() |
| continue |
| nc_idx = header.index("NC") |
| name_idx = header.index("image_name") |
| for row in rows: |
| if row[nc_idx] == 1: |
| name = row[name_idx] |
| nc.add(Path(name).stem if name else "") |
| wb.close() |
| nc.discard("") |
| return nc |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| mask_files = sorted(MASKS_DIR.glob("*.jpg")) |
| print(f"Toplam mask: {len(mask_files)}") |
|
|
| print("Slide kalibrasyonu yapılıyor...") |
| slide_grade_maps = build_slide_grade_maps(mask_files) |
| cancerous_slides = {s: gm for s, gm in slide_grade_maps.items() if gm} |
| print(f" {len(cancerous_slides)} slide kalibre edildi (cancerous).") |
| for slide, gmap in list(cancerous_slides.items())[:8]: |
| print(f" {slide}: {gmap}") |
|
|
| print("\nMask'lar işleniyor...") |
| all_rows: list[dict] = [] |
|
|
| for i, mf in enumerate(mask_files): |
| m = FILENAME_RE.match(mf.name) |
| if not m: |
| continue |
| slide = m.group("slide") |
| gmap = cancerous_slides.get(slide) |
| if not gmap: |
| continue |
| all_rows.extend(process_mask(mf, gmap)) |
| if (i + 1) % 1000 == 0: |
| print(f" {i+1}/{len(mask_files)} işlendi...") |
|
|
| print("NC patch'ler toplanıyor...") |
| nc_patches = collect_nc_patches() |
| print(f" {len(nc_patches)} NC patch bulundu.") |
| for stem in nc_patches: |
| all_rows.append({"image_name": stem, "label": "NC", "polygon": ""}) |
|
|
| print(f"\nToplam {len(all_rows)} satır → {OUT_CSV}") |
| with open(OUT_CSV, "w", newline="") as f: |
| writer = csv.DictWriter(f, fieldnames=["image_name", "label", "polygon"]) |
| writer.writeheader() |
| writer.writerows(all_rows) |
|
|
| print("Tamamlandı.") |
|
|
|
|
| if __name__ == "__main__": |
| os.chdir(Path(__file__).parent) |
| main() |
|
|