Coverage for collectra/tasks/image_classifier/yolo.py: 93.78%

209 statements  

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

1from __future__ import annotations 

2 

3import re 

4import shutil 

5import tempfile 

6from pathlib import Path 

7from typing import Annotated, TYPE_CHECKING 

8 

9from cappa import Arg 

10from pydantic import PrivateAttr 

11 

12from PIL import Image as PillowImage 

13 

14from collectra.cli import command 

15from collectra.types.images import ( 

16 Image, 

17 ImageCrop, 

18 image_channel_count, 

19 open_oriented, 

20) 

21from collectra.types.links import Link 

22from collectra.utils import change_dir 

23 

24from collectra.logger import get_logger 

25from collectra.utils import threading_locked 

26from ..machine_learning.training import print_distribution_table, run_training_command 

27from ..machine_learning.yolo import YOLOTask, get_yolo_class 

28from .training import prepare_classification_inputs 

29 

30if TYPE_CHECKING: 

31 from ultralytics.engine.results import Results 

32 from ultralytics.models import YOLO 

33 from ultralytics.utils.metrics import ClassifyMetrics 

34 

35__all__ = ["ImageClassifierYOLO"] 

36 

37logger = get_logger(__name__) 

38 

39 

40def _classification_channels(*roots): 

41 """Inspect every prepared image using metadata, before starting training.""" 

42 detected = {} 

43 for root in roots: 

44 if root is None: 

45 continue 

46 for path in sorted(Path(root).rglob("*")): 

47 if path.is_file() and path.suffix.lower() in Image.file_extensions(): 

48 try: 

49 detected[path] = image_channel_count(path) 

50 except Exception as error: 

51 raise ValueError( 

52 f"Cannot determine channels for {path}: {error}" 

53 ) from error 

54 if not detected: 

55 raise ValueError("No prepared classification images found") 

56 if len(set(detected.values())) != 1: 

57 details = ", ".join( 

58 f"{path}: {count} channels" for path, count in detected.items() 

59 ) 

60 raise ValueError( 

61 f"Inconsistent input channel counts in classifier dataset: {details}" 

62 ) 

63 channels = next(iter(detected.values())) 

64 tensor_loader = channels != 3 or any( 

65 p.suffix.lower() in {".tif", ".tiff"} for p in detected 

66 ) 

67 return channels, tensor_loader 

68 

69 

70def class_folder_names(classes: list[str]) -> list[str]: 

71 """Training folder names that make Ultralytics number the classes in this order. 

72 

73 Ultralytics numbers classes by sorted folder name, so the folders are numbered. 

74 """ 

75 width = max(2, len(str(len(classes) - 1))) 

76 return [f"{index:0{width}d}_{name}" for index, name in enumerate(classes)] 

77 

78 

79def _without_number(name: str) -> str: 

80 return re.sub(r"^\d+_", "", name) 

81 

82 

83class ImageClassifierYOLO(YOLOTask): 

84 prepare_training_inputs = staticmethod(prepare_classification_inputs) 

85 

86 _checked_names: list[str] | None = PrivateAttr(default=None) 

87 

88 def _outputs(self) -> list[str]: 

89 output = getattr(self, "output", []) 

90 return output if isinstance(output, list) else [output] 

91 

92 def _output_for(self, index: int, model_names: dict[int, str]) -> str: 

93 """The pipeline's output for a class number, after checking the model fits. 

94 

95 The pipeline is the source of truth: the names the model holds are only 

96 compared, and a difference is warned about once. 

97 """ 

98 outputs = self._outputs() 

99 names = [model_names[number] for number in sorted(model_names)] 

100 if len(names) != len(outputs): 

101 raise ValueError( 

102 f"Task {self.name!r} has {len(outputs)} output(s) " 

103 f"({', '.join(outputs)}) but the model has {len(names)} classes." 

104 ) 

105 agree = outputs in (names, [_without_number(name) for name in names]) 

106 if not agree and self._checked_names != names: 

107 logger.warning( 

108 "Class names in the model (%s) differ from the outputs of task %r " 

109 "(%s); using the pipeline's outputs, in the pipeline's order.", 

110 ", ".join(names), 

111 self.name, 

112 ", ".join(outputs), 

113 ) 

