Coverage for collectra/tasks/object_detection/yolo.py: 79.47%
302 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1from __future__ import annotations
3import shutil
4import tempfile
5from collections import Counter
6from pathlib import Path
7from typing import Annotated, TYPE_CHECKING
9from pydantic import Field
11from cappa import Arg
13from collectra.cli import command
14from .adaptation_commands import YOLOAdaptationCommands
15from .base import (
16 Batch,
17 Epochs,
18 LearningRate,
19 ObjectDetector,
20 RunResolution,
21 Threshold,
22 TrainResolution,
23 WeightDecay,
24)
25from collectra.types.images import (
26 Image,
27 ImageCrop,
28 convert_image_to_rgb,
29 image_channel_count,
30 read_tiff_channels,
31)
32from collectra.types.texts import Text
33from collectra.utils import change_dir
35from collectra.utils import threading_locked
36from ..machine_learning.training import (
37 prepare_object_detection_inputs,
38 print_distribution_table,
39 run_training_command,
40)
41from ..machine_learning.yolo import YOLOTask, get_yolo_class
43if TYPE_CHECKING:
44 from ultralytics.engine.results import Results
45 from ultralytics.models import YOLO
46 from ultralytics.utils.metrics import ClassifyMetrics, DetMetrics
48__all__ = ["ObjectDetectorYOLO", "ObjectDetectionYOLO"]
51class DetectionResult:
52 metrics: dict
53 best_result: DetMetrics
55 def __init__(self, result: DetMetrics) -> None:
56 self.best_result = result
57 self.metrics = result.results_dict if result else {}
59 @staticmethod
60 def get_best_result(
61 results: list["DetectionResult"], metric: str = "metrics/mAP50-95(B)"
62 ) -> DetMetrics:
63 best_result: DetMetrics | None = None
64 best_metric_result = 0.0
65 for result in results:
66 if result is None:
67 continue
68 metric_result = result.metrics.get(metric, 0.0)
69 if best_result is None:
70 best_metric_result = metric_result
71 best_result = result.best_result
72 continue
73 if metric_result > best_metric_result:
74 best_metric_result = metric_result
75 best_result = result.best_result
76 if best_result is None:
77 raise ValueError("No valid results found to determine the best result.")
78 return best_result
81class ObjectDetectorYOLO(YOLOAdaptationCommands, YOLOTask, ObjectDetector):
82 singletons: bool = False
83 batch_size: int = Field(default=1, ge=1)
84 # Ultralytics' own defaults, where they differ from the shared ones.
85 batch: int = Field(default=16, ge=1)
86 learning_rate: float = Field(default=0.01, gt=0)
87 weight_decay: float = Field(default=0.0005, ge=0)
88 # Overlap above which two boxes of one class count as the same object.
89 iou: float = Field(default=0.7, gt=0, le=1)
91 RENAMED_SETTINGS = {**ObjectDetector.RENAMED_SETTINGS, "lr0": "learning_rate"}
93 @command(name="run")
94 def cli_run(
95 self,
96 inputs: list[str],
97 output: Path | None = None,
98 verbose: bool = False,
99 usage: bool = False,
100 render: bool = False,
101 model: Annotated[
102 Path | None,
103 Arg(help="Model checkpoint path. Omit to keep the configured model."),
104 ] = None,
105 resolution: RunResolution = None,
106 threshold: Threshold = None,
107 imgsz: Annotated[int | None, Arg(help="Deprecated: use --resolution.")] = None,
108 batch_size: Annotated[
109 int,
110 Arg(
111 help="Number of files to run through the model at once; results are saved after each batch."
112 ),
113 ] = 16,
114 force: Annotated[
115 bool,
116 Arg(
117 help="Rerun tasks whose outputs already exist, replacing those outputs. By default such tasks are skipped."
118 ),
119 ] = False,
120 ) -> None:
121 """Run this object detector for the supplied input files."""
122 if batch_size < 1:
123 raise ValueError("--batch-size must be at least 1")
124 if model is not None:
125 self.model = model
126 resolution = self._current_name("imgsz", "resolution", imgsz, resolution)
127 if resolution is not None:
128 self.resolution = resolution
129 if threshold is not None:
130 self.threshold = threshold
131 self.batch_size = batch_size
132 super().cli_run(
133 inputs,
134 output=output,
135 verbose=verbose,
136 usage=usage,
137 render=render,
138 force=force,
139 )
141 @threading_locked()
142 def run(
143 self,
144 *args: Image,
145 model: str | Path | None = None,
146 resolution: int | None = None,
147 imgsz: int | None = None,
148 **kwargs,
149 ) -> list[ImageCrop]:
150 """Run object detection inference on the provided Image.
152 This method performs object detection on the provided input image
153 using the trained YOLO model.
155 Results include bounding boxes, confidence scores, and class
156 predictions for each detected object.
158 Args:
159 input (Image): The input image on which to perform object detection.
160 model: Optional checkpoint path overriding the task's configured model.
161 resolution: Optional image size in pixels. Defaults to the size chosen
162 for the task, or the model's own setting when none was chosen.
163 imgsz: Deprecated name for ``resolution``.
165 Returns:
166 list[ImageCrop]: A list of ImageCrop objects representing the detected
167 objects in the input image.
168 """
169 if len(args) != 1:
170 raise ValueError("This task only supports a single Image input.")
171 if not isinstance(args[0], Image):
172 raise TypeError("Input must be an instance of Image.")
173 image: Image = args[0]
174 if model is not None:
175 self.model = model
176 self._init_model()
177 from torchvision.ops import batched_nms
179 resolution = self._current_name("imgsz", "resolution", imgsz, resolution)
180 if resolution is None:
181 resolution = self.inference_resolution
182 results: Results | None = (
183 self._take_prefetched(image)
184 if resolution == self.inference_resolution
185 else None
186 )
187 if results is None:
188 results = self._predict([image], resolution)[0]
190 if getattr(self.model.model, "end2end", False) and len(results.boxes):
191 keep = batched_nms(
192 results.boxes.xyxy,
193 results.boxes.conf,
194 results.boxes.cls,
195 iou_threshold=self.iou,
196 )
197 results = results[keep]
199 detections: list[ImageCrop] = []
201 if results.boxes is None or len(results.boxes) == 0:
202 return detections
204 coordinates = results.boxes.xywhn.clone()
205 names = [
206 results.names[class_name.int().item()] for class_name in results.boxes.cls
207 ]
209 counts = Counter()
210 if len(names) == 0:
211 # No objects detected, return empty list
212 return detections
213 for index in range(len(coordinates)):
214 name = names[index]
216 if self.singletons and counts[name]:
217 continue
219 x, y, w, h = coordinates[index]
220 confidence = results.boxes.conf[index]
222 image_crop = image.make_crop(
223 x_center=float(x),
224 y_center=float(y),
225 width_relative=float(w),
226 height_relative=float(h),
227 confidence=confidence.item(),
228 orientation=image.orientation,
229 name=name,
230 )
231 counts[name] += 1
232 detections.append(image_crop)
234 print(f"Found {len(detections)} objects in the image:")
235 for name, count in counts.items():
236 print(f"\t{name}: {count}")
237 return self._orient_crops(detections)
239 def _tiff_pixels(self, image: Image):
240 """Decode a TIFF (cropped and rotated as needed) for the model's channels."""
241 import numpy as np
242 import torch
244 pixels = read_tiff_channels(image.get_path())
245 if isinstance(image, ImageCrop):
246 left, top, right, bottom = image.coordinates()
247 if right <= left or bottom <= top:
248 raise ValueError(f"ImageCrop {image.id!r} produces an empty pixel crop")
249 pixels = pixels[top:bottom, left:right, :]
250 pixels = np.rot90(pixels, k=image.orientation.to_degree() // 90)
251 first_conv = next(
252 layer
253 for layer in self.model.model.modules()
254 if isinstance(layer, torch.nn.Conv2d)
255 )
256 expected_channels = first_conv.in_channels
257 model_config = getattr(self.model.model, "yaml", {})
258 if "feature_fusion" in model_config:
259 expected_channels = model_config["channels"]
260 if pixels.shape[2] != expected_channels:
261 raise ValueError(
262 f"{image.get_path()}: {pixels.shape[2]} image channels, "
263 f"but the detection model expects {expected_channels}"
264 )
265 # Ultralytics expects BGR for three-channel arrays, but preserves
266 # channel order for multispectral arrays. Keep its usual resizing,
267 # normalization, and box scaling relative to the original image.
268 if pixels.shape[2] == 3:
269 pixels = pixels[..., ::-1]
270 return np.ascontiguousarray(pixels)
272 def _predict(self, images: list[Image], imgsz: int | None) -> list[Results]:
273 """Run the model over ``images`` together, returning one result each."""
274 inference_kwargs = {"iou": self.iou, "conf": self.threshold}
275 if imgsz is not None:
276 inference_kwargs["imgsz"] = imgsz
278 # Ultralytics takes a list of one source type at a time.
279 arrays: dict[int, object] = {}
280 paths: dict[int, Path] = {}
281 with tempfile.TemporaryDirectory() as temp_dir:
282 for index, image in enumerate(images):
283 if image.get_path().suffix.lower() in {".tif", ".tiff"}:
284 arrays[index] = self._tiff_pixels(image)
285 elif isinstance(image, ImageCrop):
286 img_path = (
287 Path(temp_dir) / f"{index}-{Path(image.get_path()).stem}.png"
288 )
289 image.pil().save(img_path, format="PNG")
290 paths[index] = img_path
291 else:
292 paths[index] = image.get_path()
294 results: list[Results | None] = [None] * len(images)
295 for sources in (arrays, paths):
296 if not sources:
297 continue
298 indices = list(sources)
299 call_kwargs = dict(inference_kwargs)
300 if len(indices) > 1:
301 call_kwargs["batch"] = len(indices)
302 predicted = self.model([sources[i] for i in indices], **call_kwargs)
303 for index, result in zip(indices, predicted):
304 results[index] = result
305 return results
307 def _predict_batch(self, images: list[Image]) -> list[Results]:
308 return self._predict(images, self.inference_resolution)
310 @command
311 def train(
312 self,
313 inputs: Annotated[
314 list[str],
315 Arg(
316 help="Pipeline data files or directories containing training annotations."
317 ),
318 ],
319 model: Annotated[
320 str,
321 Arg(
322 help="YOLO weights name or checkpoint path (for example yolo26n.pt), or a model YAML file. Omit to keep the configured model."
323 ),
324 ] = "",
325 output: Annotated[
326 Path | None,
327 Arg(help="Directory for training logs, dataset files, and checkpoints."),
328 ] = None,
329 keep_log: Annotated[
330 bool,
331 Arg(
332 help="Keep the training directory after saving the model to the pipeline."
333 ),
334 ] = True,
335 validation: Annotated[
336 str,
337 Arg(help="Partition value identifying validation examples."),
338 ] = "",
339 exclude: Annotated[
340 str,
341 Arg(help="Partition value identifying examples to exclude from training."),
342 ] = "",
343 epochs: Epochs = None,
344 batch: Batch = None,
345 resolution: TrainResolution = None,
346 early_stop: Annotated[
347 int,
348 Arg(
349 help="Stop after this many epochs without validation improvement; 0 disables early stopping."
350 ),
351 ] = 50,
352 preview: Annotated[
353 bool,
354 Arg(
355 help="Preview the prepared training images and annotations before training."
356 ),
357 ] = False,
358 rgb: Annotated[
359 bool,
360 Arg(
361 help="Convert all prepared training images to 3-channel RGB, so images with differing channel counts (grayscale, RGBA) can be trained together."
362 ),
363 ] = False,
364 workers: Annotated[
365 int,
366 Arg(help="Number of data-loading workers per distributed process."),
367 ] = 8,
368 pretrained: Annotated[
369 bool,
370 Arg(help="Use pretrained weights when supported by the selected model."),
371 ] = True,
372 optimizer: Annotated[
373 str,
374 Arg(
375 help="Optimizer: auto, SGD, MuSGD, Adam, Adamax, AdamW, NAdam, RAdam, or RMSProp."
376 ),
377 ] = "auto",
378 seed: Annotated[
379 int,
380 Arg(help="Random seed for training."),
381 ] = 0,
382 deterministic: Annotated[
383 bool,
384 Arg(
385 help="Use deterministic operations for reproducibility; may reduce speed."
386 ),
387 ] = True,
388 single_cls: Annotated[
389 bool,
390 Arg(help="Treat all object classes as one class."),
391 ] = False,
392 rect: Annotated[
393 bool,
394 Arg(help="Use rectangular training batches to reduce padding."),
395 ] = False,
396 cos_lr: Annotated[
397 bool,
398 Arg(help="Use a cosine learning-rate schedule."),
399 ] = False,
400 close_mosaic: Annotated[
401 int,
402 Arg(
403 help="Disable mosaic augmentation for the final N epochs; 0 keeps it enabled."
404 ),
405 ] = 10,
406 amp: Annotated[
407 bool,
408 Arg(help="Enable automatic mixed precision training."),
409 ] = True,
410 fraction: Annotated[
411 float,
412 Arg(help="Fraction of the training dataset to use; 1.0 uses all examples."),
413 ] = 1.0,
414 freeze: Annotated[
415 int | None,
416 Arg(help="Freeze the first N model layers during training."),
417 ] = None,
418 multi_scale: Annotated[
419 float,
420 Arg(
421 help="Vary image size by this fraction of the resolution; 0 disables multi-scale training."
422 ),
423 ] = 0.0,
424 learning_rate: LearningRate = None,
425 lrf: Annotated[
426 float,
427 Arg(
428 help="Final learning-rate multiplier; final rate is the learning rate times lrf."
429 ),
430 ] = 0.01,
431 momentum: Annotated[
432 float,
433 Arg(help="SGD momentum or the first Adam beta coefficient."),
434 ] = 0.937,
435 weight_decay: WeightDecay = None,
436 warmup_epochs: Annotated[
437 float,
438 Arg(
439 help="Number of learning-rate warmup epochs; fractional values are allowed."
440 ),
441 ] = 3.0,
442 warmup_momentum: Annotated[
443 float,
444 Arg(help="Initial momentum during warmup."),
445 ] = 0.8,
446 warmup_bias_lr: Annotated[
447 float,
448 Arg(help="Initial learning rate for bias parameters during warmup."),
449 ] = 0.1,
450 box: Annotated[
451 float,
452 Arg(help="Weight applied to bounding-box loss."),
453 ] = 7.5,
454 cls: Annotated[
455 float,
456 Arg(help="Weight applied to classification loss."),
457 ] = 0.5,
458 cls_pw: Annotated[
459 float,
460 Arg(
461 help="Class-imbalance weighting power; 0 disables weighting, 1 uses inverse class frequency."
462 ),
463 ] = 0.0,
464 dfl: Annotated[
465 float,
466 Arg(help="Weight applied to distribution focal loss."),
467 ] = 1.5,
468 nbs: Annotated[
469 int,
470 Arg(help="Nominal batch size used for loss normalization."),
471 ] = 64,
472 hsv_h: Annotated[
473 float,
474 Arg(help="Hue augmentation amount as a fraction."),
475 ] = 0.015,
476 hsv_s: Annotated[
477 float,
478 Arg(help="Saturation augmentation amount as a fraction."),
479 ] = 0.7,
480 hsv_v: Annotated[
481 float,
482 Arg(help="Brightness augmentation amount as a fraction."),
483 ] = 0.4,
484 degrees: Annotated[
485 float,
486 Arg(help="Maximum random rotation in either direction, in degrees."),
487 ] = 0.0,
488 translate: Annotated[
489 float,
490 Arg(help="Maximum random translation as a fraction of image size."),
491 ] = 0.1,
492 scale: Annotated[
493 float,
494 Arg(help="Random scale variation around 1.0."),
495 ] = 0.5,
496 shear: Annotated[
497 float,
498 Arg(help="Maximum random shear in either direction, in degrees."),
499 ] = 0.0,
500 perspective: Annotated[
501 float,
502 Arg(help="Strength of random perspective augmentation."),
503 ] = 0.0,
504 flipud: Annotated[
505 float,
506 Arg(help="Probability of vertically flipping an image."),
507 ] = 0.0,
508 fliplr: Annotated[
509 float,
510 Arg(help="Probability of horizontally flipping an image."),
511 ] = 0.5,
512 bgr: Annotated[
513 float,
514 Arg(help="Probability of swapping RGB and BGR color channels."),
515 ] = 0.0,
516 mosaic: Annotated[
517 float,
518 Arg(help="Probability of mosaic augmentation."),
519 ] = 1.0,
520 mixup: Annotated[
521 float,
522 Arg(help="Probability of MixUp augmentation."),
523 ] = 0.0,
524 cutmix: Annotated[
525 float,
526 Arg(help="Probability of CutMix augmentation."),
527 ] = 0.0,
528 time: Annotated[
529 float,
530 Arg(
531 help="Training time limit in hours; a positive value overrides epochs, 0 leaves it unset."
532 ),
533 ] = 0.0,
534 save: Annotated[
535 bool,
536 Arg(help="Save training checkpoints."),
537 ] = True,
538 save_period: Annotated[
539 int,
540 Arg(
541 help="Save an additional checkpoint every N epochs; -1 disables periodic saves."
542 ),
543 ] = -1,
544 cache: Annotated[
545 str,
546 Arg(help="Cache images in ram or on disk; omit to leave caching disabled."),
547 ] = "",
548 device: Annotated[
549 str,
550 Arg(
551 help="Training device, such as cpu, mps, 0, or 0,1; omit for automatic selection."
552 ),
553 ] = "",
554 verbose: Annotated[
555 bool,
556 Arg(help="Print detailed training logs."),
557 ] = True,
558 resume: Annotated[
559 bool,
560 Arg(help="Resume training from the selected checkpoint."),
561 ] = False,
562 compile: Annotated[
563 str,
564 Arg(
565 help="Torch compilation mode: default, reduce-overhead, or max-autotune-no-cudagraphs; omit to disable."
566 ),
567 ] = "",
568 distill_model: Annotated[
569 str,
570 Arg(
571 help="Teacher model checkpoint for knowledge distillation; omit to disable."
572 ),
573 ] = "",
574 dis: Annotated[
575 float,
576 Arg(help="Weight applied to knowledge-distillation loss."),
577 ] = 6.0,
578 plots: Annotated[
579 bool,
580 Arg(help="Save training and validation plots and images."),
581 ] = True,
582 wandb: Annotated[
583 bool, Arg(help="Log training metrics to Weights & Biases.")
584 ] = False,
585 imgsz: Annotated[int | None, Arg(help="Deprecated: use --resolution.")] = None,
586 lr0: Annotated[
587 float | None, Arg(help="Deprecated: use --learning-rate.")
588 ] = None,
589 ):
590 """Train this YOLO object detector."""
591 resolution = self._current_name("imgsz", "resolution", imgsz, resolution)
592 learning_rate = self._current_name("lr0", "learning_rate", lr0, learning_rate)
593 settings = self._settings_for_run(
594 epochs=epochs,
595 batch=batch,
596 resolution=resolution,
597 learning_rate=learning_rate,
598 weight_decay=weight_decay,
599 )
600 return run_training_command(
601 self,
602 inputs,
603 self._train,
604 keep_log=keep_log,
605 output=output,
606 validation=validation,
607 exclude=exclude,
608 prepare_inputs=prepare_object_detection_inputs,
609 include_unlabelled=True,
610 model=model,
611 epochs=settings["epochs"],
612 batch=settings["batch"],
613 imgsz=settings["resolution"],
614 early_stop=early_stop,
615 preview=preview,
616 rgb=rgb,
617 workers=workers,
618 pretrained=pretrained,
619 optimizer=optimizer,
620 seed=seed,
621 deterministic=deterministic,
622 single_cls=single_cls,
623 rect=rect,
624 cos_lr=cos_lr,
625 close_mosaic=close_mosaic,
626 amp=amp,
627 fraction=fraction,
628 freeze=freeze,
629 multi_scale=multi_scale,
630 lr0=settings["learning_rate"],
631 lrf=lrf,
632 momentum=momentum,
633 weight_decay=settings["weight_decay"],
634 warmup_epochs=warmup_epochs,
635 warmup_momentum=warmup_momentum,
636 warmup_bias_lr=warmup_bias_lr,
637 box=box,
638 cls=cls,
639 cls_pw=cls_pw,
640 dfl=dfl,
641 nbs=nbs,
642 hsv_h=hsv_h,
643 hsv_s=hsv_s,
644 hsv_v=hsv_v,
645 degrees=degrees,
646 translate=translate,
647 scale=scale,
648 shear=shear,
649 perspective=perspective,
650 flipud=flipud,
651 fliplr=fliplr,
652 bgr=bgr,
653 mosaic=mosaic,
654 mixup=mixup,
655 cutmix=cutmix,
656 time=time,
657 save=save,
658 save_period=save_period,
659 cache=cache,
660 device=device,
661 verbose=verbose,
662 resume=resume,
663 compile=compile,
664 distill_model=distill_model,
665 dis=dis,
666 plots=plots,
667 wandb=wandb,
668 )
670 def _train(
671 self, *images: ImageCrop, **kwargs
672 ) -> DetMetrics | ClassifyMetrics | None:
673 YOLO = get_yolo_class()
675 if kwargs.get("model"):
676 self.model = kwargs["model"]
677 self._init_model()
678 log = kwargs.get("log", None)
679 if log is None:
680 raise ValueError(
681 "Log directory must be specified in kwargs with key 'log'."
682 )
683 log = kwargs["base_folder"] / log
684 log.mkdir(parents=True, exist_ok=True)
685 print(f"Training files will be saved to: {log}")
686 classes = kwargs.pop("classes", [])
688 if not isinstance(self.model, YOLO):
689 raise ValueError("Model must be a YOLO instance for training.")
691 print(f"Training with model: {self.model.model_name}")
693 validation = kwargs.get("validation", "")
694 exclude = kwargs.get("exclude", "")
695 train, val = self._prepare_assets(
696 classes, log, validation, exclude, *images, rgb=kwargs.get("rgb", False)
697 )
698 return self._train_fold(train, val, classes, log, kwargs)
700 def _train_fold(
701 self,
702 train: list[str] | Path,
703 val: list[str] | Path,
704 classes: list[str],
705 log: Path,
706 kwargs: dict,
707 fold_count: int | None = None,
708 ) -> DetMetrics | ClassifyMetrics:
709 YOLO = get_yolo_class()
711 if not isinstance(self.model, YOLO):
712 raise ValueError("Expected model to be a YOLO instance for training.")
713 kwargs["config_file"] = self._prepare_yolo_config(
714 log,
715 classes,
716 train,
717 val,
718 )
719 kwargs["log"] = f"{log.name}"
720 if fold_count:
721 kwargs["log"] += f"_fold_{fold_count}"
722 params = self._prepare_params(**kwargs)
723 if kwargs.get("preview", False):
724 self._preview_assets(log, classes)
725 with (
726 change_dir(kwargs["base_folder"]),
727 self._wandb_logging(kwargs.get("wandb", False)),
728 ):
729 results: DetMetrics | None = self.model.train(**params)
730 if results is None:
731 raise Exception("[red]Training failed, no results returned.[/red]")
732 self._reload()
733 return results
735 def _preview_assets(self, log: Path, classes: list[str]) -> None:
736 try:
737 from drawyolo.draw import draw_box_on_image_with_labels
738 except ModuleNotFoundError as error:
739 if error.name != "drawyolo":
740 raise
741 raise ImportError(
742 "YOLO previews require drawyolo. Install with: "
743 'pip install "collectra[yolo]"'
744 ) from error
746 preview_dir = log / "preview"
747 preview_dir.mkdir(exist_ok=True)
749 for image_type in Image.file_extensions():
750 for image_file in log.glob(f"*{image_type}"):
751 dest = preview_dir / image_file.name
752 shutil.copy(image_file, dest)
753 output_path = preview_dir / image_file.name
754 draw_box_on_image_with_labels(
755 image=image_file,
756 output=output_path,
757 labels=image_file.with_suffix(".txt"),
758 classes=classes,
759 )
761 def _prepare_yolo_config(
762 self,
763 log: Path,
764 classes: list[str],
765 train: list[str] | Path,
766 val: list[str] | Path,
767 ) -> Path:
769 # Inspect exactly the prepared files referenced by the generated manifests.
770 # The dataset, not the selected checkpoint, determines the model input size.
771 train = [Path(path).name for path in train]
772 val = [Path(path).name for path in val]
773 detected = {}
774 for name in dict.fromkeys([*train, *val]):
775 path = log / name
776 try:
777 detected[name] = image_channel_count(path)
778 except Exception as error:
779 raise ValueError(
780 f"Cannot determine input channels for {path}: {error}"
781 ) from error
782 if not detected:
783 raise ValueError(
784 "Cannot infer input channels: no prepared training or validation images"
785 )
786 if len(set(detected.values())) != 1:
787 details = ", ".join(
788 f"{name}: {count} channels" for name, count in detected.items()
789 )
790 raise ValueError(
791 f"Inconsistent input channel counts in prepared dataset: {details}"
792 )
793 channels = next(iter(detected.values()))
795 metadata = {
796 "classes": classes,
797 "train": train,
798 "val": val,
799 }
801 Path(log / "train.txt").write_text(
802 "\n".join([f"./{Path(p).name}" for p in train])
803 )
804 Path(log / "val.txt").write_text("\n".join([f"./{Path(p).name}" for p in val]))
806 print(
807 f"Saved {len(metadata['train'])} training images and {len(metadata['val'])} validation images to {log}"
808 )
810 self._check_distribution(log, metadata)
812 train_txt = "train.txt"
813 val_txt = "val.txt"
814 num_classes = len(metadata["classes"])
815 names = metadata["classes"]
817 config = (
818 f"train: {train_txt}\nval: {val_txt}\nnc: {num_classes}\nnames: {names}\n"
819 f"channels: {channels}\n"
820 )
821 config_file = log / "config.yml"
822 Path(config_file).write_text(config)
824 return config_file
826 def _check_distribution(
827 self,
828 log: Path,
829 metadata: dict | list[str],
830 ) -> None:
831 if not isinstance(metadata, dict):
832 return
834 train_classes = {name: 0 for name in metadata["classes"]}
835 val_classes = {name: 0 for name in metadata["classes"]}
836 # (with objects, background) image counts for train and validation
837 train_images = [0, 0]
838 val_images = [0, 0]
840 for image_type in Image.file_extensions():
841 for image_file in log.glob(f"*{image_type}"):
842 label_file = image_file.with_suffix(".txt")
843 with open(label_file, "r") as f:
844 label_lines = [
845 line.strip() for line in f.readlines() if line.strip()
846 ]
847 if image_file.name in metadata["train"]:
848 train_images[0 if label_lines else 1] += 1
849 elif image_file.name in metadata["val"]:
850 val_images[0 if label_lines else 1] += 1
851 for line in label_lines:
852 class_index = int(line.split()[0])
853 class_name = metadata["classes"][class_index]
854 if image_file.name in metadata["train"]:
855 train_classes[class_name] += 1
856 elif image_file.name in metadata["val"]:
857 val_classes[class_name] += 1
859 print_distribution_table(
860 "Class Distribution",
861 metadata["classes"],
862 train_classes,
863 val_classes,
864 train_images=tuple(train_images),
865 validation_images=tuple(val_images),
866 )
868 def _write_yolo_label(self, name_index: int, img: ImageCrop, f):
869 if name_index == -1:
870 f.write("")
871 else:
872 f.write(
873 f"{name_index} {img.x_center:.6f} {img.y_center:.6f} {img.width_relative:.6f} {img.height_relative:.6f}\n"
874 )
876 def _prepare_assets(
877 self,
878 classes: list[str],
879 log: Path,
880 validation_flag: str,
881 exclude_flag: str,
882 *images: ImageCrop,
883 rgb: bool = False,
884 ) -> tuple[list[str], list[str]] | tuple[Path, Path]:
885 """Prepare assets for YOLO training.
887 Args:
888 classes (list[str]): List of class names.
889 log (Path): Path to store the assets for training.
890 validation_flag (str): The value of the validation flag to identify validation images.
891 exclude_flag (str): The value of the exclude flag to identify images to be excluded from training.
892 images (ImageCrop): Variable number of ImageCrop instances to be prepared.
893 rgb (bool): Convert each prepared image to 3-channel RGB.
895 Returns:
896 tuple[list[list[int]], list[str], list[str]]: A tuple containing the label matrix for iterative stratification,
897 training image filenames, and validation image filenames.
899 """
900 train: list[str] = list()
901 val: list[str] = list()
902 for img in images:
903 src = img.get_path()
904 dst = log / src.name
905 if isinstance(img, ImageCrop) and img.source_parent:
906 dst = log / f"{src.stem}-{str(img.source_parent.id)}{src.suffix}"
907 if not dst.exists():
908 if hasattr(img, "source_parent") and img.source_parent is not None:
909 img.source_parent.save(dst)
910 else:
911 img.save(dst)
912 if rgb:
913 convert_image_to_rgb(dst)
914 if img.partition == validation_flag:
915 val.append(dst.name)
916 elif not exclude_flag or img.partition != exclude_flag:
917 train.append(dst.name)
918 if isinstance(img, ImageCrop) and isinstance(img.source_parent, ImageCrop):
919 img.set_rel_to_src_parent()
920 name_index = classes.index(img.name) if img.name in classes else -1
921 text_dst = log / f"{dst.stem}.txt"
922 write_mode = "a" if text_dst.exists() else "w"
923 with open(text_dst, write_mode) as f:
924 self._write_yolo_label(name_index, img, f)
925 return train, val
927 def _prepare_params(self, **kwargs) -> dict:
928 params = {
929 "name": kwargs["log"],
930 "data": kwargs["config_file"],
931 "project": kwargs["project"],
932 "device": kwargs.get("device") or self._select_device(),
933 "epochs": kwargs.get("epochs", 100),
934 "imgsz": kwargs.get("imgsz", 640),
935 "patience": kwargs.get("early_stop", 50),
936 "batch": kwargs.get("batch", 16),
937 "workers": kwargs.get("workers", 8),
938 "pretrained": kwargs.get("pretrained", True),
939 "optimizer": kwargs.get("optimizer", "auto"),
940 "seed": kwargs.get("seed", 0),
941 "deterministic": kwargs.get("deterministic", True),
942 "single_cls": kwargs.get("single_cls", False),
943 "rect": kwargs.get("rect", False),
944 "cos_lr": kwargs.get("cos_lr", False),
945 "close_mosaic": kwargs.get("close_mosaic", 10),
946 "amp": kwargs.get("amp", True),
947 "fraction": kwargs.get("fraction", 1.0),
948 "multi_scale": kwargs.get("multi_scale", 0.0),
949 "lr0": kwargs.get("lr0", 0.01),
950 "lrf": kwargs.get("lrf", 0.01),
951 "momentum": kwargs.get("momentum", 0.937),
952 "weight_decay": kwargs.get("weight_decay", 0.0005),
953 "warmup_epochs": kwargs.get("warmup_epochs", 3.0),
954 "warmup_momentum": kwargs.get("warmup_momentum", 0.8),
955 "warmup_bias_lr": kwargs.get("warmup_bias_lr", 0.1),
956 "box": kwargs.get("box", 7.5),
957 "cls": kwargs.get("cls", 0.5),
958 "cls_pw": kwargs.get("cls_pw", 0.0),
959 "dfl": kwargs.get("dfl", 1.5),
960 "nbs": kwargs.get("nbs", 64),
961 "hsv_h": kwargs.get("hsv_h", 0.015),
962 "hsv_s": kwargs.get("hsv_s", 0.7),
963 "hsv_v": kwargs.get("hsv_v", 0.4),
964 "degrees": kwargs.get("degrees", 0.0),
965 "translate": kwargs.get("translate", 0.1),
966 "scale": kwargs.get("scale", 0.5),
967 "shear": kwargs.get("shear", 0.0),
968 "perspective": kwargs.get("perspective", 0.0),
969 "flipud": kwargs.get("flipud", 0.0),
970 "fliplr": kwargs.get("fliplr", 0.5),
971 "bgr": kwargs.get("bgr", 0.0),
972 "mosaic": kwargs.get("mosaic", 1.0),
973 "mixup": kwargs.get("mixup", 0.0),
974 "cutmix": kwargs.get("cutmix", 0.0),
975 "save": kwargs.get("save", True),
976 "save_period": kwargs.get("save_period", -1),
977 "verbose": kwargs.get("verbose", True),
978 "resume": kwargs.get("resume", False),
979 "dis": kwargs.get("dis", 6.0),
980 "plots": kwargs.get("plots", True),
981 }
982 if kwargs.get("freeze") is not None:
983 params["freeze"] = kwargs["freeze"]
984 for optional in ("time", "cache", "compile", "distill_model"):
985 if kwargs.get(optional):
986 params[optional] = kwargs[optional]
987 return params
990# The former name of ObjectDetectorYOLO.
991ObjectDetectionYOLO = ObjectDetectorYOLO