Coverage for collectra/tasks/image_segmentation/data.py: 92.31%

169 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Shared image/mask geometry and lossless COCO preparation for segmentation backends.""" 

2 

3from __future__ import annotations 

4 

5import json 

6import time 

7from pydantic import BaseModel 

8 

9from collectra.commons import PositionalFields 

10from pathlib import Path 

11 

12import numpy as np 

13from PIL import Image as PILImage 

14 

15from collectra.types.images import Image, ImageSegmentation 

16 

17 

18def training_progress(message): 

19 print(f"[Segmentation] {message}", flush=True) 

20 

21 

22def _bounds(image: Image): 

23 return tuple(round(value) for value in image.display_bounds()) 

24 

25 

26def mask_in_view(image: Image, mask: PILImage.Image): 

27 """Apply the same crop, region and rotation as image.pil().""" 

28 if mask.size != (image.raw_width, image.raw_height): 

29 raise ValueError("Annotation mask dimensions differ from the source image") 

30 if isinstance(image, ImageSegmentation): 

31 pixels = (np.asarray(mask) != 0) & (np.asarray(image._mask_image()) != 0) 

32 mask = PILImage.fromarray(pixels.astype("uint8")) 

33 return mask.crop(_bounds(image)).rotate(image.orientation.to_degree(), expand=True) 

34 

35 

36def mask_to_source(image: Image, mask: np.ndarray): 

37 """Invert the displayed image's rotation/crop into source-sized 0/1 pixels.""" 

38 local = PILImage.fromarray(mask.astype("uint8")) 

39 local = local.rotate(-image.orientation.to_degree(), expand=True) 

40 left, top, right, bottom = _bounds(image) 

41 if local.size != (right - left, bottom - top): 

42 raise ValueError("Predicted mask dimensions differ from the input image view") 

43 source = PILImage.new("L", (image.raw_width, image.raw_height)) 

44 source.paste(local, (left, top)) 

45 pixels = np.asarray(source) != 0 

46 if isinstance(image, ImageSegmentation): 

47 pixels &= np.asarray(image._mask_image()) != 0 

48 return pixels.astype("uint8") 

49 

50 

51def encode_rle(mask: np.ndarray): 

52 """Lossless COCO uncompressed RLE, including holes and disconnected pixels.""" 

53 values = np.asarray(mask, dtype=np.uint8).ravel(order="F") 

54 boundaries = np.concatenate( 

55 ([0], np.flatnonzero(values[1:] != values[:-1]) + 1, [len(values)]) 

56 ) 

57 counts = np.diff(boundaries).tolist() 

58 if len(values) and values[0]: 

59 counts.insert(0, 0) 

60 return {"size": list(mask.shape), "counts": counts} 

61 

62 

63class SegmentationSample(PositionalFields, BaseModel): 

64 image: Image 

65 instances: list[ImageSegmentation] 

66 

67 

68def prepare_segmentation_inputs( 

69 processed_inputs, processed_parents, input_maps, parent_input_maps 

70): 

71 samples = [] 

72 for filename, instances in input_maps.items(): 

73 parents = { 

74 image.id: image 

75 for image in parent_input_maps.get(filename, []) 

76 if isinstance(image, Image) 

77 } 

78 grouped = {} 

79 for instance in instances: 

80 if not isinstance(instance, ImageSegmentation): 

81 raise TypeError( 

82 "Segmentation training targets must be ImageSegmentation instances" 

83 ) 

84 ids = ( 

85 [instance.parents] 

86 if isinstance(instance.parents, str) 

87 else instance.parents 

88 ) 

89 candidates = [parents[key] for key in ids if key in parents] 

90 if len(candidates) != 1: 

91 raise ValueError( 

92 f"Mask {instance.id!r} must identify exactly one input image parent" 

93 ) 

94 parent = candidates[0] 

95 if parent.get_path().resolve() != instance.get_path().resolve(): 

96 raise ValueError( 

97 f"Mask {instance.id!r} refers to a different source image" 

98 ) 

99 grouped.setdefault( 

100 parent.id, SegmentationSample(parent, []) 

101 ).instances.append(instance) 

102 samples.extend(grouped.values()) 

103 return samples 

104 

105 

106def _sample_partition(sample): 

107 partitions = {item.partition for item in sample.instances if item.partition} 

