perceptra-train 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. perceptra_train/__init__.py +46 -0
  2. perceptra_train/__version__.py +8 -0
  3. perceptra_train/cli.py +186 -0
  4. perceptra_train/converters/__init__.py +6 -0
  5. perceptra_train/converters/coco.py +60 -0
  6. perceptra_train/converters/yolo.py +53 -0
  7. perceptra_train/core/__init__.py +6 -0
  8. perceptra_train/core/geometry.py +264 -0
  9. perceptra_train/core/registry.py +78 -0
  10. perceptra_train/core/types.py +238 -0
  11. perceptra_train/filters/__init__.py +28 -0
  12. perceptra_train/filters/base.py +45 -0
  13. perceptra_train/filters/merge.py +41 -0
  14. perceptra_train/filters/model_filter.py +251 -0
  15. perceptra_train/filters/rules.py +153 -0
  16. perceptra_train/generator.py +121 -0
  17. perceptra_train/models/__init__.py +5 -0
  18. perceptra_train/models/annotations.py +50 -0
  19. perceptra_train/models/base.py +92 -0
  20. perceptra_train/models/sam.py +191 -0
  21. perceptra_train/models/ultralytics.py +181 -0
  22. perceptra_train/pipeline/__init__.py +7 -0
  23. perceptra_train/pipeline/builder.py +129 -0
  24. perceptra_train/pipeline/config.py +216 -0
  25. perceptra_train/pipeline/manifest.py +100 -0
  26. perceptra_train/pipeline/runner.py +426 -0
  27. perceptra_train/sources/__init__.py +5 -0
  28. perceptra_train/sources/base.py +19 -0
  29. perceptra_train/sources/coco.py +64 -0
  30. perceptra_train/sources/folder.py +61 -0
  31. perceptra_train/sources/yolo.py +88 -0
  32. perceptra_train/utils/__init__.py +5 -0
  33. perceptra_train/utils/validation.py +135 -0
  34. perceptra_train/utils/visualization.py +42 -0
  35. perceptra_train/writers/__init__.py +8 -0
  36. perceptra_train/writers/base.py +50 -0
  37. perceptra_train/writers/coco.py +128 -0
  38. perceptra_train/writers/masks.py +51 -0
  39. perceptra_train/writers/visualization.py +75 -0
  40. perceptra_train/writers/yolo.py +63 -0
  41. perceptra_train-0.2.0.dist-info/METADATA +216 -0
  42. perceptra_train-0.2.0.dist-info/RECORD +46 -0
  43. perceptra_train-0.2.0.dist-info/WHEEL +5 -0
  44. perceptra_train-0.2.0.dist-info/entry_points.txt +2 -0
  45. perceptra_train-0.2.0.dist-info/licenses/LICENSE +201 -0
  46. perceptra_train-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,46 @@
