diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 6b5d06f2..565bf536 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -672,7 +672,6 @@ def distance(self, other: "BaseFeature2D", metric: str = "L2") -> np.ndarray: else: d = np.linalg.norm(des1[i, :] - des2[j, :], ord=metric_dict[metric]) D[i, j] = d - D[j, i] = d return D def match( diff --git a/tests/test_image_point_features_extra.py b/tests/test_image_point_features_extra.py index 8f5bbf83..cc32d4a0 100644 --- a/tests/test_image_point_features_extra.py +++ b/tests/test_image_point_features_extra.py @@ -318,15 +318,35 @@ def test_needs_descriptors(self): with pytest.raises(ValueError, match="no descriptors"): make_features(descriptors=False).distance(make_features()) - @pytest.mark.xfail( - strict=True, - raises=IndexError, - reason="distance() also writes D[j, i], which is out of range unless " - "both feature sets are the same size", - ) - def test_different_sizes(self): - D = make_features(3).distance(make_features(4)) - assert D.shape == (3, 4) + @staticmethod + def by_hand(a, b, ord): + """Distance from every descriptor of a to every descriptor of b.""" + return np.array([[np.linalg.norm(x - y, ord=ord) for y in b] for x in a]) + + @pytest.mark.parametrize("sizes", [(3, 3), (3, 4), (4, 2), (1, 3), (3, 1)]) + @pytest.mark.parametrize("metric, ord", [("L1", 1), ("L2", 2)]) + def test_every_pair_of_different_sets(self, sizes, metric, ord): + # different descriptors in each set, so the matrix is not symmetric and + # D[i, j] must be the distance from a[i] to b[j] + rng = np.random.default_rng(0) + a = make_features(sizes[0]) + b = make_features(sizes[1]) + a._descriptor = rng.normal(size=(sizes[0], 5)).astype(np.float32) + b._descriptor = rng.normal(size=(sizes[1], 5)).astype(np.float32) + D = a.distance(b, metric) + assert D.shape == sizes + nt.assert_allclose( + D, self.by_hand(a._descriptor, b._descriptor, ord), rtol=1e-5 + ) + + def test_ncc_of_different_sets(self): + rng = np.random.default_rng(1) + a, b = make_features(3), make_features(4) + a._descriptor = rng.normal(size=(3, 5)).astype(np.float32) + b._descriptor = rng.normal(size=(4, 5)).astype(np.float32) + nt.assert_allclose( + a.distance(b, "ncc"), a._descriptor @ b._descriptor.T, rtol=1e-5 + ) class TestMatchNeedsDescriptors: