File size: 9,627 Bytes
edae372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import json
import math
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union

import numpy as np
from PIL import Image, ImageDraw

_REPO = Path(__file__).resolve().parents[1]
if str(_REPO) not in sys.path:
    sys.path.insert(0, str(_REPO))
from scripts.coco_scene_paths import iter_scene_coco_for_masks, open_coco_json  # noqa: E402


def _ensure_dir(p: Path) -> None:
    p.mkdir(parents=True, exist_ok=True)


def _safe_stem(name: str) -> str:
    # Keep it deterministic + filesystem-friendly on Windows
    stem = Path(name).stem
    return "".join(c if (c.isalnum() or c in ("-", "_", ".")) else "_" for c in stem)


def _poly_to_mask(polys: List[List[float]], h: int, w: int) -> np.ndarray:
    """

    polys: list of polygons; each polygon is [x1,y1,x2,y2,...] (float/int)

    returns: (h,w) uint8 mask with values 0 or 255

    """
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    for poly in polys:
        if not poly or len(poly) < 6:
            continue
        pts = [(float(poly[i]), float(poly[i + 1])) for i in range(0, len(poly) - 1, 2)]
        # Pillow fills polygons using non-zero rule; that's standard for COCO polygon masks.
        draw.polygon(pts, outline=255, fill=255)
    return np.array(img, dtype=np.uint8)


def _rle_counts_from_string(s: str) -> List[int]:
    """

    Decode COCO's compressed RLE counts string into list[int].

    Ported from the public COCO API logic (pycocotools).

    """
    counts: List[int] = []
    p = 0
    m = 0
    while p < len(s):
        x = 0
        k = 0
        more = 1
        while more:
            if p >= len(s):
                raise ValueError("Invalid RLE string (truncated).")
            c = ord(s[p]) - 48
            p += 1
            x |= (c & 0x1F) << (5 * k)
            more = c & 0x20
            k += 1
            if k > 10:
                raise ValueError("Invalid RLE string (too long).")
        # sign bit for negative values
        if (c & 0x10) != 0:
            x |= -1 << (5 * k)
        if m > 2:
            x += counts[m - 2]
        counts.append(int(x))
        m += 1
    return counts


def _rle_to_mask(rle: Dict[str, Any], h: int, w: int) -> np.ndarray:
    """

    rle: {"counts": <list|str>, "size": [h,w]} or sometimes size omitted in file.

    returns: (h,w) uint8 mask with values 0 or 255

    """
    size = rle.get("size")
    if size is not None:
        rh, rw = int(size[0]), int(size[1])
        if rh != h or rw != w:
            # We'll honor image size; but if mismatch exists, decode with rle size then resize is wrong.
            # Better to decode with rle size and place/clip if needed. In practice should match.
            h, w = rh, rw

    counts_raw = rle.get("counts")
    if isinstance(counts_raw, str):
        counts = _rle_counts_from_string(counts_raw)
    elif isinstance(counts_raw, list):
        counts = [int(x) for x in counts_raw]
    else:
        raise TypeError(f"Unsupported RLE counts type: {type(counts_raw)}")

    # COCO RLE is for a Fortran-ordered (column-major) flattened mask of shape (h,w)
    flat_len = h * w
    flat = np.zeros(flat_len, dtype=np.uint8)
    idx = 0
    val = 0
    for run in counts:
        if run < 0:
            raise ValueError("Invalid RLE run length (negative).")
        if idx + run > flat_len:
            # Some exports may include trailing runs; clip safely.
            run = max(0, flat_len - idx)
        if run:
            if val == 1:
                flat[idx : idx + run] = 1
            idx += run
        val ^= 1
        if idx >= flat_len:
            break
    mask = flat.reshape((w, h), order="C").T  # reshape then transpose for column-major semantics
    return (mask * 255).astype(np.uint8)


def _segmentation_to_mask(

    segmentation: Any, h: int, w: int

) -> np.ndarray:
    if segmentation is None:
        return np.zeros((h, w), dtype=np.uint8)

    # Polygon format: list[list[float]] or sometimes list[float] (single poly)
    if isinstance(segmentation, list):
        if len(segmentation) == 0:
            return np.zeros((h, w), dtype=np.uint8)
        if all(isinstance(x, (int, float)) for x in segmentation):
            return _poly_to_mask([segmentation], h, w)
        # list of polygons
        polys: List[List[float]] = []
        for item in segmentation:
            if isinstance(item, list):
                polys.append(item)
            else:
                raise TypeError(f"Unsupported polygon entry type: {type(item)}")
        return _poly_to_mask(polys, h, w)

    # RLE format: dict with counts/size
    if isinstance(segmentation, dict):
        return _rle_to_mask(segmentation, h, w)

    raise TypeError(f"Unsupported segmentation type: {type(segmentation)}")


