diff --git a/tests/test_image_line_features_hough.py b/tests/test_image_line_features_hough.py new file mode 100644 index 00000000..a32aa80d --- /dev/null +++ b/tests/test_image_line_features_hough.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python +"""Tests for the Hough line methods of ``ImageLineFeatures``. + +The test image has one horizontal line (v = 50, 80 pixels long) and one +vertical line (u = 30, 60 pixels long), so the line parameters are known: +a horizontal line is (theta, rho) = (pi/2, 50) and a vertical one is (0, 30), +using u cos(theta) + v sin(theta) = rho. Nothing is mocked. +""" + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt +import numpy as np +import numpy.testing as nt +import pytest + +from machinevisiontoolbox import Image + + +@pytest.fixture +def lines_image(): + arr = np.zeros((100, 100), dtype=np.uint8) + arr[50, 10:90] = 255 # horizontal, 80 pixels + arr[20:80, 30] = 255 # vertical, 60 pixels + return Image(arr) + + +@pytest.fixture(autouse=True) +def close_figures(): + yield + plt.close("all") + + +def nearest(lines, theta, rho, tol_theta=0.03, tol_rho=1.5): + """True if some row of ``lines`` is within tolerance of (theta, rho).""" + return bool( + np.any( + (np.abs(lines[:, 0] - theta) < tol_theta) + & (np.abs(lines[:, 1] - rho) < tol_rho) + ) + ) + + +class TestLines: + def test_finds_both_lines(self, lines_image): + lines = lines_image.Hough().lines(minvotes=55) + assert lines.ndim == 2 and lines.shape[1] == 2 + assert nearest(lines, np.pi / 2, 50) + assert nearest(lines, 0, 30) + + def test_threshold_selects_the_stronger_line(self, lines_image): + # only the 80 pixel line has more than 70 votes + lines = lines_image.Hough().lines(minvotes=70) + assert nearest(lines, np.pi / 2, 50) + assert not nearest(lines, 0, 30) + + def test_no_lines_gives_an_empty_array(self): + empty = Image(np.zeros((50, 50), dtype=np.uint8)) + assert empty.Hough().lines(minvotes=5).shape == (0, 2) + + def test_float_image_is_converted(self, lines_image): + floating = Image(lines_image.array.astype(np.float32) / 255) + lines = floating.Hough().lines(minvotes=55) + assert nearest(lines, np.pi / 2, 50) + + def test_ntheta_sets_the_angle_step(self, lines_image): + h = lines_image.Hough(ntheta=90) + assert h.dtheta == pytest.approx(np.pi / 90) + assert nearest(h.lines(minvotes=55), np.pi / 2, 50, tol_theta=0.05) + + +class TestLinesP: + def test_segment_end_points(self, lines_image): + segs = lines_image.Hough().lines_p(minvotes=40, minlinelength=30, seed=1) + assert segs.ndim == 2 and segs.shape[1] == 4 + horizontal = segs[(segs[:, 1] == 50) & (segs[:, 3] == 50)] + assert len(horizontal) >= 1 + # the segment spans most of the 80 pixel line + assert horizontal[:, [0, 2]].min() <= 12 + assert horizontal[:, [0, 2]].max() >= 87 + + def test_seed_makes_the_result_repeatable(self, lines_image): + h = lines_image.Hough() + a = h.lines_p(minvotes=40, seed=7) + b = h.lines_p(minvotes=40, seed=7) + nt.assert_array_equal(a, b) + + def test_min_length_rejects_short_segments(self, lines_image): + segs = lines_image.Hough().lines_p(minvotes=20, minlinelength=70, seed=1) + # only the 80 pixel line is long enough + assert len(segs) >= 1 + length = np.hypot(segs[:, 2] - segs[:, 0], segs[:, 3] - segs[:, 1]) + assert (length >= 70).all() + + def test_no_segments_gives_an_empty_array(self): + empty = Image(np.zeros((50, 50), dtype=np.uint8)) + assert empty.Hough().lines_p(minvotes=5).shape == (0, 4) + + +class TestAccumulator: + @pytest.fixture + def h(self, lines_image): + h = lines_image.Hough() + h.accumulator() + return h + + def test_attributes(self, h): + assert h.A.ndim == 2 + assert len(h.extent) == 4 + # theta extent is in radians, rho extent in pixels + assert -h.dtheta <= h.extent[0] < h.extent[1] <= np.pi + h.dtheta + assert h.extent[2] < h.extent[3] + # the highest threshold with any line is the number of pixels of the + # longest line, and h.t records the last threshold that found one + assert h.t == 80 or h.t == 79 + + def test_votes_never_increase_with_the_threshold(self, h): + votes = np.array(h.votes) + assert (np.diff(votes) <= 0).all() + assert votes[-1] >= 1 + + def test_peak_is_the_longest_line(self, h): + rho_index, theta_index = np.unravel_index(np.argmax(h.A), h.A.shape) + theta_bins = np.linspace(h.extent[0], h.extent[1], h.A.shape[1] + 1) + rho_bins = np.linspace(h.extent[2], h.extent[3], h.A.shape[0] + 1) + theta = (theta_bins[theta_index] + theta_bins[theta_index + 1]) / 2 + rho = (rho_bins[rho_index] + rho_bins[rho_index + 1]) / 2 + # the accumulator counts how many thresholds each line survives, so + # the longest line is the strongest cell + assert theta == pytest.approx(np.pi / 2, abs=0.05) + assert rho == pytest.approx(50, abs=1.5) + + def test_skip_gives_a_coarser_vote_list(self, lines_image): + fine = lines_image.Hough() + fine.accumulator(skip=1) + coarse = lines_image.Hough() + coarse.accumulator(skip=10) + assert len(coarse.votes) < len(fine.votes) + + +class TestPlotting: + def test_plot_hough_lines(self, lines_image): + h = lines_image.Hough() + lines = h.lines(minvotes=55) + plt.figure() + plt.axis([0, 100, 100, 0]) + before = len(plt.gca().lines) + h.plot_lines(lines, "r") + assert len(plt.gca().lines) > before + + def test_plot_segments(self, lines_image): + h = lines_image.Hough() + segs = h.lines_p(minvotes=40, seed=1) + plt.figure() + h.plot_lines(segs, "b") + ax = plt.gca() + assert len(ax.lines) == len(segs) + nt.assert_array_equal(ax.lines[0].get_xdata(), segs[0, [0, 2]]) + nt.assert_array_equal(ax.lines[0].get_ydata(), segs[0, [1, 3]]) + + def test_plot_accumulator_computes_it_if_needed(self, lines_image): + h = lines_image.Hough() + assert h.A is None + h.plot_accumulator() + assert h.A is not None + ax = plt.gcf().axes[0] + assert len(ax.images) == 1 + assert ax.get_xlabel().startswith(r"$\theta$") + assert ax.get_ylabel().startswith(r"$\rho$") + assert ax.get_xlim() == (0, np.pi) + assert plt.gcf().canvas.manager.get_window_title() == "Hough Accumulator" + + def test_plot_accumulator_into_given_axes(self, lines_image): + h = lines_image.Hough() + fig, ax = plt.subplots() + h.plot_accumulator(ax=ax, cmap="gray") + assert len(ax.images) == 1 + assert ax.images[0].get_cmap().name == "gray" + # no default title when the axes are supplied + assert plt.gcf().canvas.manager.get_window_title() != "Hough Accumulator" + + def test_plot_accumulator_with_title(self, lines_image): + h = lines_image.Hough() + fig, ax = plt.subplots() + h.plot_accumulator(ax=ax, title="my accumulator") + assert fig.canvas.manager.get_window_title() == "my accumulator" diff --git a/tests/test_image_multiview.py b/tests/test_image_multiview.py index 276660d3..3bd72e2c 100644 --- a/tests/test_image_multiview.py +++ b/tests/test_image_multiview.py @@ -1,51 +1,172 @@ #!/usr/bin/env python +"""Tests for the stereo and rectification methods of ``ImageMultiview``. -import unittest +The stereo pairs are synthetic: the right image is the left image shifted by a +known number of pixels, so the true disparity is known exactly. Nothing is +mocked except the matches object given to ``rectify_homographies``. +""" + +from types import SimpleNamespace import numpy as np import numpy.testing as nt +import pytest from machinevisiontoolbox import Image +DISPARITY = 8 # true disparity of the synthetic pair, in pixels + + +@pytest.fixture(scope="module") +def pair(): + """Random-texture stereo pair, the right image shifted left by DISPARITY.""" + rng = np.random.default_rng(0) + left = rng.integers(0, 255, size=(40, 96), dtype=np.uint8) + right = np.roll(left, -DISPARITY, axis=1) + return Image(left), Image(right) + + +def interior(a, hw, margin): + """Columns and rows where the disparity is well defined.""" + return a[hw + margin : -(hw + margin), DISPARITY + hw + margin : -(hw + margin)] + + +class TestStereoSimple: + # stereo_simple takes float images here: given a uint8 image it pads with + # NaN, which numpy casts to 0 with a RuntimeWarning. + @pytest.fixture(scope="class") + def result(self, pair): + left, right = pair + left = Image(left.array.astype(np.float32)) + right = Image(right.array.astype(np.float32)) + return left.stereo_simple(right, hw=2, drange=[4, 12]) + + def test_recovers_disparity(self, result): + disparity, similarity, dsi = result + # well inside the image every window sees the true shift + nt.assert_array_equal(disparity.array[10:30, 30:80], DISPARITY) + # a perfect match has a ZNCC of 1 + nt.assert_allclose(similarity.array[10:30, 30:80], 1.0, atol=1e-5) + + def test_dsi_peak_is_at_the_true_disparity(self, result): + _, _, dsi = result + assert dsi.shape[2] == 8 + peak = np.argmax(dsi[10:30, 30:80, :], axis=2) + 4 + nt.assert_array_equal(peak, DISPARITY) + + def test_border_is_nan(self, result): + disparity, _, _ = result + assert np.isnan(disparity.array[:, :4]).all() + + @pytest.mark.xfail( + strict=True, + reason="the docstring says the outputs are the same size as the inputs " + "but the window stack makes them larger by 2*hw in each direction", + ) + def test_output_is_the_size_of_the_input(self, pair, result): + left, _ = pair + disparity, similarity, dsi = result + assert disparity.shape == left.shape + assert similarity.shape == left.shape + assert dsi.shape[:2] == left.shape + + @pytest.mark.xfail( + strict=True, + raises=ValueError, + reason="an integer drange becomes (0, n) and the slice right_arr[:, :-0] " + "is then empty, so the arrays cannot be multiplied", + ) + def test_integer_range(self, pair): + left, right = pair + left = Image(left.array.astype(np.float32)) + right = Image(right.array.astype(np.float32)) + disparity, _, _ = left.stereo_simple(right, hw=2, drange=12) + nt.assert_array_equal(disparity.array[10:30, 30:80], DISPARITY) + + +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)) + 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) + + +@pytest.mark.parametrize("method", ["stereo_BM", "stereo_SGBM"]) +class TestOpenCVStereo: + def test_recovers_disparity(self, pair, method): + left, right = pair + disparity = getattr(left, method)(right, hw=3, drange=[0, 16]) + assert disparity.shape == left.shape + inner = interior(disparity.A, 3, 3) + # the matcher agrees with the known shift for most interior pixels + assert np.median(inner) == pytest.approx(DISPARITY, abs=0.5) + assert np.mean(np.abs(inner - DISPARITY) < 1) > 0.9 + + def test_integer_range_means_zero_to_n(self, pair, method): + left, right = pair + a = getattr(left, method)(right, hw=3, drange=16) + b = getattr(left, method)(right, hw=3, drange=(0, 16)) + nt.assert_array_equal(a.A, b.A) + + def test_speckle_filter_is_accepted(self, pair, method): + left, right = pair + disparity = getattr(left, method)(right, hw=3, drange=[0, 16], speckle=(50, 2)) + assert disparity.shape == left.shape + + def test_small_block_is_an_error(self, pair, method): + left, right = pair + with pytest.raises(ValueError, match="block size too small"): + getattr(left, method)(right, hw=1, drange=[0, 16]) + + +class TestRectifyHomographies: + def test_pure_horizontal_translation(self): + # For a pair related by a horizontal translation the fundamental matrix + # is the skew-symmetric matrix of the x axis, and rectification must + # leave corresponding points on the same row. + rng = np.random.default_rng(1) + n = 20 + u1 = rng.uniform(10, 150, n) + v = rng.uniform(10, 110, n) + p1 = np.vstack((u1, v)) + p2 = np.vstack((u1 - 12 - 0.05 * v, v)) # shifted along the row + F = np.array([[0, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=float) + matches = SimpleNamespace(inliers=SimpleNamespace(p1=p1, p2=p2)) + + im = Image.Zeros(size=(160, 120), dtype="uint8") + H1, H2 = im.rectify_homographies(matches, F) + assert H1.shape == (3, 3) + assert H2.shape == (3, 3) + + def warp(H, p): + q = H @ np.vstack((p, np.ones(n))) + return q[:2] / q[2] -class TestImageMultiview(unittest.TestCase): - # new test - def test_DSI_refine(self): - """Test DSI refinement class method""" - # TODO: Create minimal DSI for testing - pass - - # new test - def test_rectify_homographies(self): - """Test stereo rectification using homographies""" - # TODO: Create stereo pair and test rectification - pass - - # new test - def test_stereo_BM(self): - """Test Block Matching stereo algorithm""" - im_left = Image.Random(size=(100, 100), dtype="uint8") - im_right = Image.Random(size=(100, 100), dtype="uint8") - # TODO: Test with actual stereo pair - pass - - # new test - def test_stereo_SGBM(self): - """Test Semi-Global Block Matching stereo algorithm""" - im_left = Image.Random(size=(100, 100), dtype="uint8") - im_right = Image.Random(size=(100, 100), dtype="uint8") - # TODO: Test with actual stereo pair - pass - - # new test - def test_stereo_simple(self): - """Test simple stereo matching""" - im_left = Image.Random(size=(100, 100), dtype="uint8") - im_right = Image.Random(size=(100, 100), dtype="uint8") - # TODO: Test with actual stereo pair - pass - - -# ----------------------------------------------------------------------- # -if __name__ == "__main__": - unittest.main() + q1 = warp(H1, p1) + q2 = warp(H2, p2) + nt.assert_allclose(q1[1], q2[1], atol=1e-3) diff --git a/tests/test_image_region_features_extra.py b/tests/test_image_region_features_extra.py new file mode 100644 index 00000000..cda71e1c --- /dev/null +++ b/tests/test_image_region_features_extra.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +"""More tests for ``ImageRegionFeatures``: MSER indexing and printing, and OCR. + +OpenCV 5 finds far fewer MSERs than OpenCV 4 on the same image (Issue 54), so +the indexing tests build an ``MSERFeature`` by hand with known points and +bounding boxes, which behaves the same on both. The OCR tests use the real +``pytesseract`` where it and the ``tesseract`` program are installed, and a +stand-in for ``pytesseract`` for the code that filters and plots the words. +""" + +import shutil + +import matplotlib +import numpy as np +import numpy.testing as nt +import pytest + +matplotlib.use("Agg") + +import cv2 +import matplotlib.pyplot as plt + +from machinevisiontoolbox import Image +from machinevisiontoolbox import ImageRegionFeatures as irf +from machinevisiontoolbox.ImageRegionFeatures import MSERFeature, OCRWord + +# --------------------------------------------------------------------------- # +# MSER + + +@pytest.fixture +def msers(): + """Three regions with 3, 2 and 1 points, each a 2 x N array of (u, v).""" + m = MSERFeature() + m._points = [ + np.array([[1, 3, 5], [2, 4, 6]]), + np.array([[7, 9], [8, 10]]), + np.array([[0], [0]]), + ] + m._bboxes = np.array([[1, 2, 5, 6], [7, 8, 9, 10], [0, 0, 1, 1]]) + return m + + +class TestMSERIndexing: + def test_length(self, msers): + assert len(msers) == 3 + + def test_empty(self): + m = MSERFeature() + assert len(m) == 0 + assert m.bbox.shape == (0, 4) + assert m.points == [] + + def test_slice(self, msers): + sub = msers[1:] + assert len(sub) == 2 + nt.assert_array_equal(sub.bbox, [[7, 8, 9, 10], [0, 0, 1, 1]]) + + @pytest.mark.parametrize( + "index", + [ + [0, 2], + (0, 2), + np.array([0, 2]), + np.array([True, False, True]), + ], + ids=["list", "tuple", "int array", "bool array"], + ) + def test_sequence_of_indices(self, msers, index): + sub = msers[index] + assert len(sub) == 2 + nt.assert_array_equal(sub.bbox, [[1, 2, 5, 6], [0, 0, 1, 1]]) + nt.assert_array_equal(sub.points[0], [[1, 3, 5], [2, 4, 6]]) + nt.assert_array_equal(sub.points[1], [[0], [0]]) + + def test_single_region_gives_arrays(self, msers): + # a one-region object returns the array itself, not a list of one + one = msers[2:] + assert len(one) == 1 + nt.assert_array_equal(one.bbox, [0, 0, 1, 1]) + nt.assert_array_equal(one.points, [[0], [0]]) + + def test_several_regions_give_lists(self, msers): + assert len(msers.points) == 3 + assert msers.bbox.shape == (3, 4) + + @pytest.mark.xfail( + strict=True, + reason="an int index leaves the region's 2 x N point array in _points, " + "so len() of the result is 2, not 1", + ) + def test_integer_index_is_one_region(self, msers): + assert len(msers[0]) == 1 + + +class TestMSERPrinting: + def test_several(self, msers): + assert str(msers) == "MSER features, 3 regions" + assert repr(msers) == str(msers) + + def test_single(self, msers): + assert str(msers[2:]) == "MSER feature: u: 0 - 1, v: 0 - 1" + + @pytest.mark.xfail( + strict=True, + raises=IndexError, + reason="str() of an object with no regions looks up the first bounding box", + ) + def test_empty(self): + str(MSERFeature()) + + +class TestMSERDetection: + def test_blank_image_is_handled(self): + # a flat image has no detail: OpenCV 5 finds no regions, OpenCV 4 finds + # the whole image as two. The empty case is the one that differs. + m = Image(np.zeros((50, 50), dtype=np.uint8)).MSER() + if len(m) == 0: + assert m.bbox.shape == (0, 4) + else: + assert m.bbox.shape == (len(m), 4) + + def test_real_image(self): + m = Image.Read("castle.png").MSER() + if len(m) == 0: + pytest.skip("OpenCV 5 finds no MSERs on this image, see Issue 54") + bbox = m.bbox + assert bbox.shape == (len(m), 4) + # lrtb: left < right and top < bottom for every region + assert (bbox[:, 2] > bbox[:, 0]).all() + assert (bbox[:, 3] > bbox[:, 1]).all() + # each point array is 2 x N, inside its own bounding box + for p, b in zip(m.points, bbox): + assert p.shape[0] == 2 + assert p[0].min() >= b[0] and p[0].max() <= b[2] + assert p[1].min() >= b[1] and p[1].max() <= b[3] + + +# --------------------------------------------------------------------------- # +# OCR + +WORD = { + "text": ["", "HELLO", "low", "maybe"], + "conf": ["-1", 96, 12, 70], + "left": [0, 10, 40, 80], + "top": [0, 20, 30, 40], + "width": [100, 50, 20, 25], + "height": [60, 15, 10, 12], +} + + +class TestOCRWord: + def test_properties(self): + w = OCRWord(WORD, 1) + assert w.text == "HELLO" + assert w.conf == 96 + assert (w.l, w.t, w.w, w.h) == (10, 20, 50, 15) + assert w.ltrb == [10, 20, 60, 35] + assert str(w) == "HELLO (96%)" + assert repr(w) == str(w) + + def test_plot(self): + plt.figure() + OCRWord(WORD, 1).plot() + ax = plt.gca() + assert len(ax.patches) == 1 # the label box + plt.close("all") + + def test_plot_falls_back_when_linestyle_is_not_accepted(self, monkeypatch): + calls = [] + + def fake(text, lb, wh, color, linestyle=None): + calls.append(linestyle) + if linestyle is not None: + raise TypeError("linestyle passed twice") + + monkeypatch.setattr(irf, "plot_labelbox", fake) + OCRWord(WORD, 1).plot() + assert calls == ["--", None] + + +class FakePytesseract: + """Stand-in that returns the dictionary WORD, as image_to_data would.""" + + class Output: + DICT = "dict" + + @staticmethod + def image_to_data(image, output_type): + assert output_type == "dict" + return WORD + + +class TestOCRFiltering: + @pytest.fixture(autouse=True) + def fake(self, monkeypatch): + monkeypatch.setattr(irf, "_pytesseract", FakePytesseract) + monkeypatch.setattr(irf, "_pytesseract_available", True) + + def test_words_above_the_confidence_threshold(self): + words = Image.Zeros(size=(100, 60), dtype="uint8").ocr(minconf=50) + # "-1" marks a non-word row and "low" is under the threshold + assert [w.text for w in words] == ["HELLO", "maybe"] + + def test_lower_threshold_keeps_more(self): + words = Image.Zeros(size=(100, 60), dtype="uint8").ocr(minconf=10) + assert [w.text for w in words] == ["HELLO", "low", "maybe"] + + def test_plot(self): + plt.figure() + Image.Zeros(size=(100, 60), dtype="uint8").ocr(minconf=50, plot=True) + assert len(plt.gca().patches) == 2 + plt.close("all") + + +def test_ocr_without_pytesseract(monkeypatch, capsys): + monkeypatch.setattr(irf, "_pytesseract_available", False) + words = Image.Zeros(size=(10, 10), dtype="uint8").ocr() + assert words == [] + assert "pytesseract is required" in capsys.readouterr().out + + +@pytest.mark.skipif( + not irf._pytesseract_available or shutil.which("tesseract") is None, + reason="pytesseract and the tesseract program are needed", +) +def test_ocr_reads_rendered_text(): + img = np.full((60, 300), 255, dtype=np.uint8) + cv2.putText(img, "HELLO", (10, 45), cv2.FONT_HERSHEY_SIMPLEX, 1.5, 0, 3) + words = Image(img).ocr(minconf=10) + assert "HELLO" in [w.text for w in words] + word = next(w for w in words if w.text == "HELLO") + # the bounding box lies on the drawn text + assert 0 <= word.l < 30 and 0 <= word.t < 30 + assert word.ltrb[2] > 100