From 9f4c44245798f2c47857285c90dcab014190851a Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 23 Nov 2026 15:36:02 +1000 Subject: [PATCH] fix: replace DSI_refine drange with dmin and ignore NaN planes DSI_refine compared drange with plane indices and returned a plane index, so a DSI that did not start at disparity 0 gave wrong values or an IndexError. It also used argmax, which returns the first NaN, so a pixel with a good peak and some NaN planes came out NaN. dmin is the disparity of the first plane; the default 0 keeps the result of DSI_refine(DSI). stereo_BM and stereo_SGBM annotations now include int, which they already accepted. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/ImageMultiview.py | 78 ++++++++++------- tests/test_image_multiview.py | 99 ++++++++++++++++------ 2 files changed, 117 insertions(+), 60 deletions(-) diff --git a/src/machinevisiontoolbox/ImageMultiview.py b/src/machinevisiontoolbox/ImageMultiview.py index 1698f65e..d2a04e31 100644 --- a/src/machinevisiontoolbox/ImageMultiview.py +++ b/src/machinevisiontoolbox/ImageMultiview.py @@ -193,21 +193,33 @@ def window_stack(image, hw): return self.__class__(disparity, dtype=np.float32), self.__class__(maxima), dsi @classmethod - def DSI_refine( - cls, DSI: np.ndarray, drange: tuple[int, int] | None = None - ) -> tuple[Self, Self]: + def DSI_refine(cls, DSI: np.ndarray, dmin: int = 0) -> tuple[Self, Self]: """ Refine disparity from disparity space image :param DSI: disparity space image :type DSI: ndarray(H,W,D) - :param drange: disparity range, defaults to span of DSI values - :type drange: array_like(2), optional - :return: refined disparity image - :rtype: :class:`Image` + :param dmin: disparity of the first plane of the DSI, defaults to 0 + :type dmin: int, optional + :return: refined disparity image and the curvature at the peak + :rtype: 2-tuple of :class:`Image` Performs subpixel interpolation on the peaks in the DSI to provide disparity - estimates to a fraction of a pixel. + estimates to a fraction of a pixel. A parabola is fitted to the peak and + the two values either side of it, and the position of the parabola's peak + is the refined disparity. + + Each plane of the DSI is a disparity, and the first plane is the first + element of the ``drange`` passed to :meth:`stereo_simple`. The DSI does + not record this, so by default the returned disparities are relative to + it: 0 is the first plane, 1 is the second, and so on, and a fraction + gives the position between planes. Pass ``dmin`` equal to ``drange[0]`` + to turn them into true disparity values. + + The result is NaN where there is no valid peak: where the best disparity + is the first or last plane, so one neighbour is missing, where a + neighbour is NaN, or where every plane is NaN. Planes that are NaN are + never chosen as the peak. Example: @@ -216,41 +228,43 @@ def DSI_refine( rocks_l = Image.Read("rocks2-l.png", reduce=2) rocks_r = Image.Read("rocks2-r.png", reduce=2) disparity, similarity, DSI = rocks_l.stereo_simple(rocks_r, hw=3, drange=[40, 90]) - disparity = Image.DSI_refine(DSI) + disparity, curvature = Image.DSI_refine(DSI, dmin=40) + .. versionchanged:: 2.5.0 + The ``drange`` argument is replaced by ``dmin``. ``drange`` was + compared with plane indices, not disparities, which made it unusable + unless the first disparity was 0. A DSI plane that is NaN no longer + gives a NaN result for a pixel that has a valid peak. :references: - |RVC3|, Section 14.4.1. :seealso: :meth:`stereo_simple` """ - DSI_flat = DSI.reshape((-1, DSI.shape[2])) - - yp: list[float] = [] - y: list[float] = [] - yn: list[float] = [] - - disparity = np.argmax(DSI, axis=2) - if drange is None: - drange = (int(disparity.min()), int(disparity.max())) - for i, d in enumerate(disparity.ravel()): - if drange[0] < d < drange[1]: - yp.append(DSI_flat[i, d - 1]) - y.append(DSI_flat[i, d]) - yn.append(DSI_flat[i, d + 1]) - else: - yp.append(np.nan) - y.append(np.nan) - yn.append(np.nan) - - YP = np.array(yp).reshape(DSI.shape[:2]) - Y = np.array(y).reshape(DSI.shape[:2]) - YN = np.array(yn).reshape(DSI.shape[:2]) + invalid = np.isnan(DSI) + # best plane, never a NaN one (argmax would return the first NaN) + peak = np.argmax(np.where(invalid, -np.inf, DSI), axis=2) + + # the peak needs a plane either side of it + nplanes = DSI.shape[2] + interior = (peak > 0) & (peak < nplanes - 1) & ~invalid.all(axis=2) + + # values at the peak and either side, wherever the peak is not interior + # use the peak itself, and the result is masked out below + def plane(offset: int) -> np.ndarray: + index = np.where(interior, peak + offset, peak) + return np.take_along_axis(DSI, index[:, :, np.newaxis], axis=2)[:, :, 0] + + YP, Y, YN = plane(-1), plane(0), plane(1) A = YP + YN - 2 * Y B = YN - YP - d_subpix = disparity - B / (2 * A) + # a flat peak (A == 0) has no parabola + ok = interior & (A != 0) + d_subpix = np.full(peak.shape, np.nan) + d_subpix[ok] = peak[ok] - B[ok] / (2 * A[ok]) + dmin + A = np.where(interior, A, np.nan) return cls(d_subpix), cls(A) diff --git a/tests/test_image_multiview.py b/tests/test_image_multiview.py index 2a81952c..11c2704c 100644 --- a/tests/test_image_multiview.py +++ b/tests/test_image_multiview.py @@ -151,36 +151,79 @@ def test_zero_minimum_agrees_with_a_larger_one(self, pair): nt.assert_array_equal(a.array[10:30, 30:80], b.array[10:30, 30:80]) +def parabolic_dsi(peaks, nplanes=8): + """A DSI whose fibre at each pixel is a parabola with its peak at ``peaks``.""" + peaks = np.asarray(peaks, dtype=np.float32) + planes = np.arange(nplanes, dtype=np.float32) + return -((planes[np.newaxis, np.newaxis, :] - peaks[:, :, np.newaxis]) ** 2) + + class TestDSIRefine: - def test_parabola_gives_subpixel_peak(self): - # every fibre is an exact parabola peaking at 3.3, so the - # three-point fit must recover 3.3 - k = np.arange(7) - dsi = np.tile(-((k - 3.3) ** 2), (4, 5, 1)) - refined, curvature = Image.DSI_refine(dsi, drange=(0, 6)) - assert refined.shape == (4, 5) - nt.assert_allclose(refined.A, 3.3) - # second difference of -(x^2) is -2 - nt.assert_allclose(curvature.A, -2.0) - - def test_default_range_is_the_span_of_the_peaks(self): - # the peak is at index 3 everywhere, so the default range is (3, 3) - # and no pixel is strictly inside it: all NaN - k = np.arange(7) - dsi = np.tile(-((k - 3.3) ** 2), (2, 2, 1)) + def test_recovers_the_subpixel_peak(self): + peaks = np.array([[2.0, 2.25, 3.5], [4.75, 5.5, 1.1]]) + refined, curvature = Image.DSI_refine(parabolic_dsi(peaks)) + assert refined.array.shape == (2, 3) + nt.assert_allclose(refined.array, peaks, atol=1e-4) + # for -(x - p)^2 the second difference is -2 + nt.assert_allclose(curvature.array, -2, atol=1e-4) + + def test_dmin_gives_true_disparities(self): + peaks = np.array([[2.0, 2.25, 3.5], [4.75, 5.5, 1.1]]) + refined, _ = Image.DSI_refine(parabolic_dsi(peaks), dmin=4) + nt.assert_allclose(refined.array, peaks + 4, atol=1e-4) + + def test_peak_in_the_first_or_last_plane_is_nan(self): + refined, curvature = Image.DSI_refine(parabolic_dsi([[0.0, 7.0, 3.0]])) + assert np.isnan(refined.array[0, :2]).all() + assert np.isnan(curvature.array[0, :2]).all() + assert refined.array[0, 2] == pytest.approx(3.0, abs=1e-4) + + def test_nan_planes_are_not_chosen_as_the_peak(self): + # the peak is at 2.4, but the planes from 5 on are NaN (disparities that + # reach beyond the image edge). argmax returns the first NaN. + dsi = parabolic_dsi([[2.4]]) + dsi[:, :, 5:] = np.nan refined, _ = Image.DSI_refine(dsi) - assert np.isnan(refined.A).all() - - def test_peaks_at_the_ends_are_nan(self): - k = np.arange(7) - dsi = np.zeros((1, 3, 7)) - dsi[0, 0] = -((k - 0.2) ** 2) # peak at 0, no neighbour below - dsi[0, 1] = -((k - 3.3) ** 2) # interior peak - dsi[0, 2] = -((k - 5.9) ** 2) # peak at 6, no neighbour above - refined, _ = Image.DSI_refine(dsi, drange=(0, 6)) - assert np.isnan(refined.A[0, 0]) - assert np.isnan(refined.A[0, 2]) - nt.assert_allclose(refined.A[0, 1], 3.3) + assert refined.array[0, 0] == pytest.approx(2.4, abs=1e-4) + + def test_every_plane_nan_is_nan(self): + dsi = parabolic_dsi([[3.0, 3.0]]) + dsi[:, 1, :] = np.nan + refined, curvature = Image.DSI_refine(dsi) + assert refined.array[0, 0] == pytest.approx(3.0, abs=1e-4) + assert np.isnan(refined.array[0, 1]) and np.isnan(curvature.array[0, 1]) + + def test_nan_neighbour_is_nan_without_a_warning(self): + import warnings + + dsi = parabolic_dsi([[2.0]]) + dsi[:, :, 3] = np.nan + with warnings.catch_warnings(): + warnings.simplefilter("error") + refined, _ = Image.DSI_refine(dsi) + assert np.isnan(refined.array[0, 0]) + + def test_flat_peak_is_nan_without_a_warning(self): + import warnings + + dsi = np.zeros((1, 1, 5), dtype=np.float32) + with warnings.catch_warnings(): + warnings.simplefilter("error") + refined, _ = Image.DSI_refine(dsi) + assert np.isnan(refined.array[0, 0]) + + def test_refines_the_dsi_of_stereo_simple(self, pair): + # the pair has a true disparity of 8 and the DSI starts at disparity 4: the + # old drange handling raised IndexError here + left, right = pair + _, _, dsi = left.stereo_simple(right, hw=2, drange=[4, 12]) + relative, _ = Image.DSI_refine(dsi) + true, _ = Image.DSI_refine(dsi, dmin=4) + window = (slice(10, 30), slice(30, 80)) + # the neighbours of a random texture match are not symmetric, so the + # parabola peak is within a fifth of a pixel of the true value + nt.assert_allclose(relative.array[window], DISPARITY - 4, atol=0.2) + nt.assert_allclose(true.array[window], DISPARITY, atol=0.2) @pytest.mark.parametrize("method", ["stereo_BM", "stereo_SGBM"])