108 if sample.image.partition: 

109 partitions.add(sample.image.partition) 

110 if len(partitions) > 1: 

111 raise ValueError("Instances of one image cannot belong to different partitions") 

112 return next(iter(partitions), "") 

113 

114 

115def export_dataset( 

116 samples, directory: Path, *, prompts=None, validation="", exclude="", max_items=None, 

117 progress=None, 

118): 

119 progress = progress or training_progress 

120 if max_items is not None and max_items < 1: 

121 raise ValueError("max_items must be positive") 

122 started = time.monotonic() 

123 directory = Path(directory).resolve() 

124 selected = [] 

125 for sample in samples: 

126 partition = _sample_partition(sample) 

127 if exclude and partition == exclude: 

128 continue 

129 selected.append( 

130 (sample, "valid" if validation and partition == validation else "train") 

131 ) 

132 if max_items is not None and len(selected) >= max_items: 

133 break 

134 labels = sorted({item.name for sample, _ in selected for item in sample.instances}) 

135 if not labels or not any(split == "train" for _, split in selected): 

136 raise ValueError("No labelled training instances were found") 

137 categories = [ 

138 {"id": index + 1, "name": (prompts or {}).get(label, label.replace("_", " "))} 

139 for index, label in enumerate(labels) 

140 ] 

141 label_ids = {label: index + 1 for index, label in enumerate(labels)} 

142 progress( 

143 f"Exporting {len(selected)} images and " 

144 f"{sum(len(sample.instances) for sample, _ in selected)} masks to {directory} " 

145 f"({sum(split == 'train' for _, split in selected)} train, " 

146 f"{sum(split == 'valid' for _, split in selected)} validation images)" 

147 ) 

148 datasets = { 

149 split: {"images": [], "annotations": [], "categories": categories} 

150 for split in ("train", "valid") 

151 } 

152 for split in datasets: 

153 (directory / split).mkdir(parents=True, exist_ok=True) 

154 skipped_masks, skipped_images = [], [] 

155 image_id = 0 

156 for index, (sample, split) in enumerate(selected, 1): 

157 progress( 

158 f"Export {index}/{len(selected)} [{split}]: {sample.image.id} " 

159 f"({len(sample.instances)} masks; {time.monotonic() - started:.1f}s elapsed)" 

160 ) 

161 image = sample.image.pil().convert("RGB") 

162 annotations = [] 

163 for mask_index, instance in enumerate(sample.instances, 1): 

164 mask = np.asarray(mask_in_view(sample.image, instance._mask_image())) != 0 

165 ys, xs = np.nonzero(mask) 

166 if not len(xs): 

167 # Usually an annotation lying outside its parent region; skip it 

168 # rather than abandon the whole export. 

169 skipped_masks.append(instance.id) 

170 progress( 

171 f" WARNING: skipping mask {instance.id!r}: no pixels inside " 

172 f"its input image {sample.image.id!r}" 

173 ) 

174 continue 

175 if mask.shape != (image.height, image.width): 

176 raise ValueError( 

177 "Image subclass crop differs from its declared display bounds" 

178 ) 

179 annotations.append( 

180 { 

181 "category_id": label_ids[instance.name], 

182 "iscrowd": 0, 

183 "bbox": [ 

184 int(xs.min()), 

185 int(ys.min()), 

186 int(xs.max() - xs.min() + 1), 

187 int(ys.max() - ys.min() + 1), 

188 ], 

189 "area": int(mask.sum()), 

190 "segmentation": encode_rle(mask), 

191 } 

192 ) 

193 if mask_index % 25 == 0: 

194 progress( 

195 f" Image {index}/{len(selected)}: encoded mask " 

196 f"{mask_index}/{len(sample.instances)}" 

197 ) 

198 if sample.instances and not annotations: 

199 # Without its masks the image would wrongly teach that it has no instances. 

200 skipped_images.append(sample.image.id) 

201 progress( 

202 f" WARNING: skipping image {sample.image.id!r}: none of its " 

203 f"{len(sample.instances)} masks lie inside it" 

204 ) 

205 continue 

206 image_id += 1 

207 filename = f"{image_id:08d}.png" 

208 image.save(directory / split / filename) 

209 data = datasets[split] 