@dataclass(frozen=True)
class ImageInfo:
    file_name: str
    height: int
    width: int


def generate_masks_for_coco(

    coco_path: Path,

    output_dir: Path,

    overwrite: bool = False,

) -> Dict[str, int]:
    coco = open_coco_json(coco_path)

    images = coco.get("images", [])
    annotations = coco.get("annotations", [])
    categories = coco.get("categories", [])

    image_by_id: Dict[int, ImageInfo] = {}
    for im in images:
        image_by_id[int(im["id"])] = ImageInfo(
            file_name=str(im.get("file_name", f"{im['id']}")),
            height=int(im["height"]),
            width=int(im["width"]),
        )

    cat_name_by_id: Dict[int, str] = {int(c["id"]): str(c.get("name", c["id"])) for c in categories}

    written = 0
    skipped = 0
    errors = 0

    for ann in annotations:
        try:
            ann_id = int(ann["id"])
            image_id = int(ann["image_id"])
            cat_id = int(ann.get("category_id", -1))
            im = image_by_id.get(image_id)
            if im is None:
                errors += 1
                continue

            h, w = im.height, im.width
            mask = _segmentation_to_mask(ann.get("segmentation"), h, w)

            img_stem = _safe_stem(im.file_name)
            cat_name = cat_name_by_id.get(cat_id, str(cat_id))
            cat_safe = "".join(c if (c.isalnum() or c in ("-", "_", ".")) else "_" for c in cat_name)[:80]

            out_subdir = output_dir / img_stem
            _ensure_dir(out_subdir)
            out_path = out_subdir / f"ann_{ann_id:06d}_cat_{cat_id}_{cat_safe}.png"

            if out_path.exists() and not overwrite:
                skipped += 1
                continue

            Image.fromarray(mask, mode="L").save(out_path)
            written += 1
        except Exception:
            errors += 1

    return {"written": written, "skipped": skipped, "errors": errors}


def main() -> None:
    ap = argparse.ArgumentParser(description="Generate per-instance binary masks from COCO annotations.")
    ap.add_argument(
        "--scenes-dir",
        type=str,
        default=str(Path("data") / "scenes"),
        help="Directory that contains scene subfolders.",
    )
    ap.add_argument(
        "--ann-name",
        type=str,
        default=None,
        help="If set, only this annotation filename per scene (legacy). "
        "Otherwise uses _annotations_original + _annotations_extended (+ fixed fallback).",
    )
    ap.add_argument(
        "--scene",
        type=str,
        default=None,
        help="Only process this scene folder name (e.g. cut_lemon).",
    )
    ap.add_argument(
        "--out-name",
        type=str,
        default="instance_masks",
        help="Output directory name to create inside each scene directory.",
    )
    ap.add_argument("--overwrite", action="store_true", help="Overwrite existing mask pngs.")
    args = ap.parse_args()

    scenes_dir = Path(args.scenes_dir)
    if not scenes_dir.exists():
        raise SystemExit(f"Scenes dir not found: {scenes_dir}")

    scene_dirs = [p for p in scenes_dir.iterdir() if p.is_dir()]
    scene_dirs.sort(key=lambda p: p.name.lower())

    total = {"written": 0, "skipped": 0, "errors": 0, "scenes": 0}
    for scene_dir in scene_dirs:
        if args.scene and scene_dir.name != args.scene:
            continue
        if args.ann_name:
            coco_paths = [scene_dir / args.ann_name]
        else:
            coco_paths = iter_scene_coco_for_masks(scene_dir)
        if not coco_paths or not all(p.is_file() for p in coco_paths):
            continue
        out_dir = scene_dir / args.out_name
        _ensure_dir(out_dir)
        scene_written = scene_skipped = scene_errors = 0
        for coco_path in coco_paths:
            stats = generate_masks_for_coco(coco_path, out_dir, overwrite=args.overwrite)
            scene_written += stats["written"]
            scene_skipped += stats["skipped"]
            scene_errors += stats["errors"]
            print(
                f"[{scene_dir.name}] {coco_path.name} written={stats['written']} "
                f"skipped={stats['skipped']} errors={stats['errors']}"
            )
        total["written"] += scene_written
        total["skipped"] += scene_skipped
        total["errors"] += scene_errors
        total["scenes"] += 1

    print(
        f"Done. scenes={total['scenes']} written={total['written']} skipped={total['skipped']} errors={total['errors']}"
    )


if __name__ == "__main__":
    main()