Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 46 additions & 32 deletions src/machinevisiontoolbox/ImageMultiview.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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)

Expand Down
99 changes: 71 additions & 28 deletions tests/test_image_multiview.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
Loading