File size: 3,374 Bytes
1d21e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Spatial cross-validation of automatic correspondences, not anatomical ground truth."""
import cv2
import numpy as np
from .mesh import fit_mesh, basis


def fit_geometry(reference_points, moving_points, shape, ransac_threshold=4):
    if len(reference_points) < 24:
        raise ValueError('At least 24 verified correspondences are needed for geometry fitting.')
    matrix, inliers = cv2.findHomography(moving_points, reference_points, cv2.USAC_MAGSAC, ransac_threshold)
    if matrix is None or inliers is None or not np.isfinite(matrix).all() or inliers.sum() < 12 or inliers.mean() < .3:
        raise ValueError('Correspondences do not support stable geometry.')
    h,w=shape
    corners=np.float32([[0,0],[w,0],[w,h],[0,h]])
    denominator=(matrix @ np.c_[corners,np.ones(4)].T)[2]
    projected=cv2.perspectiveTransform(corners[None],matrix)[0]
    if np.any(denominator<=0) or not .5<cv2.contourArea(projected,oriented=True)/(h*w)<2:
        raise ValueError('Unstable or reflected geometry was rejected.')
    coverage=cv2.contourArea(cv2.convexHull(reference_points[inliers.ravel().astype(bool)]))/(h*w)
    if coverage<.08:
        raise ValueError('Correspondences cover too little of the iris crop.')
    coefficients=fit_mesh(reference_points,moving_points,matrix,shape)
    return matrix,coefficients,inliers,coverage


def predict_points(points,matrix,coefficients,shape):
    base=cv2.perspectiveTransform(points[None],np.linalg.inv(matrix))[0]
    return base+basis(points,shape,coefficients.shape[0]) @ coefficients.reshape(-1,2)


def evaluate_correspondences(reference_points,moving_points,shape):
    result=dict(kind='automatic_spatial_cross_validation',count=len(reference_points),scored_count=0,
                failed_folds=[],within_px_percent=None,median_px=None,p95_px=None,
                description='Consistency against patch-verified automatic correspondences held out of each geometric fit. Not independently verified accuracy. Unscored points count as outside each tolerance.')
    if len(reference_points)<60:
        result['reason']='Too few verified correspondences for five-fold evaluation (minimum 60).'
        return result
    # Distributed 150px cells at the benchmark resolution; fixed before evaluation.
    cell=max(shape)/2200*150
    folds=((reference_points[:,0]//cell+reference_points[:,1]//cell).astype(int)%5)
    errors=np.full(len(reference_points),np.inf)
    for fold in range(5):
        test=folds==fold;train=~test
        if test.sum()<6 or train.sum()<24:
            result['failed_folds'].append(fold);continue
        try:
            matrix,coef,_,_=fit_geometry(reference_points[train],moving_points[train],shape)
            predicted=predict_points(reference_points[test],matrix,coef,shape)
            errors[test]=np.linalg.norm(predicted-moving_points[test],axis=1)
        except (ValueError,cv2.error,np.linalg.LinAlgError):
            result['failed_folds'].append(fold)
    finite=np.isfinite(errors);result['scored_count']=int(finite.sum())
    result['within_px_percent']={str(t):round(float((errors<=t).mean()*100),2) for t in [1,2,3,5]}
    if finite.all():
        result.update(median_px=float(np.median(errors)),p95_px=float(np.percentile(errors,95)))
    else:
        result['reason']='One or more folds could not be evaluated; no complete tail-error estimate.'
    return result