210 data["images"].append( 

211 { 

212 "id": image_id, 

213 "file_name": filename, 

214 "width": image.width, 

215 "height": image.height, 

216 } 

217 ) 

218 for annotation in annotations: 

219 data["annotations"].append( 

220 {"id": len(data["annotations"]) + 1, "image_id": image_id, **annotation} 

221 ) 

222 if skipped_masks: 

223 progress( 

224 f"WARNING: skipped {len(skipped_masks)} masks with no pixels inside their " 

225 f"input images and {len(skipped_images)} images left without masks" 

226 ) 

227 if not datasets["train"]["images"]: 

228 raise ValueError("No labelled training instances remain after skipping empty masks") 

229 for split, data in datasets.items(): 

230 progress( 

231 f"Writing {split} annotations: {len(data['images'])} images, " 

232 f"{len(data['annotations'])} masks" 

233 ) 

234 (directory / split / "_annotations.coco.json").write_text( 

235 json.dumps(data), encoding="utf-8" 

236 ) 

237 progress(f"Dataset export complete ({time.monotonic() - started:.1f}s): {directory}") 

238 return directory 

239 

240 

241class SegmentationTrainingData: 

242 """Backend-independent annotated instance collection and export.""" 

243 

244 def _samples(self, inputs, max_items=None, exclude=""): 

245 from collectra.tasks.machine_learning.training import ( 

246 _training_files, 

247 _prepare_data, 

248 ) 

249 

250 if self.pipeline is None: 

251 raise RuntimeError( 

252 "Attach the task to a pipeline before preparing training data" 

253 ) 

254 started = time.monotonic() 

255 self._progress("Discovering training result files (CPU/I/O preparation)") 

256 self.pipeline._ensure_workflow_connected() 

257 node = self.pipeline.node_manager.resolve_node(self.name) 

258 files = [] 

259 for value in inputs: 

260 path = Path(value).expanduser().resolve() 

261 self._progress(f"Scanning {path}") 

262 if path.name == "results.yaml" and path.is_file(): 

263 path = path.parent 

264 if path.is_dir() and (path / "results.yaml").is_file(): 

265 files.append(path) 

266 else: 

267 files.extend(_training_files(self, [str(path)])) 

268 samples = [] 

269 files = list(dict.fromkeys(files)) 

270 self._progress(f"Found {len(files)} result files; loading images and validating masks") 

271 for index, path in enumerate(files, 1): 

272 self._progress( 

273 f"Load {index}/{len(files)}: {path} " 

274 f"({time.monotonic() - started:.1f}s elapsed)" 

275 ) 

276 # Read each results directory independently. Different datasets can 

277 # have the same page basename and even the same artefact ids. 

278 targets, target_maps = _prepare_data( 

279 self, [path], self.pipeline.node_manager.get_children_artefact(node) 

280 ) 

281 parents, parent_maps = _prepare_data( 

282 self, [path], self.pipeline.node_manager.get_ancestor_artefacts(node) 

283 ) 

284 for sample in prepare_segmentation_inputs(targets, parents, target_maps, parent_maps): 

285 if max_items is not None and exclude and _sample_partition(sample) == exclude: 

286 continue 

287 samples.append(sample) 

288 if max_items is not None and len(samples) >= max_items: 

289 break 

290 if max_items is not None and len(samples) >= max_items: 

291 self._progress(f"Reached max_items={max_items}; stopping source loading") 

292 break 

293 self._progress( 

294 f"Loaded {len(samples)} labelled images and " 

295 f"{sum(len(sample.instances) for sample in samples)} masks " 

296 f"({time.monotonic() - started:.1f}s)" 

297 ) 

298 return samples 

299 

300 def prepare_training_data( 

301 self, inputs: list[str], output: Path, validation: str = "", exclude: str = "", 

302 max_items: int | None = None, 

303 ) -> Path: 

304 """Export annotated masks and input images as lossless COCO datasets.""" 

305 samples = self._samples(inputs, max_items=max_items, exclude=exclude) 

306 return export_dataset( 

307 samples, 

308 output, 

309 prompts=self._label_prompts(samples), 

310 progress=self._progress, 

311 validation=validation, 

312 exclude=exclude, 

313 max_items=max_items, 

314 ) 

315 

316 def _label_prompts(self, samples): 

317 return self._prompts() 

318