Implementation snapshot supporting the published lesson. Only cited line ranges are included; this is not a runnable source file. Configuration and recorded examples describe this project snapshot.
… uncited lines omitted …44 def composite(self, image, mask, rng=random):45 if mask.shape != image.shape[:2]:46 raise ValueError("Image and foreground mask dimensions must match")47 height, width = image.shape[:2]48 background = self.read(rng.choice(self.paths))49 scale = max(width / background.shape[1], height / background.shape[0])50 scale *= rng.uniform(1.0, 1.3)51 resized = cv2.resize(52 background,53 (max(width, int(np.ceil(background.shape[1] * scale))),54 max(height, int(np.ceil(background.shape[0] * scale)))),55 )56 x = rng.randint(0, resized.shape[1] - width)57 y = rng.randint(0, resized.shape[0] - height)58 canvas = resized[y:y + height, x:x + width].copy()59 if rng.random() < 0.5:60 canvas = canvas[:, ::-1].copy()61 canvas[mask > 0] = image[mask > 0]62 return canvas636465class BackgroundYOLODataset(YOLODataset):66 def __init__(self, *args, dataset_root, background_dir,67 background_probability=0.85, epoch_repeats=1, **kwargs):68 self.dataset_root = Path(dataset_root).resolve()69 self.background_probability = float(background_probability)70 self.epoch_repeats = int(epoch_repeats)71 if self.epoch_repeats < 1:72 raise ValueError("epoch_repeats must be at least 1")73 self.background_replacer = BackgroundReplacer(background_dir)74 super().__init__(*args, **kwargs)75 self.mask_paths = {}76 for image in self.im_files:77 # Preserve the dataset-side path. ``resolve()`` would follow the78 # exporter's space-saving image symlink back into the capture tree.79 relative = Path(image).absolute().relative_to(self.dataset_root / "images")80 mask = self.dataset_root / "masks" / relative.with_suffix(".png")81 if not mask.is_file():82 raise ValueError(f"Foreground mask missing: {mask}")83 self.mask_paths[image] = mask8485 def __len__(self):86 """Draw each source repeatedly without materializing augmented images.8788 A small capture set otherwise produces only a few optimizer steps per89 epoch. Repeating indices here retains the old materialized-dataset90 training volume while every read can receive a newly sampled background.91 """92 return len(self.im_files) * self.epoch_repeats9394 def get_image_and_label(self, index):95 index %= len(self.im_files)96 label = super().get_image_and_label(index)97 if self.augment and random.random() < self.background_probability:98 mask = cv2.imread(str(self.mask_paths[label["im_file"]]), cv2.IMREAD_GRAYSCALE)99 if mask is None or mask.shape != label["ori_shape"]:100 raise ValueError(f"Invalid foreground mask for {label['im_file']}")101 height, width = label["img"].shape[:2]102 mask = cv2.resize(mask, (width, height), interpolation=cv2.INTER_NEAREST)103 label["img"] = self.background_replacer.composite(label["img"], mask)104 return label