114 self._checked_names = names 

115 return outputs[index] 

116 

117 @threading_locked() 

118 def run(self, *args: Image, **kwargs) -> Link: 

119 """Run image classification inference on the provided Image. 

120 

121 Args: 

122 *args: A single Image (or ImageCrop) to classify. 

123 

124 Returns: 

125 Link: A link from the predicted class node to the input image. 

126 """ 

127 if len(args) != 1: 

128 raise ValueError("This task only supports a single Image input.") 

129 if not isinstance(args[0], Image): 

130 raise TypeError("Input must be an instance of Image.") 

131 image: Image = args[0] 

132 self._init_model() 

133 

134 if ( 

135 getattr( 

136 getattr(self.model, "model", None), 

137 "collectra_tensor_classification", 

138 False, 

139 ) 

140 or image.get_path().suffix.lower() in {".tif", ".tiff"} 

141 or image_channel_count(image.get_path()) != 3 

142 ): 

143 from .yolo_multichannel import classify_multichannel 

144 

145 index, names = classify_multichannel(self.model, image) 

146 else: 

147 index, names = self._predict_rgb(image) 

148 

149 predicted_class = self._output_for(index, names) 

150 print(f"Classified as: {predicted_class}") 

151 

152 return Link(name=predicted_class, target=image) 

153 

154 def _predict_rgb(self, image): 

155 if isinstance(image, ImageCrop): 

156 with tempfile.TemporaryDirectory() as temp_dir: 

157 img = image.pil() 

158 img_path = Path(temp_dir) / Path(image.get_path()).name 

159 img.save(img_path) 

160 results: Results = (self.model(img_path))[0] 

161 else: 

162 results: Results = (self.model(image.get_path()))[0] 

163 

164 if results.probs is None: 

165 raise ValueError("No classification probabilities returned.") 

166 

167 return results.probs.top1, results.names 

168 

169 @command 

170 def train( 

171 self, 

172 inputs: Annotated[ 

173 list[str], 

174 Arg( 

175 help="Pipeline data files or directories containing image classification labels." 

176 ), 

177 ], 

178 model: Annotated[ 

179 str, 

180 Arg( 

181 help="YOLO classification weights name or checkpoint path (for example yolo26n-cls.pt), or a model YAML file. Omit to keep the configured model." 

182 ), 

183 ] = "", 

184 output: Annotated[ 

185 Path | None, 

186 Arg(help="Directory for training logs, dataset files, and checkpoints."), 

187 ] = None, 

188 keep_log: Annotated[ 

189 bool, 

190 Arg( 

191 help="Keep the training directory after saving the model to the pipeline." 

192 ), 

193 ] = True, 

194 validation: Annotated[ 

195 str, 

196 Arg(help="Partition value identifying validation examples."), 

197 ] = "", 

198 exclude: Annotated[ 

199 str, 

200 Arg(help="Partition value identifying examples to exclude from training."), 

201 ] = "", 

202 epochs: Annotated[ 

203 int, 

204 Arg(help="Number of training epochs."), 

205 ] = 100, 

206 batch: Annotated[ 

207 int, 

208 Arg(help="Training batch size."), 

209 ] = 16, 

210 imgsz: Annotated[ 

211 int, 

212 Arg(help="Target training image size in pixels."), 

213 ] = 1280, 

214 early_stop: Annotated[ 

215 int, 

216 Arg( 

217 help="Stop after this many epochs without validation improvement; 0 disables early stopping." 

218 ), 

219 ] = 50, 

220 min_size: Annotated[ 

221 int, 

222 Arg( 

223 help="Skip images or crops with either dimension below this many pixels; 0 disables the size threshold." 

224 ), 

225 ] = 0, 

226 learning_rate: Annotated[ 

227 float, 

228 Arg(help="Initial learning rate."), 

229 ] = 0.01, 

230 weight_decay: Annotated[ 

231 float, 

232 Arg(help="Weight decay used for regularization."), 

233 ] = 0.0005, 

234 dropout: Annotated[ 

235 float, 

236 Arg(help="Dropout probability for the classification head."), 

237 ] = 0.0, 

238 erasing: Annotated[ 

239 float, 

240 Arg(help="Probability of random erasing augmentation."), 

241 ] = 0.4, 

242 auto_augment: Annotated[ 

243 str, 

244 Arg( 

245 help="Automatic augmentation policy: randaugment, autoaugment, or augmix. Skipped for TIFF and non-RGB datasets." 

246 ), 

247 ] = "randaugment", 

248 fliplr: Annotated[ 

249 float, 

250 Arg(help="Probability of horizontally flipping an image."), 

251 ] = 0.5, 

252 flipud: Annotated[ 

253 float, 

254 Arg(help="Probability of vertically flipping an image."), 

255 ] = 0.0, 

256 hsv_h: Annotated[ 

257 float, 

258 Arg( 

259 help="Hue augmentation amount as a fraction; skipped for TIFF and non-RGB datasets." 

260 ), 

261 ] = 0.015, 

262 hsv_s: Annotated[ 

263 float, 

264 Arg( 

265 help="Saturation augmentation amount as a fraction; skipped for TIFF and non-RGB datasets." 

266 ), 

267 ] = 0.7, 

268 hsv_v: Annotated[ 

269 float, 

270 Arg( 

271 help="Brightness augmentation amount as a fraction; skipped for TIFF and non-RGB datasets." 

272 ), 

273 ] = 0.4, 

274 cls_pw: Annotated[ 

275 float, 

276 Arg( 

277 help="Class-imbalance weighting power; 0 disables weighting, 1 uses inverse class frequency." 

278 ), 

279 ] = 0.0, 

280 freeze: Annotated[ 

281 int | None, 

282 Arg(help="Freeze the first N model layers during training."), 

283 ] = None, 

284 wandb: Annotated[ 

285 bool, Arg(help="Log training metrics to Weights & Biases.") 

286 ] = False, 

287 ): 

