File size: 16,782 Bytes
06eb8a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""dacl10k 공통 데이터 생성: 클래스 순서, 5-fold 분할, 손상-부재(종류 단위) 연결 정답, 정답 마스크.

사용법:
    python make_common.py <dacl10k_v2_devphase 경로> [--out 출력폴더] [--skip-masks]

필요 패키지: numpy, opencv-python-headless, iterative-stratification (없으면 g만으로 층화, scikit-learn 필요)
원본 데이터는 읽기만 한다. 결과(기본: <data_dir>/../common):
    classes.json, split.json, links_gt.csv, damage_labels.csv, split_report.md, gt_masks/<image>.npz

연결 정답 (정의 A, 부재 종류 단위):
    M_c   = 그 사진에서 종류 c 인 부재 폴리곤 전부의 합집합
    ratio = |dilate_5(M_d) ∩ M_c| / |M_d|   (원형 커널 반지름 5px, 원본 해상도)
    y     = 1[ratio >= 0.1]
손상 라벨 = y=1 인 종류 중 ratio 최대, 없으면 "none"
"""
import argparse
import csv
import glob
import io
import json
import os
import random
from collections import Counter, defaultdict
from multiprocessing import Pool

import cv2
import numpy as np

SEED = 42
N_FOLDS = 5
DAMAGES = ["Crack", "ACrack", "Wetspot", "Efflorescence", "Rust", "Rockpocket", "Hollowareas",
           "Cavity", "Spalling", "Graffiti", "Weathering", "Restformwork", "ExposedRebars", "WConccor"]
OBJECTS = ["Bearing", "EJoint", "Drainage", "PEquipment", "JTape"]
CLASSES = DAMAGES + OBJECTS
SPLITS = ["train", "validation"]
R, TAU = 5, 0.1


# ---------- 래스터화 (check_dacl10k.py 와 동일, 창 위치와 무관하게 전체 이미지 래스터화와 같은 결과) ----------
def bbox(pts, W, H):
    x0, y0 = np.floor(pts.min(0)).astype(int)
    x1, y1 = np.ceil(pts.max(0)).astype(int)
    return max(x0, 0), max(y0, 0), min(x1, W - 1), min(y1, H - 1)


def raster(pts, x0, y0, x1, y1):
    m = np.zeros((y1 - y0 + 1, x1 - x0 + 1), np.uint8)
    p = (np.round(pts).astype(np.int64) - [x0, y0]).astype(np.int32)
    cv2.fillPoly(m, [p], 1)
    return m.astype(bool)


def paste(dst, x0, y0, mask, bx0, by0):
    """mask(좌상단 bx0,by0)를 dst(좌상단 x0,y0) 창에 OR 로 붙인다."""
    H, W = dst.shape
    h, w = mask.shape
    ix0, iy0 = max(x0, bx0), max(y0, by0)
    ix1, iy1 = min(x0 + W, bx0 + w) - 1, min(y0 + H, by0 + h) - 1
    if ix0 <= ix1 and iy0 <= iy1:
        dst[iy0 - y0:iy1 - y0 + 1, ix0 - x0:ix1 - x0 + 1] |= mask[iy0 - by0:iy1 - by0 + 1, ix0 - bx0:ix1 - bx0 + 1]


def load(path):
    with open(path, encoding="utf-8") as f:
        a = json.load(f)
    W, H = a["imageWidth"], a["imageHeight"]
    polys = []
    for i, s in enumerate(a["shapes"]):
        pts = np.asarray(s["points"], dtype=np.float64)
        b = bbox(pts, W, H)
        if b[0] > b[2] or b[1] > b[3]:
            continue
        m = raster(pts, *b)
        if m.any():
            polys.append({"id": i, "label": s["label"], "bbox": b, "mask": m, "area": int(m.sum())})
    return W, H, polys


def union_by_class(polys, labels):
    """종류별 합집합 마스크 {c: (bbox, mask)}."""
    out = {}
    for c in labels:
        ps = [p for p in polys if p["label"] == c]
        if not ps:
            continue
        x0 = min(p["bbox"][0] for p in ps)
        y0 = min(p["bbox"][1] for p in ps)
        x1 = max(p["bbox"][2] for p in ps)
        y1 = max(p["bbox"][3] for p in ps)
        m = np.zeros((y1 - y0 + 1, x1 - x0 + 1), bool)
        for p in ps:
            paste(m, x0, y0, p["mask"], p["bbox"][0], p["bbox"][1])
        out[c] = ((x0, y0, x1, y1), m)
    return out


def inter_dilated(d, cb, cm, W, H):
    """|dilate_R(M_d) ∩ M_c|, 영향 영역만 잘라서 계산."""
    dx0, dy0, dx1, dy1 = d["bbox"]
    kx0, ky0, kx1, ky1 = cb
    cx0, cy0 = max(dx0 - R, kx0), max(dy0 - R, ky0)
    cx1, cy1 = min(dx1 + R, kx1), min(dy1 + R, ky1)
    if cx0 > cx1 or cy0 > cy1:
        return 0
    px0, py0 = max(cx0 - R, 0), max(cy0 - R, 0)
    px1, py1 = min(cx1 + R, W - 1), min(cy1 + R, H - 1)
    D = np.zeros((py1 - py0 + 1, px1 - px0 + 1), bool)
    paste(D, px0, py0, d["mask"], dx0, dy0)
    K = np.zeros((cy1 - cy0 + 1, cx1 - cx0 + 1), bool)
    paste(K, cx0, cy0, cm, kx0, ky0)
    Dr = cv2.dilate(D.astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * R + 1, 2 * R + 1)))
    return int(np.count_nonzero(Dr[cy0 - py0:cy1 - py0 + 1, cx0 - px0:cx1 - px0 + 1].astype(bool) & K))


# ---------- 1단계: 이미지별 연결 정답 ----------
def links_of(job):
    split, path = job
    W, H, polys = load(path)
    name = os.path.basename(path)[:-5]
    comps = union_by_class(polys, OBJECTS)
    rows, dlabels = [], []
    for d in (p for p in polys if p["label"] in DAMAGES):
        best, nlink = ("none", -1.0), 0
        for c in OBJECTS:
            if c not in comps:
                continue
            cb, cm = comps[c]
            inter = inter_dilated(d, cb, cm, W, H)
            ratio = inter / d["area"]
            y = int(ratio >= TAU)
            rows.append([name, d["id"], d["label"], c, d["area"], int(cm.sum()), inter, ratio, y])
            if y:
                nlink += 1
                if ratio > best[1]:
                    best = (c, ratio)
        dlabels.append([name, d["id"], d["label"], best[0], nlink])
    return {"name": name, "split": split, "W": W, "H": H, "comp_types": sorted(comps, key=OBJECTS.index),
            "rows": rows, "dlabels": dlabels}


# ---------- 정답 마스크 ----------
def build_mask(path):
    W, H, polys = load(path)
    m = np.zeros((len(CLASSES), H, W), bool)
    for p in polys:
        if p["label"] in CLASSES:
            paste(m[CLASSES.index(p["label"])], 0, 0, p["mask"], p["bbox"][0], p["bbox"][1])
    return m


def compressed_size(path):
    buf = io.BytesIO()
    np.savez_compressed(buf, mask=build_mask(path))
    return buf.tell()


def write_mask(args):
    path, out_dir = args
    dst = os.path.join(out_dir, os.path.basename(path)[:-5] + ".npz")
    if not os.path.exists(dst):
        tmp = dst[:-4] + ".tmp.npz"
        np.savez_compressed(tmp, mask=build_mask(path))
        os.replace(tmp, dst)
    return os.path.getsize(dst)


# ---------- 분할 ----------
def make_folds(names, g, comp_types):
    Y = np.zeros((len(names), 4 + len(OBJECTS)), int)
    for i, n in enumerate(names):
        Y[i, g[n]] = 1
        for c in comp_types[n]:
            Y[i, 4 + OBJECTS.index(c)] = 1
    X = np.zeros((len(names), 1))
    try:
        from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
        kf, y, method = MultilabelStratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED), Y, \
            "iterative stratification (iterstrat MultilabelStratifiedKFold): g 원핫 4 + 부재 5종 포함 여부"
    except ImportError:
        from sklearn.model_selection import StratifiedKFold
        kf, y, method = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED), \
            np.array([g[n] for n in names]), "StratifiedKFold (g만으로 층화, iterstrat 없음)"
    fold = {}
    for f, (_, te) in enumerate(kf.split(X, y)):
        for i in te:
            fold[names[i]] = f
    return fold, method


# ---------- 보고서 ----------
def pct(a, b):
    return f"{a / b:.1%}" if b else "-"


def report(out, imgs, fold, g, method, links, dlab, mask_info):
    F = list(range(N_FOLDS))
    by_f = {f: [n for n in imgs if fold[n] == f] for f in F}
    pos = [r for r in links if r[8] == 1]
    g3 = {n for n in imgs if g[n] == 3}
    comp_types = {n: imgs[n]["comp_types"] for n in imgs}
    has_comp = {n for n in imgs if comp_types[n]}
    L = ["# 공통 데이터 검증 보고서", "",
         f"- 데이터: dacl10k v2 train+validation {len(imgs)}장, 원본 해상도",
         f"- **교량 정보 없음** → 사진 단위 분할 (grouping = image). JSON 키·파일명·원본 README에 교량 ID/촬영 묶음 없음,"
         " JPEG EXIF는 160장(약 2%)에만 있어 묶음 구성 불가. 같은 교량 사진이 여러 fold에 나뉠 수 있음(누수 위험).",
         f"- 분할: {N_FOLDS}-fold, seed {SEED}, {method}",
         f"- 연결 정답: 정의 A, 부재 **종류** 단위, r={R}px 원형 팽창, τ={TAU}",
         "- g: 3=부재 종류 2개 이상, 2=부재 1종+연결≥1, 1=부재 1종+연결 0, 0=부재 없음", ""]

    # 전체 합계
    n_dmg = len(dlab)
    n_dmg_c = sum(1 for d in dlab if d[0] in has_comp)
    none_all = sum(d[3] == "none" for d in dlab)
    none_c = sum(d[3] == "none" for d in dlab if d[0] in has_comp)
    linked = [d for d in dlab if d[4] >= 1]
    multi = sum(d[4] >= 2 for d in linked)
    pos_g3 = sum(r[0] in g3 for r in pos)
    g3_dmg = sum(1 for n in g3 if imgs[n]["dlabels"])
    L += ["## 전체 합계", "", "| 항목 | 값 |", "|---|---:|",
          f"| 사진 | {len(imgs)} |",
          f"| 후보 (손상 × 사진 내 부재 종류) | {len(links)} |",
          f"| 연결 (y=1) | {len(pos)} |",
          f"| 부재 2종 이상 사진 (g=3) | {len(g3)}장 (그중 손상 있는 사진 {g3_dmg}장) |",
          f"| g=3 사진의 연결 | {pos_g3} |",
          f"| 손상 수 | {n_dmg} (부재 있는 사진의 손상 {n_dmg_c}) |",
          f"| 손상 단위 none 비율 (전체 손상) | {pct(none_all, n_dmg)} |",
          f"| 손상 단위 none 비율 (부재 있는 사진의 손상) | {pct(none_c, n_dmg_c)} |",
          f"| 연결된 손상 | {len(linked)} |",
          f"| 연결된 손상 중 2종 이상 연결 | {multi} ({pct(multi, len(linked))}) |",
          f"| Rust 비중 (연결 중) | {pct(sum(r[2] == 'Rust' for r in pos), len(pos))} |", ""]

    # 이전 인스턴스 단위 값과 비교
    L += ["## 이전 인스턴스 단위 값과 비교", "",
          "| 항목 | 이전 (인스턴스 단위, 요청서 기재) | 이번 (종류 단위) | 비고 |", "|---|---:|---:|---|",
          f"| 연결 쌍 | 4,180 | {len(pos)} | 같은 종류 부재 여러 개 → 1행으로 합쳐짐 |",
          f"| 부분집합 (부재 2종 이상) 사진·연결 | 715장·1,303쌍 | {len(g3)}장 (손상 있는 {g3_dmg}장)·{pos_g3}쌍 |"
          " 715장 = g=3 중 손상 있는 사진 |",
          f"| none 비율 | 84.4% | {pct(none_all, n_dmg)} (전체) / {pct(none_c, n_dmg_c)} (부재 있는 사진) |"
          " 84.4% = 부재 있는 사진의 손상 기준 |",
          f"| 다중 (2종 이상) | 1.6% | {pct(multi, len(linked))} | |", ""]

    # fold별
    hdr = "| 항목 | " + " | ".join(f"fold {f}" for f in F) + " | 합계 |"
    sep = "|---" * (N_FOLDS + 2) + "|"
    rows = []
    rows.append("| 사진 | " + " | ".join(str(len(by_f[f])) for f in F) + f" | {len(imgs)} |")
    warn = []
    for gv in (3, 2, 1, 0):
        cnt = [sum(g[n] == gv for n in by_f[f]) for f in F]
        ratios = [c / len(by_f[f]) for c, f in zip(cnt, F)]
        spread = max(ratios) - min(ratios)
        flag = " ⚠️" if spread > 0.01 else ""
        if flag:
            warn.append(f"g={gv} 비율 fold 간 차이 {spread * 100:.2f}%p > 1%p")
        rows.append(f"| g={gv}{flag} | " + " | ".join(f"{c} ({r:.1%})" for c, r in zip(cnt, ratios))
                    + f" | {sum(cnt)} |")
    for c in OBJECTS:
        cnt = [sum(c in comp_types[n] for n in by_f[f]) for f in F]
        rows.append(f"| {c} 포함 사진 | " + " | ".join(map(str, cnt)) + f" | {sum(cnt)} |")
    pf = [sum(fold[r[0]] == f for r in pos) for f in F]
    rows.append("| 연결 (y=1) | " + " | ".join(map(str, pf)) + f" | {sum(pf)} |")
    pg = [sum(fold[r[0]] == f and r[0] in g3 for r in pos) for f in F]
    rows.append("| g=3 사진의 연결 | " + " | ".join(map(str, pg)) + f" | {sum(pg)} |")
    nf = []
    for f in F:
        ds = [d for d in dlab if fold[d[0]] == f]
        nf.append(pct(sum(d[3] == "none" for d in ds), len(ds)))
    rows.append("| 손상 none 비율 | " + " | ".join(nf) + f" | {pct(none_all, n_dmg)} |")
    rf = [pct(sum(fold[r[0]] == f and r[2] == "Rust" for r in pos), pf[f]) for f in F]
    rows.append("| Rust 비중 (연결 중) | " + " | ".join(rf) + f" | {pct(sum(r[2] == 'Rust' for r in pos), len(pos))} |")
    L += ["## fold별", "", hdr, sep] + rows + [""]
    L += ["## 경고", ""] + ([f"- ⚠️ {w}" for w in warn] or ["- 없음 (모든 g 비율의 fold 간 차이 ≤ 1%p)"]) + [""]
    if mask_info:
        L += ["## 정답 마스크", "", f"- gt_masks/: {mask_info['n']}개, 총 {mask_info['bytes'] / 1e9:.2f} GB"
              f" (사전 추정 {mask_info['est'] / 1e9:.2f} GB)", ""]
    with open(os.path.join(out, "split_report.md"), "w", encoding="utf-8") as f:
        f.write("\n".join(L))
    return warn


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("data_dir", help="dacl10k_v2_devphase 폴더 (annotations/, images/ 포함)")
    ap.add_argument("--out", default=None, help="출력 폴더 (기본: <data_dir>/../common)")
    ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
    ap.add_argument("--mask-workers", type=int, default=4, help="마스크 저장 병렬 수 (큰 이미지는 장당 ~0.5GB 메모리)")
    ap.add_argument("--max-gb", type=float, default=50, help="마스크 예상 용량이 이를 넘으면 중단")
    ap.add_argument("--skip-masks", action="store_true")
    args = ap.parse_args()
    random.seed(SEED)
    np.random.seed(SEED)
    data_dir = os.path.abspath(args.data_dir)
    out = os.path.abspath(args.out or os.path.join(data_dir, "..", "common"))
    os.makedirs(out, exist_ok=True)

    jobs = [(sp, p) for sp in SPLITS
            for p in sorted(glob.glob(os.path.join(data_dir, "annotations", sp, "*.json")))]
    paths = {os.path.basename(p)[:-5]: p for _, p in jobs}

    # classes.json
    with open(os.path.join(out, "classes.json"), "w", encoding="utf-8") as f:
        json.dump({"classes": [{"index": i, "name": c, "type": "damage" if c in DAMAGES else "component"}
                               for i, c in enumerate(CLASSES)]}, f, indent=2)

    # 연결 정답
    with Pool(args.workers) as pool:
        res = pool.map(links_of, jobs, chunksize=8)
    imgs = {r["name"]: r for r in res}
    names = sorted(imgs)
    g = {}
    for n in names:
        k = len(imgs[n]["comp_types"])
        g[n] = 3 if k >= 2 else 0 if k == 0 else 2 if any(r[8] for r in imgs[n]["rows"]) else 1
    fold, method = make_folds(names, g, {n: imgs[n]["comp_types"] for n in names})

    with open(os.path.join(out, "split.json"), "w", encoding="utf-8") as f:
        json.dump({"seed": SEED, "n_folds": N_FOLDS, "grouping": "image", "stratification": method,
                   "images": {n: {"fold": fold[n], "orig_split": imgs[n]["split"], "g": g[n]} for n in names}},
                  f, indent=1)
    links = [r for n in names for r in imgs[n]["rows"]]
    dlab = [d for n in names for d in imgs[n]["dlabels"]]
    with open(os.path.join(out, "links_gt.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["image", "fold", "dmg_id", "dmg_class", "comp_class", "area_d", "area_c", "inter5_c", "ratio", "y"])
        for r in links:
            w.writerow([r[0], fold[r[0]], *r[1:7], f"{r[7]:.6f}", r[8]])
    with open(os.path.join(out, "damage_labels.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["image", "fold", "dmg_id", "dmg_class", "label", "n_linked_types"])
        for d in dlab:
            w.writerow([d[0], fold[d[0]], *d[1:]])
    print(f"links_gt: {len(links)} rows, y=1 {sum(r[8] for r in links)}; damages {len(dlab)}", flush=True)

    # 정답 마스크
    mask_info = {}
    if not args.skip_masks:
        rng = random.Random(SEED)
        sample = rng.sample(names, 60)
        with Pool(args.mask_workers) as pool:
            sizes = pool.map(compressed_size, [paths[n] for n in sample])
        bpp = sum(sizes) / sum(imgs[n]["W"] * imgs[n]["H"] for n in sample)
        est = bpp * sum(imgs[n]["W"] * imgs[n]["H"] for n in names)
        print(f"mask size estimate: {est / 1e9:.2f} GB (sample of 60, {bpp * 8:.3f} bits/pixel)", flush=True)
        if est > args.max_gb * 1e9:
            print(f"estimate exceeds {args.max_gb} GB -> stopping before writing masks", flush=True)
        else:
            mdir = os.path.join(out, "gt_masks")
            os.makedirs(mdir, exist_ok=True)
            total = 0
            with Pool(args.mask_workers) as pool:
                for i, s in enumerate(pool.imap_unordered(write_mask, [(paths[n], mdir) for n in names], chunksize=4)):
                    total += s
                    if (i + 1) % 1000 == 0:
                        print(f"masks {i + 1}/{len(names)}", flush=True)
            mask_info = {"n": len(names), "bytes": total, "est": est}

    warn = report(out, imgs, fold, g, method, links, dlab, mask_info)
    print("warnings:", warn or "none")
    print("done ->", out)


if __name__ == "__main__":
    main()