Prevent match_template from returning NaNs.

This commit is contained in:
Tony S Yu
2012-03-26 22:27:42 -04:00
parent 0c1e3541b3
commit ad99285bc0
2 changed files with 20 additions and 5 deletions
+5 -5
View File
@@ -119,11 +119,11 @@ def match_template(np.ndarray[float, ndim=2, mode="c"] image,
window_sum = integrate(image_sat, i, j, i_end, j_end)
window_mean_sqr = window_sum * window_sum * inv_area
window_sqr_sum = integrate(image_sqr_sat, i, j, i_end, j_end)
den = sqrt((window_sqr_sum - window_mean_sqr) * template_ssd)
if den == 0:
if window_sqr_sum <= window_mean_sqr:
corr[i, j] = 0
else:
corr[i, j] /= den
continue
den = sqrt((window_sqr_sum - window_mean_sqr) * template_ssd)
corr[i, j] /= den
return corr
+15
View File
@@ -70,6 +70,21 @@ def test_normalization():
assert np.allclose(result.flat[iflat_max], 1)
def test_no_nans():
"""Test that `match_template` doesn't return NaN values.
When image values are only slightly different, floating-point errors can
cause a subtraction inside of a square root to go negative (without an
explicit check that was added to `match_template`).
"""
np.random.seed(1)
image = 10000 + np.random.normal(size=(20, 20))
template = np.ones((6, 6))
template[:3, :] = 0
result = match_template(image, template)
assert not np.any(np.isnan(result))
def test_switched_arguments():
image = np.ones((5, 5))
template = np.ones((3, 3))