288 """Train this YOLO image classifier.""" 

289 return run_training_command( 

290 self, 

291 inputs, 

292 self._train, 

293 keep_log=keep_log, 

294 output=output, 

295 validation=validation, 

296 exclude=exclude, 

297 prepare_inputs=self.prepare_training_inputs, 

298 model=model, 

299 epochs=epochs, 

300 batch=batch, 

301 imgsz=imgsz, 

302 early_stop=early_stop, 

303 min_size=min_size, 

304 learning_rate=learning_rate, 

305 weight_decay=weight_decay, 

306 dropout=dropout, 

307 erasing=erasing, 

308 auto_augment=auto_augment, 

309 fliplr=fliplr, 

310 flipud=flipud, 

311 hsv_h=hsv_h, 

312 hsv_s=hsv_s, 

313 hsv_v=hsv_v, 

314 cls_pw=cls_pw, 

315 freeze=freeze, 

316 wandb=wandb, 

317 ) 

318 

319 def _train(self, *images: Image, **kwargs) -> ClassifyMetrics | None: 

320 YOLO = get_yolo_class() 

321 

322 if kwargs.get("model"): 

323 self.model = kwargs["model"] 

324 self._init_model() 

325 log = kwargs.get("log", None) 

326 if log is None: 

327 raise ValueError( 

328 "Log directory must be specified in kwargs with key 'log'." 

329 ) 

330 log = kwargs["base_folder"] / log 

331 log.mkdir(parents=True, exist_ok=True) 

332 print(f"Training files will be saved to: {log}") 

333 # The pipeline's outputs, in its order. Only without them are the classes 

334 # found from the images. 

335 classes = list(dict.fromkeys(kwargs.pop("classes", None) or self._outputs())) 

336 classes = classes or sorted({img.name for img in images}) 

337 if not isinstance(self.model, YOLO): 

338 raise ValueError("Model must be a YOLO instance for training.") 

339 

340 print(f"Training with model: {self.model.model_name}") 

341 

342 validation = kwargs.get("validation", "") 

343 exclude = kwargs.get("exclude", "") 

344 train_dir, val_dir = self._prepare_assets( 

345 classes, 

346 log, 

347 validation, 

348 exclude, 

349 *images, 

350 min_size=int(kwargs.get("min_size", 0)), 

351 ) 

352 return self._train_fold(train_dir, val_dir, classes, log, kwargs) 

353 

