Spaces:
Paused
Paused
File size: 5,509 Bytes
b5af7d6 1d21e88 b5af7d6 1d21e88 b5af7d6 f65c627 | 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 | """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
def common_evaluation(a, b, anchors_a, anchors_b, shape, geometry=None):
"""Same automatic target points for every candidate; never fit those locations.
A 32px exclusion neighborhood also removes overlapping validation patches.
These labels remain automatic, not anatomical ground truth.
"""
errors = np.full(len(anchors_a), np.inf)
cell = max(shape)/2200*150
folds = lambda p: ((p[:, 0]//cell+p[:, 1]//cell).astype(int)%5)
if len(anchors_a) >= 60:
for fold in range(5):
test = folds(anchors_a)==fold
train = folds(a)!=fold
if test.sum() < 6:
continue
# Chunk distances to bound memory for dense feature sets.
heldout = anchors_a[test]
for start in range(0, len(a), 256):
near = np.linalg.norm(a[start:start+256, None]-heldout[None], axis=2).min(axis=1) < 32
train[start:start+256] &= ~near
try:
if geometry is None:
matrix, coef, _, _ = fit_geometry(a[train], b[train], shape)
prediction = predict_points(heldout, matrix, coef, shape)
else:
from .radial import fit_radial_mesh
prediction = fit_radial_mesh(a[train], b[train], shape, geometry).predict(heldout)
errors[test] = np.linalg.norm(prediction-anchors_b[test], axis=1)
except (ValueError, cv2.error, np.linalg.LinAlgError):
pass
return dict(count=len(errors), scored_count=int(np.isfinite(errors).sum()),
median_px=float(np.median(errors)) if np.isfinite(errors).all() and len(errors) else None,
p95_px=float(np.percentile(errors, 95)) if np.isfinite(errors).all() and len(errors) else None,
within_px_percent={str(t): round(float((errors<=t).mean()*100), 2) if len(errors) else None for t in (1, 2, 3, 5)},
description='Fixed baseline automatic correspondences; five spatial folds with 32px training exclusion. Not anatomical ground truth. Unscored points count as failures.')
|