File size: 4,496 Bytes
790d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""Checks for the photo-guided boundary alpha. No GPU, no models, no network.

The property that matters is not "the alpha looks nice" but "the alpha refines
the transition without moving the region". A filter that quietly grew or shrank
a surface would be far worse than the staircase it replaces.
"""

from __future__ import annotations

import pathlib
import sys

import cv2
import numpy as np

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))

from services.pipeline.mask_alpha import (  # noqa: E402
    DEFAULT_BAND_RADIUS,
    attach_mask_alpha,
    soft_mask_alpha,
)

failures: list[str] = []


def check(label: str, condition: bool, detail: str = "") -> None:
    if condition:
        print(f"  PASS  {label}")
    else:
        failures.append(label)
        print(f"  FAIL  {label}" + (f"  ({detail})" if detail else ""))


def scene(height: int = 240, width: int = 320) -> tuple[np.ndarray, np.ndarray]:
    """A photo with one strong horizontal edge, and a mask displaced from it."""
    photo = np.zeros((height, width, 3), np.uint8)
    photo[: height // 2] = 200          # bright wall
    photo[height // 2 :] = 70           # dark floor
    photo = cv2.GaussianBlur(photo, (0, 0), 1.0)

    truth = np.zeros((height, width), np.uint8)
    truth[height // 2 :] = 1
    displaced = np.zeros_like(truth)
    displaced[height // 2 + 3 :] = 1    # segmentation sits 3px inside the floor
    return photo, displaced


def main() -> int:
    photo, mask = scene()
    height, width = mask.shape
    alpha = soft_mask_alpha(mask, photo)

    print("\nShape and range")
    check("alpha has the mask's shape", alpha.shape == mask.shape)
    check("alpha is uint8", alpha.dtype == np.uint8, str(alpha.dtype))
    check("alpha carries partial coverage",
          ((alpha > 0) & (alpha < 255)).any(),
          "a binary result means the filter did nothing")
    check("interior stays fully opaque", alpha[-1, :].min() == 255)
    check("exterior stays fully transparent", alpha[0, :].max() == 0)

    print("\nThe region is not moved")
    kernel = np.ones((2 * DEFAULT_BAND_RADIUS + 1,) * 2, np.uint8)
    band = (cv2.dilate(mask, kernel) - cv2.erode(mask, kernel)).astype(bool)
    outside = ~band
    check("outside the band alpha equals the original mask",
          np.array_equal(alpha[outside], mask[outside] * 255),
          "the filter may refine the transition, never the selection")
    check("the band is a small fraction of the frame",
          band.mean() < 0.35, f"band covers {100 * band.mean():.1f}%")

    print("\nThe boundary moves toward the photograph's edge")
    # Column-wise centre of the transition, versus the real edge at height/2.
    profile = alpha.mean(axis=1) / 255.0
    soft_edge_row = float(np.argmin(np.abs(profile - 0.5)))
    hard_edge_row = float(height // 2 + 3)
    true_edge_row = float(height // 2)
    check("soft boundary is closer to the real edge than the hard one",
          abs(soft_edge_row - true_edge_row) < abs(hard_edge_row - true_edge_row),
          f"soft at {soft_edge_row}, hard at {hard_edge_row}, true at {true_edge_row}")

    print("\nDegenerate inputs")
    check("an empty mask returns all zeros",
          soft_mask_alpha(np.zeros_like(mask), photo).max() == 0)
    check("a full mask returns all 255",
          soft_mask_alpha(np.ones_like(mask), photo).min() == 255)
    small = np.zeros((8, 8), np.uint8); small[4:] = 1
    check("a tiny mask does not raise",
          soft_mask_alpha(small, np.zeros((8, 8, 3), np.uint8)).shape == (8, 8))

    print("\nSegment attachment")
    import base64
    indices = np.flatnonzero(mask.ravel()).astype(np.uint32)
    segments = [{"id": 0, "mask": base64.b64encode(indices.tobytes()).decode()}]
    attached = attach_mask_alpha(segments, photo, width, height)
    check("one segment received an alpha", attached == 1)
    check("the alpha is a full frame plane",
          segments[0]["maskAlpha"].shape == (width * height,),
          str(segments[0]["maskAlpha"].shape))
    check("a segment with no mask is skipped",
          attach_mask_alpha([{"id": 1}], photo, width, height) == 0)
    check("a corrupt mask does not fail the conversion",
          attach_mask_alpha([{"id": 2, "mask": "!!!not base64!!!"}], photo, width, height) == 0)

    print()
    if failures:
        print(f"{len(failures)} FAILED: {', '.join(failures)}")
        return 1
    print("All checks passed.")
    return 0


if __name__ == "__main__":
    sys.exit(main())