354 def _train_fold( 

355 self, 

356 train: list[str] | Path, 

357 val: list[str] | Path, 

358 classes: list[str], 

359 log: Path, 

360 kwargs: dict, 

361 fold_count: int | None = None, 

362 ) -> ClassifyMetrics: 

363 YOLO = get_yolo_class() 

364 

365 if not isinstance(self.model, YOLO): 

366 raise ValueError("Expected model to be a YOLO instance for training.") 

367 _, tensor_loader = _classification_channels(train, val) 

368 kwargs["config_file"] = self._prepare_yolo_config(log, classes, train, val) 

369 kwargs["log"] = f"{log.name}" 

370 if fold_count: 

371 kwargs["log"] += f"_fold_{fold_count}" 

372 params = self._prepare_params(**kwargs) 

373 if tensor_loader: 

374 from .yolo_multichannel import MultichannelClassificationTrainer 

375 

376 params["trainer"] = MultichannelClassificationTrainer 

377 with ( 

378 change_dir(kwargs["base_folder"]), 

379 self._wandb_logging(kwargs.get("wandb", False)), 

380 ): 

381 results = self.model.train(**params) 

382 if results is None: 

383 raise Exception("[red]Training failed, no results returned.[/red]") 

384 self._reload() 

385 return results 

386 

387 def _prepare_assets( 

388 self, 

389 classes: list[str], 

390 log: Path, 

391 validation_flag: str, 

392 exclude_flag: str, 

393 *images: Image, 

394 min_size: int = 0, 

395 ) -> tuple[Path, Path]: 

396 """Prepare assets for YOLO classification training. 

397 

398 Creates directory structure: log/train/{class}/ and log/val/{class}/ 

399 

400 Args: 

401 classes: List of class names. 

402 log: Path to store the assets for training. 

403 validation_flag: The value of the validation flag to identify validation images. 

404 exclude_flag: The value of the exclude flag to identify images to be excluded. 

405 *images: Image instances to be prepared. 

406 

407 Returns: 

408 Tuple of (train_dir, val_dir) paths. 

409 """ 

410 train_dir = log / "train" 

411 val_dir = log / "val" 

412 

413 if min_size < 0: 

414 raise ValueError("min_size cannot be negative") 

415 

416 folders = dict(zip(classes, class_folder_names(classes))) 

417 for folder in folders.values(): 

418 (train_dir / folder).mkdir(parents=True, exist_ok=True) 

419 (val_dir / folder).mkdir(parents=True, exist_ok=True) 

420 

421 source_images: dict[Path, PillowImage.Image] = {} 

422 for img in images: 

423 if exclude_flag and img.partition == exclude_flag: 

424 continue 

425 

426 cls_name = img.name 

427 if cls_name not in classes: 

428 continue 

429 

430 if img.partition == validation_flag: 

431 target_dir = val_dir / folders[cls_name] 

432 else: 

433 target_dir = train_dir / folders[cls_name] 

434 

435 target = img.resolve() if type(img) is Link else img 

436 src = target.get_path() 

437 dst = target_dir / src.name 

438 pixel_box = None 

439 if isinstance(target, ImageCrop): 

440 dst = target_dir / f"{src.stem}-{img.id}{src.suffix}" 

441 left, upper, right, bottom = target.coordinates() 

442 pixel_box = (left, upper, right, bottom) 

443 width = right - left 

444 height = bottom - upper 

445 elif min_size: 

446 width = int(target.width) 

447 height = int(target.height) 

448 

449 if type(img) is Link: 

450 dst = target_dir / f"{src.stem}-{img.id}{src.suffix}" 

451 

452 empty_crop = isinstance(target, ImageCrop) and (width <= 0 or height <= 0) 

453 below_minimum = min_size and (width < min_size or height < min_size) 

454 if empty_crop or below_minimum: 

455 effective_minimum = min_size or 1 

456 parent_id = img.parent_id if type(img) is Link else "" 

457 logger.warning( 

458 "Skipping classifier image %s%s from %s: image is %dx%d " 

459 "pixels (minimum %d)%s", 

460 img.id, 

461 f" -> {parent_id}" if parent_id else "", 

462 img.source_file or src, 

463 width, 

464 height, 

465 effective_minimum, 

466 f", pixel_box={pixel_box}" if pixel_box else "", 

467 ) 