1
+ """
2
+ PerceptraTrain - training data from combinations of models
3
+ ==========================================================
4
+
5
+ Producers (segmentation / detection models, existing labels) propose instances,
6
+ filter models (e.g. a crane-grab detector) remove unwanted objects, rule filters
7
+ clean up, and writers emit YOLO / COCO / mask datasets.
8
+
9
+ Quick start:
10
+ >>> from perceptra_train import run_pipeline
11
+ >>> stats = run_pipeline("pipeline.yaml")
12
+
13
+ Legacy box -> mask API:
14
+ >>> from perceptra_train import DataGenerator
15
+ """
16
+
17
+ from perceptra_train.__version__ import (
18
+ __author__,
19
+ __description__,
20
+ __email__,
21
+ __license__,
22
+ __url__,
23
+ __version__,
24
+ )
25
+ from perceptra_train.core import Frame, ImageRecord, ImageResult, Instances, register
26
+ from perceptra_train.generator import DataGenerator # perceptra-seg is imported on instantiation
27
+ from perceptra_train.pipeline import PipelineConfig, build_pipeline, finalize, run_pipeline
28
+
29
+ __all__ = [
30
+ "DataGenerator",
31
+ "Frame",
32
+ "ImageRecord",
33
+ "ImageResult",
34
+ "Instances",
35
+ "PipelineConfig",
36
+ "build_pipeline",
37
+ "finalize",
38
+ "register",
39
+ "run_pipeline",
40
+ "__version__",
41
+ "__author__",
42
+ "__email__",
43
+ "__license__",
44
+ "__url__",
45
+ "__description__",
46
+ ]
@@ -0,0 +1,8 @@
1
+ """Version information for PerceptraTrain."""
2
+
3
+ __version__ = "0.2.0"
4
+ __author__ = "Tannous Geagea"
5
+ __email__ = "tannousgeagea@hotmail.com"
6
+ __license__ = "Apache-2.0"
7
+ __url__ = "https://github.com/tannousgeagea/PerceptraTrain"
8
+ __description__ = "Generate training data from combinations of models"
perceptra_train/cli.py ADDED
@@ -0,0 +1,186 @@
1
+ """Command-line interface.
2
+
3
+ perceptra-train run pipeline.yaml [--set output.task=detect] [--shard 0/4] [--limit 50]
4
+ perceptra-train validate pipeline.yaml [--load-models]
5
+ perceptra-train inspect model.pt [model2.pt ...]
6
+ perceptra-train finalize runs/my_dataset
7
+ perceptra-train convert --images ... --annotations ... --output ... (legacy box -> mask)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import logging
15
+ import sys
16
+ from typing import Any
17
+
18
+ import yaml
19
+
20
+ from perceptra_train.__version__ import __version__
21
+
22
+
23
+ def _overrides(args: argparse.Namespace) -> dict[str, Any]:
24
+ out: dict[str, Any] = {}
25
+ for item in args.set or []:
26
+ if "=" not in item:
27
+ raise SystemExit(f"--set expects key=value, got {item!r}")
28
+ k, v = item.split("=", 1)
29
+ out[k] = yaml.safe_load(v)
30
+ if getattr(args, "shard", None):
31
+ out["runtime.shard"] = args.shard
32
+ if getattr(args, "limit", None) is not None:
33
+ out["runtime.limit"] = args.limit
34
+ if getattr(args, "device", None):
35
+ out["runtime.device"] = args.device
36
+ if getattr(args, "no_resume", False):
37
+ out["runtime.resume"] = False
38
+ if getattr(args, "output", None):
39
+ out["output.dir"] = args.output
40
+ return out
41
+
42
+
43
+ def cmd_run(args: argparse.Namespace) -> int:
44
+ from perceptra_train.pipeline import run_pipeline
45
+
46
+ stats = run_pipeline(args.config, **_overrides(args))
47
+ if args.json:
48
+ print(json.dumps(stats, indent=2))
49
+ return 0 if stats["images"]["errors"] == 0 else 2
50
+
51
+
52
+ def cmd_validate(args: argparse.Namespace) -> int:
53
+ from perceptra_train.pipeline import PipelineConfig, build_pipeline
54
+
55
+ cfg = PipelineConfig.from_yaml(args.config, _overrides(args))
56
+ print(f"config OK (fingerprint {cfg.fingerprint()})")
57
+ if args.load_models:
58
+ p = build_pipeline(cfg)
59
+ try:
60
+ print(f"categories: {p.categories}")
61
+ for prod in p.producers:
62
+ print(f"producer {prod.name}: task={prod.task} map={prod.class_map}")
63
+ for f in p.image_filters + p.instance_filters:
64
+ print(f"filter {f.name}: {type(f).__name__} image_level={f.image_level}")
65
+ print(f"images: {sum(1 for _ in p.source)}")
66
+ finally:
67
+ p.close()
68
+ return 0
69
+
70
+
71
+ def cmd_inspect(args: argparse.Namespace) -> int:
72
+ from perceptra_train.models.ultralytics import inspect_model
73
+
74
+ for w in args.weights:
75
+ print(json.dumps(inspect_model(w), indent=2))
76
+ return 0
77
+
78
+
79
+ def cmd_finalize(args: argparse.Namespace) -> int:
80
+ from perceptra_train.pipeline import finalize
81
+
82
+ finalize(args.out_dir)
83
+ return 0
84
+
85
+
86
+ def cmd_convert(args: argparse.Namespace) -> int:
87
+ from perceptra_train import DataGenerator
88
+
89
+ with DataGenerator(
90
+ segmentor_config={
91
+ "model": args.model,
92
+ "device": args.device,
93
+ "backend": "torch",
94
+ "precision": "fp16" if args.device == "cuda" else "fp32",
95
+ },
96
+ min_score_threshold=args.min_score,
97
+ min_area=args.min_area,
98
+ ) as generator:
99
+ generator.process_dataset(
100
+ images_dir=args.images,
101
+ annotations_path=args.annotations,
102
+ output_dir=args.output,
103
+ input_format=args.input_format,
104
+ output_format=args.output_format,
105
+ save_visualizations=not args.no_vis,
106
+ )
107
+ return 0
108
+
109
+
110
+ def _add_convert_args(p: argparse.ArgumentParser) -> None:
111
+ p.add_argument("--images", required=True, help="Directory containing images")
112
+ p.add_argument("--annotations", required=True, help="COCO json or YOLO labels dir")
113
+ p.add_argument("--output", required=True, help="Output directory")
114
+ p.add_argument("--input-format", choices=["yolo", "coco"], default="coco")
115
+ p.add_argument("--output-format", choices=["yolo", "coco", "masks"], default="coco")
116
+ p.add_argument("--model", default="sam_v1", help="SAM model (sam_v1 or sam_v2)")
117
+ p.add_argument("--device", default="cuda")
118
+ p.add_argument("--min-score", type=float, default=0.5)
119
+ p.add_argument("--min-area", type=int, default=100)
120
+ p.add_argument("--no-vis", action="store_true")
121
+
122
+
123
+ def build_parser() -> argparse.ArgumentParser:
124
+ parser = argparse.ArgumentParser(
125
+ prog="perceptra-train",
126
+ description="Generate training data from combinations of models (producers + filters).",
127
+ )
128
+ parser.add_argument("--version", action="version", version=__version__)
129
+ parser.add_argument("-v", "--verbose", action="store_true")
130
+ sub = parser.add_subparsers(dest="command", required=True)
131
+
132
+ def common(p: argparse.ArgumentParser) -> None:
133
+ p.add_argument("config", help="pipeline YAML")
134
+ p.add_argument("--set", action="append", metavar="KEY=VALUE",
135
+ help="override a config value, e.g. --set output.task=detect")
136
+
137
+ p = sub.add_parser("run", help="run a pipeline")
138
+ common(p)
139
+ p.add_argument("--shard", help="process shard i of N, e.g. 0/4")
140
+ p.add_argument("--limit", type=int, help="process at most N images")
141
+ p.add_argument("--device", help="override runtime.device (cpu, 0, cuda:1, ...)")
142
+ p.add_argument("--output", help="override output.dir")
143
+ p.add_argument("--no-resume", action="store_true", help="reprocess images already done")
144
+ p.add_argument("--json", action="store_true", help="print stats as JSON")
145
+ p.set_defaults(func=cmd_run)
146
+
147
+ p = sub.add_parser("validate", help="validate a pipeline config")
148
+ common(p)
149
+ p.add_argument("--load-models", action="store_true", help="also load models and check classes")
150
+ p.set_defaults(func=cmd_validate)
151
+
152
+ p = sub.add_parser("inspect", help="print task and class names of model weights")
153
+ p.add_argument("weights", nargs="+")
154
+ p.set_defaults(func=cmd_inspect)
155
+
156
+ p = sub.add_parser("finalize", help="merge shard outputs and write stats.json")
157
+ p.add_argument("out_dir")
158
+ p.set_defaults(func=cmd_finalize)
159
+
160
+ p = sub.add_parser("convert", help="legacy: detection boxes -> SAM masks")
161
+ _add_convert_args(p)
162
+ p.set_defaults(func=cmd_convert)
163
+ return parser
164
+
165
+
166
+ def main(argv: list[str] | None = None) -> None:
167
+ argv = list(sys.argv[1:] if argv is None else argv)
168
+ # legacy invocation: `perceptra-train --images ... --annotations ...`
169
+ if argv and argv[0].startswith("--") and argv[0] not in ("--help", "--version", "--verbose"):
170
+ argv = ["convert", *argv]
171
+ args = build_parser().parse_args(argv)
172
+ logging.basicConfig(
173
+ level=logging.DEBUG if args.verbose else logging.INFO,
174
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
175
+ )
176
+ try:
177
+ sys.exit(args.func(args))
178
+ except (ValueError, FileNotFoundError, RuntimeError, KeyError) as e:
179
+ if args.verbose:
180
+ raise
181
+ logging.getLogger("perceptra_train").error("%s", e)
182
+ sys.exit(1)
183
+
184
+
185
+ if __name__ == "__main__":
186
+ main()
@@ -0,0 +1,6 @@
1
+ """Format converters for PerceptraTrain."""
2
+
3
+ from perceptra_train.converters.coco import COCOConverter
4
+ from perceptra_train.converters.yolo import YOLOConverter
5
+
6
+ __all__ = ["COCOConverter", "YOLOConverter"]
@@ -0,0 +1,60 @@
1
+ """Legacy COCO helper (deprecated: use ``perceptra_train.sources.coco`` / ``writers.coco``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import defaultdict
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ class COCOConverter:
12
+ """Read COCO detection boxes and build COCO segmentation output (legacy API)."""
13
+
14
+ def load_annotations(self, json_path: Path, images_dir: Path) -> list[tuple[dict[str, Any], list[dict[str, Any]]]]:
15
+ """Return ``[(image_info, [box_info, ...]), ...]`` (boxes as x1, y1, x2, y2)."""
16
+ with open(json_path) as f:
17
+ coco = json.load(f)
18
+ categories = {c["id"]: c["name"] for c in coco.get("categories", [])}
19
+ boxes: dict[Any, list[dict[str, Any]]] = defaultdict(list)
20
+ for ann in coco.get("annotations", []):
21
+ x, y, w, h = ann["bbox"]
22
+ boxes[ann["image_id"]].append(
23
+ {
24
+ "box": (int(x), int(y), int(x + w), int(y + h)),
25
+ "category_id": ann["category_id"],
26
+ "class_name": categories.get(ann["category_id"], "unknown"),
27
+ }
28
+ )
29
+ self.original_coco = coco
30
+ return [(img, boxes[img["id"]]) for img in coco.get("images", []) if boxes.get(img["id"])]
31
+
32
+ def init_output(self, *_: Any) -> dict[str, Any]:
33
+ return {
34
+ "images": [],
35
+ "categories": self.original_coco.get("categories", []),
36
+ "annotations": [],
37
+ "info": self.original_coco.get("info", {}),
38
+ "licenses": self.original_coco.get("licenses", []),
39
+ }
40
+
41
+ def add_results(self, output: dict[str, Any], img_info: dict[str, Any], results: list[dict[str, Any]]) -> None:
42
+ if results and all(im["id"] != img_info["id"] for im in output["images"]):
43
+ output["images"].append(img_info)
44
+ for r in results:
45
+ x1, y1, x2, y2 = r["bbox"]
46
+ output["annotations"].append(
47
+ {
48
+ "id": len(output["annotations"]) + 1,
49
+ "image_id": img_info["id"],
50
+ "category_id": r["category_id"],
51
+ "segmentation": [[c for pt in poly for c in pt] for poly in r["polygons"]],
52
+ "area": float(r["area"]),
53
+ "bbox": [float(x1), float(y1), float(x2 - x1), float(y2 - y1)],
54
+ "iscrowd": 0,
55
+ }
56
+ )
57
+
58
+ def save_output(self, output: dict[str, Any], output_path: Path) -> None:
59
+ with open(output_path, "w") as f:
60
+ json.dump(output, f)
@@ -0,0 +1,53 @@
1
+ """Legacy YOLO helper (deprecated: use ``perceptra_train.sources.yolo`` / ``writers.yolo``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from PIL import Image
9
+
10
+ from perceptra_train.sources.base import IMAGE_EXTENSIONS
11
+
12
+
13
+ class YOLOConverter:
14
+ def load_annotations(self, labels_dir: Path, images_dir: Path) -> list[tuple[dict[str, Any], list[dict[str, Any]]]]:
15
+ """Return ``[(image_info, [box_info, ...]), ...]`` with absolute x1, y1, x2, y2 boxes."""
16
+ out = []
17
+ for idx, label_file in enumerate(sorted(Path(labels_dir).glob("*.txt"))):
18
+ image_path = next(
19
+ (Path(images_dir) / f"{label_file.stem}{e}" for e in IMAGE_EXTENSIONS
20
+ if (Path(images_dir) / f"{label_file.stem}{e}").exists()),
21
+ None,
22
+ )
23
+ if image_path is None:
24
+ continue
25
+ with Image.open(image_path) as im: # reads the header only
26
+ w, h = im.size
27
+ boxes = []
28
+ for line in label_file.read_text().splitlines():
29
+ parts = line.split()
30
+ if len(parts) < 5:
31
+ continue
32
+ c = int(parts[0])
33
+ cx, cy, bw, bh = map(float, parts[1:5])
34
+ boxes.append(
35
+ {
36
+ "box": (int((cx - bw / 2) * w), int((cy - bh / 2) * h), int((cx + bw / 2) * w), int((cy + bh / 2) * h)),
37
+ "category_id": c,
38
+ "class_name": f"class_{c}",
39
+ }
40
+ )
41
+ out.append(({"file_name": image_path.name, "id": idx, "width": w, "height": h}, boxes))
42
+ return out
43
+
44
+ def save_results(self, output_path: Path, results: list[dict[str, Any]], image_shape: tuple[int, ...]) -> None:
45
+ """Write YOLO segmentation lines (largest polygon per instance)."""
46
+ h, w = image_shape[:2]
47
+ with open(output_path, "w") as f:
48
+ for r in results:
49
+ if not r["polygons"]:
50
+ continue
51
+ poly = max(r["polygons"], key=len)
52
+ coords = " ".join(f"{x / w:.6f} {y / h:.6f}" for x, y in poly)
53
+ f.write(f"{r['category_id']} {coords}\n")
@@ -0,0 +1,6 @@
1
+ """Core types, geometry and plugin registry."""
2
+
3
+ from perceptra_train.core.registry import register
4
+ from perceptra_train.core.types import Frame, ImageRecord, ImageResult, Instances
5
+
6
+ __all__ = ["Frame", "ImageRecord", "ImageResult", "Instances", "register"]
@@ -0,0 +1,264 @@
1
+ """Vectorised box / crop-mask geometry.
2
+
3
+ All masks here are *crop masks*: ``(crop: bool[h, w], x0, y0)`` placed at
4
+ ``(x0, y0)`` in image coordinates. Every operation touches only the
5
+ overlapping window of two crops, so cost scales with object size, not image size.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ CropMask = tuple[np.ndarray, int, int]
14
+
15
+
16
+ # --------------------------------------------------------------------- boxes
17
+ def box_area(boxes: np.ndarray) -> np.ndarray:
18
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
19
+ return np.clip(boxes[:, 2] - boxes[:, 0], 0, None) * np.clip(boxes[:, 3] - boxes[:, 1], 0, None)
20
+
21
+
22
+ def box_intersection(a: np.ndarray, b: np.ndarray) -> np.ndarray:
23
+ """Pairwise intersection area, (N, M)."""
24
+ a = np.asarray(a, dtype=np.float32).reshape(-1, 4)
25
+ b = np.asarray(b, dtype=np.float32).reshape(-1, 4)
26
+ lt = np.maximum(a[:, None, :2], b[None, :, :2])
27
+ rb = np.minimum(a[:, None, 2:], b[None, :, 2:])
28
+ wh = np.clip(rb - lt, 0, None)
29
+ return wh[..., 0] * wh[..., 1]
30
+
31
+
32
+ def box_iou(a: np.ndarray, b: np.ndarray) -> np.ndarray:
33
+ inter = box_intersection(a, b)
34
+ union = box_area(a)[:, None] + box_area(b)[None, :] - inter
35
+ return np.where(union > 0, inter / np.maximum(union, 1e-9), 0.0)
36
+
37
+
38
+ def box_ioa(a: np.ndarray, b: np.ndarray) -> np.ndarray:
39
+ """Intersection over area of ``a`` (share of each ``a`` box covered by each ``b`` box)."""
40
+ inter = box_intersection(a, b)
41
+ area = box_area(a)[:, None]
42
+ return np.where(area > 0, inter / np.maximum(area, 1e-9), 0.0)
43
+
44
+
45
+ def expand_boxes(boxes: np.ndarray, px: float, image_size: tuple[int, int]) -> np.ndarray:
46
+ """Grow boxes by ``px`` on every side, clipped to the image."""
47
+ h, w = image_size
48
+ out = np.asarray(boxes, dtype=np.float32).reshape(-1, 4).copy()
49
+ out[:, :2] -= px
50
+ out[:, 2:] += px
51
+ return clip_boxes(out, image_size)
52
+
53
+
54
+ def clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
55
+ h, w = image_size
56
+ out = np.asarray(boxes, dtype=np.float32).reshape(-1, 4).copy()
57
+ out[:, [0, 2]] = out[:, [0, 2]].clip(0, w)
58
+ out[:, [1, 3]] = out[:, [1, 3]].clip(0, h)
59
+ return out
60
+
61
+
62
+ def int_box(box: np.ndarray, image_size: tuple[int, int]) -> tuple[int, int, int, int]:
63
+ """Outer integer pixel window of a float box, clipped to the image."""
64
+ h, w = image_size
65
+ x0 = int(np.clip(np.floor(box[0]), 0, w))
66
+ y0 = int(np.clip(np.floor(box[1]), 0, h))
67
+ x1 = int(np.clip(np.ceil(box[2]), 0, w))
68
+ y1 = int(np.clip(np.ceil(box[3]), 0, h))
69
+ return x0, y0, x1, y1
70
+
71
+
72
+ # --------------------------------------------------------------- crop masks
73
+ def crop_bbox(crop: np.ndarray, x0: int, y0: int) -> tuple[int, int, int, int] | None:
74
+ """Tight xyxy box (exclusive max) of a crop mask, None when empty."""
75
+ rows = np.flatnonzero(crop.any(axis=1))
76
+ if rows.size == 0:
77
+ return None
78
+ cols = np.flatnonzero(crop.any(axis=0))
79
+ return x0 + int(cols[0]), y0 + int(rows[0]), x0 + int(cols[-1]) + 1, y0 + int(rows[-1]) + 1
80
+
81
+
82
+ def tighten(crop: np.ndarray, x0: int, y0: int) -> CropMask | None:
83
+ """Shrink a crop to its non-zero extent."""
84
+ bb = crop_bbox(crop, x0, y0)
85
+ if bb is None:
86
+ return None
87
+ bx0, by0, bx1, by1 = bb
88
+ return crop[by0 - y0 : by1 - y0, bx0 - x0 : bx1 - x0], bx0, by0
89
+
90
+
91
+ def from_full(mask: np.ndarray) -> CropMask | None:
92
+ return tighten(np.asarray(mask, dtype=bool), 0, 0)
93
+
94
+
95
+ def paste(crop: np.ndarray, x0: int, y0: int, image_size: tuple[int, int]) -> np.ndarray:
96
+ h, w = image_size
97
+ full = np.zeros((h, w), dtype=bool)
98
+ ch, cw = crop.shape
99
+ full[y0 : y0 + ch, x0 : x0 + cw] = crop[: max(0, h - y0), : max(0, w - x0)]
100
+ return full
101
+
102
+
103
+ def _window(a: tuple[int, int, int, int], b: tuple[int, int, int, int]):
104
+ x0, y0 = max(a[0], b[0]), max(a[1], b[1])
105
+ x1, y1 = min(a[2], b[2]), min(a[3], b[3])
106
+ if x1 <= x0 or y1 <= y0:
107
+ return None
108
+ return x0, y0, x1, y1
109
+
110
+
111
+ def crop_extent(crop: np.ndarray, x0: int, y0: int) -> tuple[int, int, int, int]:
112
+ return x0, y0, x0 + crop.shape[1], y0 + crop.shape[0]
113
+
114
+
115
+ def crop_box_intersection(crop: np.ndarray, x0: int, y0: int, box) -> int:
116
+ """Number of mask pixels inside an (integer-rounded) box."""
117
+ win = _window(crop_extent(crop, x0, y0), tuple(int(round(v)) for v in box))
118
+ if win is None:
119
+ return 0
120
+ wx0, wy0, wx1, wy1 = win
121
+ return int(np.count_nonzero(crop[wy0 - y0 : wy1 - y0, wx0 - x0 : wx1 - x0]))
122
+
123
+
124
+ def crop_crop_intersection(a: CropMask, b: CropMask) -> int:
125
+ ca, ax, ay = a
126
+ cb, bx, by = b
127
+ win = _window(crop_extent(ca, ax, ay), crop_extent(cb, bx, by))
128
+ if win is None:
129
+ return 0
130
+ x0, y0, x1, y1 = win
131
+ return int(
132
+ np.count_nonzero(
133
+ ca[y0 - ay : y1 - ay, x0 - ax : x1 - ax] & cb[y0 - by : y1 - by, x0 - bx : x1 - bx]
134
+ )
135
+ )
136
+
137
+
138
+ def window_of(crop_or_box, x0: int | None = None, y0: int | None = None):
139
+ if x0 is None:
140
+ return tuple(int(round(v)) for v in crop_or_box)
141
+ return crop_extent(crop_or_box, x0, y0)
142
+
143
+
144
+ def region_in_window(
145
+ window: tuple[int, int, int, int],
146
+ boxes: np.ndarray,
147
+ masks: list[CropMask | None],
148
+ ) -> np.ndarray:
149
+ """Rasterise the union of regions (box, or mask when available) into ``window``."""
150
+ wx0, wy0, wx1, wy1 = window
151
+ out = np.zeros((wy1 - wy0, wx1 - wx0), dtype=bool)
152
+ for box, m in zip(boxes, masks):
153
+ if m is None:
154
+ win = _window(window, tuple(int(round(v)) for v in box))
155
+ if win is not None:
156
+ x0, y0, x1, y1 = win
157
+ out[y0 - wy0 : y1 - wy0, x0 - wx0 : x1 - wx0] = True
158
+ else:
159
+ crop, mx, my = m
160
+ win = _window(window, crop_extent(crop, mx, my))
161
+ if win is not None:
162
+ x0, y0, x1, y1 = win
163
+ out[y0 - wy0 : y1 - wy0, x0 - wx0 : x1 - wx0] |= crop[
164
+ y0 - my : y1 - my, x0 - mx : x1 - mx
165
+ ]
166
+ return out
167
+
168
+
169
+ def dilate_crop(crop: np.ndarray, x0: int, y0: int, px: int, image_size: tuple[int, int]) -> CropMask:
170
+ """Morphological dilation that grows the crop canvas (clipped to the image)."""
171
+ if px <= 0:
172
+ return crop, x0, y0
173
+ h, w = image_size
174
+ nx0, ny0 = max(0, x0 - px), max(0, y0 - px)
175
+ nx1, ny1 = min(w, x0 + crop.shape[1] + px), min(h, y0 + crop.shape[0] + px)
176
+ canvas = np.zeros((ny1 - ny0, nx1 - nx0), dtype=np.uint8)
177
+ canvas[y0 - ny0 : y0 - ny0 + crop.shape[0], x0 - nx0 : x0 - nx0 + crop.shape[1]] = crop
178
+ k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * px + 1, 2 * px + 1))
179
+ return cv2.dilate(canvas, k).astype(bool), nx0, ny0
180
+
181
+
182
+ # ------------------------------------------------------------------ polygons
183
+ def mask_to_polygons(
184
+ crop: np.ndarray,
185
+ x0: int,
186
+ y0: int,
187
+ epsilon: float = 1.0,
188
+ min_area: float = 4.0,
189
+ ) -> list[np.ndarray]:
190
+ """External contours as float32 (K, 2) arrays in image coordinates, largest first.
191
+
192
+ ``epsilon`` is the Douglas-Peucker tolerance in pixels (0 disables simplification).
193
+ """
194
+ if crop.size == 0:
195
+ return []
196
+ padded = np.pad(crop.astype(np.uint8), 1)
197
+ contours, _ = cv2.findContours(padded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
198
+ polys: list[tuple[float, np.ndarray]] = []
199
+ for c in contours:
200
+ area = cv2.contourArea(c)
201
+ if area < min_area:
202
+ continue
203
+ if epsilon > 0:
204
+ c = cv2.approxPolyDP(c, epsilon, True)
205
+ if len(c) < 3:
206
+ continue
207
+ pts = c.reshape(-1, 2).astype(np.float32)
208
+ pts += np.array([x0 - 1, y0 - 1], dtype=np.float32)
209
+ polys.append((area, pts))
210
+ polys.sort(key=lambda t: -t[0])
211
+ return [p for _, p in polys]
212
+
213
+
214
+ def polygons_to_crop(polygons: list[np.ndarray], image_size: tuple[int, int]) -> CropMask | None:
215
+ if not polygons:
216
+ return None
217
+ allpts = np.concatenate([np.asarray(p, np.float32).reshape(-1, 2) for p in polygons])
218
+ h, w = image_size
219
+ x0 = int(np.clip(np.floor(allpts[:, 0].min()), 0, w))
220
+ y0 = int(np.clip(np.floor(allpts[:, 1].min()), 0, h))
221
+ x1 = int(np.clip(np.ceil(allpts[:, 0].max()) + 1, 0, w))
222
+ y1 = int(np.clip(np.ceil(allpts[:, 1].max()) + 1, 0, h))
223
+ if x1 <= x0 or y1 <= y0:
224
+ return None
225
+ canvas = np.zeros((y1 - y0, x1 - x0), dtype=np.uint8)
226
+ cv2.fillPoly(
227
+ canvas,
228
+ [np.round(np.asarray(p, np.float32).reshape(-1, 2) - [x0, y0]).astype(np.int32) for p in polygons],
229
+ 1,
230
+ )
231
+ return tighten(canvas.astype(bool), x0, y0)
232
+
233
+
234
+ def box_to_crop(box: np.ndarray, image_size: tuple[int, int]) -> CropMask | None:
235
+ x0, y0, x1, y1 = int_box(box, image_size)
236
+ if x1 <= x0 or y1 <= y0:
237
+ return None
238
+ return np.ones((y1 - y0, x1 - x0), dtype=bool), x0, y0
239
+
240
+
241
+ # ----------------------------------------------------------------------- RLE
242
+ def rle_encode(full_mask: np.ndarray) -> dict:
243
+ """COCO RLE. Uses pycocotools (compressed) when available, else uncompressed counts."""
244
+ try:
245
+ from pycocotools import mask as mask_utils
246
+
247
+ rle = mask_utils.encode(np.asfortranarray(full_mask.astype(np.uint8)))
248
+ rle["counts"] = rle["counts"].decode("ascii")
249
+ return rle
250
+ except ImportError:
251
+ return rle_encode_uncompressed(full_mask)
252
+
253
+
254
+ def rle_encode_uncompressed(full_mask: np.ndarray) -> dict:
255
+ """Uncompressed COCO RLE (column-major runs, starting with a zero-run)."""
256
+ flat = np.asarray(full_mask, dtype=np.uint8).ravel(order="F")
257
+ counts: list[int] = []
258
+ if flat.size:
259
+ change = np.flatnonzero(flat[1:] != flat[:-1]) + 1
260
+ bounds = np.concatenate([[0], change, [flat.size]])
261
+ counts = np.diff(bounds).astype(int).tolist()
262
+ if flat[0] == 1:
263
+ counts = [0] + counts
264
+ return {"size": [int(full_mask.shape[0]), int(full_mask.shape[1])], "counts": counts}