File size: 5,453 Bytes
6ca097e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Conservative circle hypotheses for centered crops; uncertain boundaries fail closed.

This is an interpretable detector, not a trained eyelid/eyelash segmentation model.
Native masks exclude boundary margins and saturated reflections. Inspect overlays
before using its pupil geometry as a deformation prior.
"""
from dataclasses import asdict, dataclass
import cv2
import numpy as np
from .preprocessing import glare_mask, iris_mask


@dataclass(frozen=True)
class IrisGeometry:
    center: tuple[float, float]
    pupil_radius: float
    iris_radius: float
    boundary_support: float
    limbus_detected: bool = True

    def to_dict(self):
        return asdict(self)


def detect_geometry(image):
    h, w = image.shape[:2]
    scale = min(1., 600 / max(h, w))
    # Red-channel contrast separates blue pupil reflections from iris tissue better
    # than luminance on these visible-light crops. This is an analysis copy only.
    gray = cv2.resize(image, (round(w*scale), round(h*scale)))[:, :, 2]
    gray = cv2.GaussianBlur(gray, (7, 7), 1.5)
    sh, sw = gray.shape
    size = min(sh, sw)
    yy, xx = np.indices(gray.shape)
    central = np.hypot(xx-sw/2, yy-sh/2) < size*.22
    candidates = []
    # Search several levels: a fixed darkness threshold is unreliable across exposures.
    for percentile in (5, 8, 12, 15, 25, 35, 45):
        threshold = np.percentile(gray[central], percentile)
        binary = (gray <= threshold).astype(np.uint8)
        binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
        contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for contour in contours:
            area = cv2.contourArea(contour)
            if not np.pi*(size*.065)**2 < area < np.pi*(size*.24)**2:
                continue
            (cx, cy), radius = cv2.minEnclosingCircle(contour)
            circularity = area / max(np.pi*radius**2, 1)
            offset = np.hypot(cx-sw/2, cy-sh/2)/size
            if circularity > .78 and offset < .18:
                candidates.append((circularity-offset, cx, cy, np.sqrt(area/np.pi)))
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, size*.15, param1=40, param2=20,
                               minRadius=round(size*.065), maxRadius=round(size*.20))
    if circles is not None:
        angles = np.linspace(0, 2*np.pi, 180, endpoint=False)
        for cx, cy, radius in circles[0]:
            offset = np.hypot(cx-sw/2, cy-sh/2)/size
            if offset > .18:
                continue
            def sample(r):
                return cv2.remap(gray.astype(np.float32), (cx+np.cos(angles)*r).astype(np.float32),
                                 (cy+np.sin(angles)*r).astype(np.float32), cv2.INTER_LINEAR).ravel()
            contrast = sample(radius*1.15)-sample(radius*.8)
            boundary_support = float((contrast > 10).mean())
            if boundary_support > .7:
                candidates.append((boundary_support-offset, float(cx), float(cy), float(radius)))
    if not candidates:
        return None
    _, cx, cy, pupil = max(candidates)
    # Pupil-only detection is useful even when the outer boundary is occluded.
    # Explicitly report the assumed conservative outer radius; never use it as
    # a measured limbus for radial-model evaluation.
    fallback = IrisGeometry((float(cx/scale), float(cy/scale)), float(pupil/scale), min(h,w)*.4, 0., False)
    angles = np.linspace(0, 2*np.pi, 180, endpoint=False)
    radii = np.arange(max(pupil*1.7, size*.29), size*.49, .5)
    if len(radii) < 20:
        return fallback
    mx = (cx+np.cos(angles[:, None])*radii).astype(np.float32)
    my = (cy+np.sin(angles[:, None])*radii).astype(np.float32)
    profile = cv2.remap(gray.astype(np.float32), mx, my, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
    # Limbus transitions toward brighter sclera; both contrast and angular support matter.
    gradient = cv2.GaussianBlur(profile, (11, 1), 2)[:, 8:] - cv2.GaussianBlur(profile, (11, 1), 2)[:, :-8]
    peaks = gradient.argmax(axis=1)
    strength = gradient[np.arange(len(angles)), peaks]
    boundaries = radii[peaks+4]
    valid = strength > 12
    if valid.sum() < 90:
        return fallback
    outer = float(np.median(boundaries[valid]))
    support = float((valid & (np.abs(boundaries-outer) < size*.035)).mean())
    if support < .60 or not 1.8 < outer/pupil < 6:
        return fallback
    return IrisGeometry((float(cx/scale), float(cy/scale)), float(pupil/scale), outer/scale, support)


def adaptive_mask(image, geometry=None):
    geometry = detect_geometry(image) if geometry is None else geometry
    if geometry is None:
        return iris_mask(image) & ~glare_mask(image), None
    y, x = np.indices(image.shape[:2], dtype=np.float32)
    radius = np.hypot(x-geometry.center[0], y-geometry.center[1])
    margin = min(image.shape[:2])*.015
    mask = (radius > geometry.pupil_radius+margin) & (radius < geometry.iris_radius-margin)
    return mask & ~glare_mask(image), geometry


def geometry_overlay(image, geometry):
    out = image.copy()
    if geometry is not None:
        center = tuple(round(v) for v in geometry.center)
        for radius, detected in ((geometry.pupil_radius, True), (geometry.iris_radius, geometry.limbus_detected)):
            color = (0, 255, 0) if detected else (0, 165, 255)
            cv2.circle(out, center, round(radius), color, max(2, image.shape[0]//400))
    return out