468 continue 

469 

470 if not dst.exists(): 

471 if isinstance(target, ImageCrop) and src.suffix.lower() in { 

472 ".tif", 

473 ".tiff", 

474 }: 

475 import numpy as np 

476 import tifffile 

477 from .torchvision import _target_tiff_pixels 

478 

479 pixels = _target_tiff_pixels(target) 

480 tifffile.imwrite( 

481 dst, 

482 np.ascontiguousarray(pixels.transpose(2, 0, 1)), 

483 photometric="minisblack", 

484 metadata={"axes": "CYX"}, 

485 ) 

486 elif isinstance(target, ImageCrop): 

487 source_path = src.resolve() 

488 if source_path not in source_images: 

489 source_images[source_path] = open_oriented(source_path) 

490 with source_images[source_path].crop(pixel_box) as cropped: 

491 rotated = cropped.rotate( 

492 target.orientation.to_degree(), expand=True 

493 ) 

494 try: 

495 rotated.save(dst) 

496 finally: 

497 rotated.close() 

498 else: 

499 shutil.copy(src, dst) 

500 

501 for source in source_images.values(): 

502 source.close() 

503 

504 return train_dir, val_dir 

505 

506 def _prepare_yolo_config( 

507 self, 

508 log: Path, 

509 classes: list[str], 

510 train: list[str] | Path, 

511 val: list[str] | Path, 

512 ) -> Path: 

513 """For classification, data param is the parent directory containing train/ and val/. 

514 

515 Also prints distribution info. 

516 """ 

517 self._check_distribution(log, classes) 

518 return log 

519 

520 def _check_distribution( 

521 self, 

522 log: Path, 

523 metadata: dict | list[str], 

524 ) -> None: 

525 classes = ( 

526 metadata 

527 if isinstance(metadata, list) 

528 else list(metadata.get("classes", [])) 

529 ) 

530 train_dir = log / "train" 

531 val_dir = log / "val" 

532 

533 train_counts = {} 

534 validation_counts = {} 

535 for cls_name, folder in zip(classes, class_folder_names(classes)): 

536 train_counts[cls_name] = sum( 

537 1 

538 for ext in Image.file_extensions() 

539 for _ in (train_dir / folder).glob(f"*{ext}") 

540 ) 

541 validation_counts[cls_name] = sum( 

542 1 

543 for ext in Image.file_extensions() 

544 for _ in (val_dir / folder).glob(f"*{ext}") 

545 ) 

546 print_distribution_table( 

547 "Classification Distribution", classes, train_counts, validation_counts 

548 ) 

549 

550 def _prepare_params(self, **kwargs) -> dict: 

551 import platform 

552 

553 import torch 

554 

555 params = { 

556 "name": kwargs["log"], 

557 "data": kwargs["config_file"], 

558 "project": kwargs["project"], 

559 "device": ( 

560 "mps" 

561 if platform.system() == "Darwin" 

562 else "cuda" if torch.cuda.is_available() else "cpu" 

563 ), 

564 "epochs": kwargs.get("epochs", 100), 

565 "imgsz": kwargs.get("imgsz", 640), 

566 "patience": kwargs.get("early_stop", 50), 

567 "batch": kwargs.get("batch", 16), 

568 "lr0": kwargs.get("learning_rate", 0.01), 

569 "weight_decay": kwargs.get("weight_decay", 0.0005), 

570 "dropout": kwargs.get("dropout", 0.0), 

571 "erasing": kwargs.get("erasing", 0.4), 

572 "auto_augment": kwargs.get("auto_augment", "randaugment"), 

573 "fliplr": kwargs.get("fliplr", 0.5), 

574 "flipud": kwargs.get("flipud", 0.0), 

575 "hsv_h": kwargs.get("hsv_h", 0.015), 

576 "hsv_s": kwargs.get("hsv_s", 0.7), 

577 "hsv_v": kwargs.get("hsv_v", 0.4), 

578 "cls_pw": kwargs.get("cls_pw", 0.0), 

579 } 

580 if kwargs.get("freeze") is not None: 

581 params["freeze"] = kwargs["freeze"] 

582 return params