← Back to the animated process

scripts/augment_centerpose_backgrounds.py

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 …
98    """BiRefNet inference matching objectSegmentation/remove_background.py."""99100    def __init__(self, project, device="auto", size=1024):101        import torch102        from PIL import Image103        from torchvision import transforms104        project = Path(project).resolve()105        sys.path.insert(0, str(project / "BiRefNet"))106        from models.birefnet import BiRefNet107        if device == "auto":108            device = "cuda" if torch.cuda.is_available() else "cpu"109        if device == "cuda" and not torch.cuda.is_available():110            raise ValueError("CUDA is unavailable; use --device cpu")111        self.torch = torch112        self.Image = Image113        self.device = device114        self.size = size115        torch.set_num_threads(min(8, torch.get_num_threads()))116        self.model = BiRefNet.from_pretrained(117            str(project / "models/birefnet"), bb_pretrained=False, strict=True)118        self.model.eval().requires_grad_(False).to(device)119        self.transform = transforms.Compose([120            transforms.Resize((size, size)),121            transforms.ToTensor(),122            transforms.Normalize([0.485, 0.456, 0.406],123                                 [0.229, 0.224, 0.225]),124        ])125126    def _predict_image(self, image):127        rgb = self.Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))128        inputs = self.transform(rgb).unsqueeze(0).to(self.device)129        context = (self.torch.autocast("cuda", dtype=self.torch.float16)130                   if self.device == "cuda" else nullcontext())131        with self.torch.inference_mode(), context:132            prediction = self.model(inputs)[-1].sigmoid().float()133        prediction = self.torch.nn.functional.interpolate(134            prediction, size=image.shape[:2], mode="bilinear", align_corners=False135        )[0, 0].cpu().numpy()136        if not np.isfinite(prediction).all():137            raise ValueError("BiRefNet returned non-finite foreground probabilities")138        return prediction139140    def predict(self, image):141        return self._predict_image(image)142143    def predict_crop(self, image, label, margin_ratio=0.6):144        """Run BiRefNet on a pose-guided crop and restore full-frame coordinates."""145        height, width = image.shape[:2]146        box = expected_bbox(label)147        margin = int(round(max(box[2] - box[0], box[3] - box[1]) * margin_ratio))148        x0, y0 = np.floor(box[:2]).astype(int) - margin149        x1, y1 = np.ceil(box[2:]).astype(int) + margin150        x0, y0 = max(0, x0), max(0, y0)151        x1, y1 = min(width, x1), min(height, y1)152        if x1 <= x0 or y1 <= y0:153            raise ValueError("Projected pose box produced an empty BiRefNet crop")154        probability = np.zeros((height, width), np.float32)155        probability[y0:y1, x0:x1] = self._predict_image(image[y0:y1, x0:x1])156        return probability… uncited lines omitted …
177def mask_metrics(mask, label):178    ys, xs = np.where(mask > 0)179    if not len(xs):180        raise ValueError("Empty refined foreground mask")181    mask_box = np.asarray([xs.min(), ys.min(), xs.max() + 1, ys.max() + 1], dtype=np.float64)182    label_box = expected_bbox(label)183    overlap_size = np.maximum(0.0, np.minimum(mask_box[2:], label_box[2:])184                              - np.maximum(mask_box[:2], label_box[:2]))185    intersection = float(np.prod(overlap_size))186    union = (float(np.prod(mask_box[2:] - mask_box[:2]))187             + float(np.prod(label_box[2:] - label_box[:2])) - intersection)188    height, width = mask.shape189    x0, y0 = np.floor(label_box[:2]).astype(int)190    x1, y1 = np.ceil(label_box[2:]).astype(int)191    x0, y0, x1, y1 = max(0, x0), max(0, y0), min(width, x1), min(height, y1)192    within = np.zeros_like(mask, dtype=bool)193    within[y0:y1, x0:x1] = True194    foreground = mask > 0195    center = np.rint(label["center_uv_px"]).astype(int)196    center_inside = (0 <= center[0] < width and 0 <= center[1] < height197                     and bool(foreground[center[1], center[0]]))198    return {199        "mask_area_px": int(np.count_nonzero(foreground)),200        "mask_bbox_xyxy_px": mask_box.astype(int).tolist(),201        "projected_bbox_xyxy_px": label_box.tolist(),202        "bbox_iou": intersection / union if union else 0.0,203        "foreground_inside_projected_bbox": float(204            np.count_nonzero(foreground & within) / np.count_nonzero(foreground)),205        "object_center_inside_mask": center_inside,206    }207208209def inpaint_exclusion_mask(image, raw_image, minimum_area=20):210    """Recover the regions changed by AprilTag inpainting for mask subtraction."""211    if raw_image is None or raw_image.shape != image.shape:212        raise ValueError("Raw and inpainted images must have matching dimensions")213    changed = (np.max(cv2.absdiff(image, raw_image), axis=2) > 2).astype(np.uint8)214    changed = cv2.morphologyEx(changed, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))215    count, components, stats, _ = cv2.connectedComponentsWithStats(changed)216    result = np.zeros(image.shape[:2], np.uint8)217    for component in range(1, count):218        if stats[component, cv2.CC_STAT_AREA] < minimum_area:219            continue220        region = (components == component).astype(np.uint8) * 255221        contours, _ = cv2.findContours(region, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)222        cv2.drawContours(result, contours, -1, 255, cv2.FILLED)223    return cv2.dilate(result, np.ones((3, 3), np.uint8))224225226def bright_neutral_disconnect_mask(image):227    """Break connections through pale surfaces or white fiducial paper."""228    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)229    return ((hsv[:, :, 1] < 65) & (hsv[:, :, 2] > 90)).astype(np.uint8) * 255230231232def pose_refine_mask(raw_mask, label, kernel_size=11, padding_ratio=0.03,233                     exclusion_mask=None, disconnect_mask=None):234    """Use the calibrated cuboid to isolate the rigid object and break cables."""235    if raw_mask.ndim != 2 or not np.any(raw_mask):236        raise ValueError("BiRefNet produced an empty foreground mask")237    height, width = raw_mask.shape238    box = expected_bbox(label)239    padding = max(2, int(round(max(box[2] - box[0], box[3] - box[1]) * padding_ratio)))240    x0, y0 = np.floor(box[:2]).astype(int) - padding241    x1, y1 = np.ceil(box[2:]).astype(int) + padding242    x0, y0, x1, y1 = max(0, x0), max(0, y0), min(width, x1), min(height, y1)243    candidate = np.zeros_like(raw_mask)244    candidate[y0:y1, x0:x1] = raw_mask[y0:y1, x0:x1]245    if exclusion_mask is not None:246        if exclusion_mask.shape != raw_mask.shape:247            raise ValueError("Exclusion mask dimensions do not match BiRefNet mask")248        candidate[exclusion_mask > 0] = 0249    if disconnect_mask is not None:250        if disconnect_mask.shape != raw_mask.shape:251            raise ValueError("Disconnect mask dimensions do not match BiRefNet mask")252        candidate[disconnect_mask > 0] = 0253254    kernel_size = max(3, int(kernel_size) | 1)255    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))256    opened = cv2.morphologyEx(candidate, cv2.MORPH_OPEN, kernel)257    count, components, stats, _ = cv2.connectedComponentsWithStats(opened)258    if count < 2:259        raise ValueError("No foreground component remains inside projected 3D box")260    center = np.rint(label["center_uv_px"]).astype(int)261    selected = 0262    if 0 <= center[0] < width and 0 <= center[1] < height:263        selected = int(components[center[1], center[0]])264    if selected == 0:265        selected = int(1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]))266    component = (components == selected).astype(np.uint8) * 255267    contours, _ = cv2.findContours(component, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)268    if not contours:269        raise ValueError("Selected pose-box foreground has no external contour")270    result = np.zeros_like(raw_mask)271    cv2.drawContours(result, [max(contours, key=cv2.contourArea)], -1, 255, cv2.FILLED)272    # Filling the external contour can paint a previously excluded inpainted273    # fiducial back into a concavity. Apply the exact capture-time exclusion a274    # second time so no tag-derived pixels reach a synthetic background.275    if exclusion_mask is not None:276        result[exclusion_mask > 0] = 0277    return result278279280def refine_probability(probability, label, threshold, min_threshold, exclusion_mask=None,281                       disconnect_mask=None):282    thresholds = np.arange(threshold, min_threshold - 1e-9, -0.1)283    last_error = None284    for selected_threshold in thresholds:285        raw_mask = (probability >= selected_threshold).astype(np.uint8) * 255286        try:287            mask = pose_refine_mask(raw_mask, label, exclusion_mask=exclusion_mask,288                                    disconnect_mask=disconnect_mask)289            break290        except ValueError as error:291            last_error = error292    else:293        raise ValueError(str(last_error))294    return raw_mask, mask, selected_threshold295296297def refine_mask(image, label, predictor, threshold=0.5, min_threshold=0.2,298                exclusion_mask=None):299    disconnect_mask = bright_neutral_disconnect_mask(image)300    crop_available = hasattr(predictor, "predict_crop")301    inference = "pose_guided_crop" if crop_available else "full_frame"302    probability = (predictor.predict_crop(image, label) if crop_available303                   else predictor.predict(image))304    try:305        raw_mask, mask, selected_threshold = refine_probability(306            probability, label, threshold, min_threshold, exclusion_mask,307            disconnect_mask)308    except ValueError as primary_error:309        if not crop_available:310            raise ValueError(311                f"No usable BiRefNet mask at thresholds {threshold:g} to "312                f"{min_threshold:g}: {primary_error}") from primary_error313        inference = "full_frame_fallback"314        probability = predictor.predict(image)315        try:316            raw_mask, mask, selected_threshold = refine_probability(317                probability, label, threshold, min_threshold, exclusion_mask,318                disconnect_mask)319        except ValueError as fallback_error:320            raise ValueError(321                f"No usable pose-guided crop or full-frame BiRefNet mask at "322                f"thresholds {threshold:g} to {min_threshold:g}: {fallback_error}"323            ) from fallback_error324    metrics = mask_metrics(mask, label)325    metrics.update(birefnet_threshold=float(selected_threshold),326                   birefnet_probability_max=float(probability.max()),327                   birefnet_inference=inference)328    warnings = []329    if metrics["foreground_inside_projected_bbox"] < 0.95:330        warnings.append("foreground extends substantially outside projected 3D box")331    if metrics["bbox_iou"] < 0.2:332        warnings.append("mask bbox and projected 3D bbox have low overlap")333    if not metrics["object_center_inside_mask"]:334        warnings.append("projected object center is outside mask")335    metrics["warnings"] = warnings336    return raw_mask, mask, metrics… uncited lines omitted …
410        for index, (image_path, centerpose_path, rich_path) in enumerate(sources, 1):411            image = cv2.imread(str(image_path))412            if image is None:413                raise ValueError(f"Cannot read {image_path}")414            label = json.loads(rich_path.read_text())415            raw_path = dataset / label.get("raw_image", f"raw_images/{image_path.name}")416            raw_image = cv2.imread(str(raw_path))417            if raw_image is None:418                raise ValueError(f"Cannot read raw pre-inpainting image: {raw_path}")419            exclusion = inpaint_exclusion_mask(image, raw_image)420            raw_mask, mask, metrics = refine_mask(421                image, label, predictor, args.threshold, args.min_threshold, exclusion)422            if metrics["warnings"] and not args.allow_warnings:423                raise ValueError(f"Mask validation failed for {image_path.name}: "424                                 + "; ".join(metrics["warnings"]))425            stem = image_path.stem426            write_image(stage / "raw_masks" / f"{stem}.png", raw_mask)427            write_image(stage / "masks" / f"{stem}.png", mask)428            if args.write_cutouts:429                write_image(stage / "cutouts" / f"{stem}.png", np.dstack([image, mask]))430            preview_path = stage / "previews" / f"{stem}.jpg"431            write_image(preview_path, preview_image(image, mask, label, metrics))… uncited lines omitted …
503    parser.add_argument("--dataset", type=Path, default=ROOT / "datasets/my_object")504    parser.add_argument("--output", type=Path,505                        default=ROOT / "datasets/my_object/centerpose_augmented")506    parser.add_argument("--segmentation-project", type=Path,507                        default=DEFAULT_SEGMENTATION_PROJECT)508    parser.add_argument("--backgrounds", type=Path,509                        default=DEFAULT_SEGMENTATION_PROJECT / "backgrounds/picsum")510    parser.add_argument("--augmentations-per-image", type=int, default=0,511                        help="Legacy materialized composites per image; default 0 because YOLO samples backgrounds on the fly")512    parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")513    parser.add_argument("--inference-size", type=int, default=1024)514    parser.add_argument("--threshold", type=float, default=0.5,515                        help="Initial BiRefNet threshold (default: 0.5)")516    parser.add_argument("--min-threshold", type=float, default=0.2,517                        help="Lowest adaptive threshold for pose-box recovery (default: 0.2)")518    parser.add_argument("--seed", type=int, default=42)519    parser.add_argument("--allow-warnings", action="store_true",520                        help="Keep masks that fail geometric review checks")521    parser.add_argument("--write-cutouts", action="store_true",