diff --git a/src/machinevisiontoolbox/ImageLineFeatures.py b/src/machinevisiontoolbox/ImageLineFeatures.py index 05d3356c..ace383c7 100644 --- a/src/machinevisiontoolbox/ImageLineFeatures.py +++ b/src/machinevisiontoolbox/ImageLineFeatures.py @@ -200,65 +200,89 @@ def plot_lines(self, lines: np.ndarray, *args: Any, **kwargs: Any) -> None: for line in lines: plt.plot(line[[0, 2]], line[[1, 3]], *args, **kwargs) - def accumulator(self, skip: int = 1) -> None: + def accumulator(self) -> None: r""" Compute the Hough accumulator - :param skip: increment for line strength threshold, defaults to 1 - :type skip: int, optional + Every set pixel :math:`(u, v)` of the image votes for all the lines that + pass through it, one for each quantized :math:`\theta`, with - It creates two new attributes for the instance: + .. math:: \rho = u \cos \theta + v \sin \theta - - ``A`` which is the Hough "accumulator" array, rows represent :math:`\rho` - and columns represent :math:`\theta`. + quantized into steps of ``drho``. It creates the following attributes + for the instance: + + - ``A`` is the Hough "accumulator" array of integer vote counts, rows + represent :math:`\rho` and columns represent :math:`\theta`. - ``votes`` is a list of the number of lines found versus threshold, it - can be used to select an optimal threshold. + can be used to select an optimal threshold. Element ``t`` is the number + of lines that :meth:`lines` returns for ``minvotes=t``, to within + rounding, since a line is a cell of ``A`` that exceeds the threshold + and is a local maximum. + - ``t`` is the highest threshold at which a line is still found. - ``extent`` is :math:`[\theta_{\mbox{min}}, \theta_{\mbox{max}}, - \rho_{\mbox{min}}, \rho_{\mbox{max}}]`. - - .. warning:: The OpenCV ``HoughLines`` function does not expose the - accumulator array. This method "reverse engineers" the accumulator - array through a costly process of computing the Hough transform - for all possible thresholds (increasing in steps of ``skip``). This - is helpful for pedagogy but very inefficient in practice. - - :seealso: :meth:`plot_accumulator` + \rho_{\mbox{min}}, \rho_{\mbox{max}}]`, the edges of the array + for plotting. + + .. warning:: The OpenCV ``HoughLines`` function does not expose its + accumulator array, so it is computed here directly by voting, with + the same quantization. Unlike the lines returned by :meth:`lines`, + which are only the peaks, ``A`` holds the votes of every cell. + The peaks of ``A`` and the lines from OpenCV can differ by a very + few cells, where OpenCV's single-precision arithmetic rounds a + :math:`\rho` value differently. This is helpful for pedagogy but + it is not the array that OpenCV used. + + .. versionchanged:: 2.5.0 + The accumulator is computed directly by voting, so ``A`` is the + complete array and not just its peaks, and ``extent`` spans the + whole range of :math:`\rho`. Previously it was reconstructed + from repeated calls of ``HoughLines``, which was slow. The ``skip`` + argument has been removed since every threshold is now counted. + + .. seealso:: :meth:`plot_accumulator` :meth:`lines` """ - self.nz = np.sum(self.image > 0) - t = 0 - theta = np.empty((0,)) - rho = np.empty((0,)) - votes = [] - while True: - lines = cv2.HoughLines( - image=self.image, rho=self.drho, theta=self.dtheta, threshold=t - ) - - if lines is None or len(lines) == 0: - # no lines found at this threshold, bail out. OpenCV 5.1 - # returns an empty array, not None, so test for both. - self.t = t - 1 - break - - # append the found lines and votes - theta = np.concatenate((theta, lines[:, 0, 1].flatten())) - rho = np.concatenate((rho, lines[:, 0, 0].flatten())) - votes.append(lines.shape[0]) - - t += skip # increment the line strength threshold - - # now create the accumulator array - theta_bins = np.arange( - theta.min() - self.dtheta / 2, theta.max() + self.dtheta / 2, self.dtheta - ) - rho_bins = np.arange( - rho.min() - self.drho / 2, rho.max() + self.drho / 2, self.drho + image = self.image + height, width = image.shape[:2] + ntheta = int(round(np.pi / self.dtheta)) + # the same number of bins as OpenCV: rho = 0 is in the middle row + nrho = int(round(((width + height) * 2 + 1) / self.drho)) + rho0 = (nrho - 1) // 2 + + v, u = np.nonzero(image) + self.nz = len(u) + + A = np.zeros((nrho, ntheta), dtype=int) + for n in range(ntheta): + theta = n * self.dtheta + rho = np.round((u * np.cos(theta) + v * np.sin(theta)) / self.drho) + A[:, n] = np.bincount(rho.astype(int) + rho0, minlength=nrho) + + # a line is a cell above the threshold that is a local maximum in the + # rho and theta directions, which is the rule OpenCV uses + P = np.pad(A, 1) + centre = P[1:-1, 1:-1] + peak = ( + (centre > P[:-2, 1:-1]) + & (centre >= P[2:, 1:-1]) + & (centre > P[1:-1, :-2]) + & (centre >= P[1:-1, 2:]) ) + counts = np.bincount(A[peak], minlength=1) + # a peak of v votes is found at every threshold t < v + peaks_above = counts.sum() - np.cumsum(counts) + votes = [int(n) for n in peaks_above[: np.max(A, initial=0)]] - self.extent = (theta_bins[0], theta_bins[-1], rho_bins[0], rho_bins[-1]) - self.A = np.histogram2d(theta, rho, bins=(theta_bins, rho_bins))[0].T + self.A = A self.votes = votes + self.t = len(votes) - 1 + self.extent = ( + -self.dtheta / 2, + (ntheta - 0.5) * self.dtheta, + (-rho0 - 0.5) * self.drho, + (nrho - 1 - rho0 + 0.5) * self.drho, + ) def plot_accumulator( self, ax: Axes | None = None, title: str | None = None, **kwargs: Any diff --git a/tests/test_image_line_features.py b/tests/test_image_line_features.py index 9f8dd83c..03aa6921 100644 --- a/tests/test_image_line_features.py +++ b/tests/test_image_line_features.py @@ -67,8 +67,7 @@ def test_plot_lines(self): class TestHoughNoLines(unittest.TestCase): """OpenCV 4 and 5.0 return None from HoughLines when nothing is found, - OpenCV 5.1 returns an empty array. The accumulator used to loop forever - on the second.""" + OpenCV 5.1 returns an empty array.""" def setUp(self): arr = np.zeros((60, 60), dtype="uint8") @@ -92,16 +91,6 @@ def wrapper(*args, **kwargs): return wrapper - def test_accumulator_stops_when_there_are_no_more_lines(self): - import cv2 - - with unittest.mock.patch.object( - cv2, "HoughLines", self.as_opencv_5_1(cv2.HoughLines) - ): - self.hough.accumulator() - self.assertIsNotNone(self.hough.A) - self.assertEqual(self.hough.t, 39) # 40 votes survive a threshold of 39 - def test_lines_with_an_empty_array(self): import cv2 @@ -119,6 +108,85 @@ def test_lines_p_with_an_empty_array(self): self.assertEqual(self.hough.lines_p(minvotes=100).shape, (0, 4)) +class TestHoughAccumulator(unittest.TestCase): + """The accumulator is computed by voting, so it can be checked exactly.""" + + def setUp(self): + arr = np.zeros((100, 100), dtype="uint8") + arr[50, 10:90] = 255 # horizontal, theta = pi/2, rho = 50, 80 votes + arr[20:80, 30] = 255 # vertical, theta = 0, rho = 30, 60 votes + self.arr = arr + self.hough = Image(arr).Hough() + self.hough.accumulator() + + def test_matches_voting_one_pixel_at_a_time(self): + arr = np.zeros((6, 8), dtype="uint8") + arr[1, 2] = arr[4, 5] = arr[3, 0] = 255 + h = Image(arr).Hough(ntheta=12) + h.accumulator() + nrho = (6 + 8) * 2 + 1 + expected = np.zeros((nrho, 12), dtype=int) + for v, u in zip(*np.nonzero(arr)): + for n in range(12): + theta = n * (np.pi / 12) + rho = int(round(u * np.cos(theta) + v * np.sin(theta))) + expected[rho + (nrho - 1) // 2, n] += 1 + np.testing.assert_array_equal(h.A, expected) + + def test_every_set_pixel_votes_once_per_angle(self): + self.assertEqual(self.hough.nz, 80 + 60 - 1) + self.assertEqual(self.hough.A.sum(), self.hough.nz * 180) + self.assertEqual(self.hough.A.shape, (401, 180)) + + def test_the_peaks_are_the_lines(self): + A = self.hough.A + centre = (A.shape[0] - 1) // 2 + self.assertEqual(A[centre + 50, 90], 80) # theta = 90 degrees + self.assertEqual(A[centre + 30, 0], 60) # theta = 0 + self.assertEqual(np.sort(A.ravel())[-1], 80) + + def test_votes_count_the_lines_at_each_threshold(self): + import cv2 + + h = self.hough + for t in (0, 10, 30, 59, 60, 61, 79, 80): + lines = cv2.HoughLines(h.image, h.drho, h.dtheta, t) + expected = 0 if lines is None else len(lines) + n = h.votes[t] if t < len(h.votes) else 0 + self.assertEqual(n, expected, f"threshold {t}") + + def test_votes_fall_with_threshold_and_t_is_the_last_with_a_line(self): + votes = np.array(self.hough.votes) + self.assertTrue((np.diff(votes) <= 0).all()) + self.assertGreater(votes[-1], 0) + self.assertEqual(self.hough.t, len(votes) - 1) + self.assertEqual(self.hough.t, 79) # the longest line has 80 votes + + def test_empty_image(self): + h = Image(np.zeros((20, 20), dtype="uint8")).Hough() + h.accumulator() + self.assertEqual(h.A.sum(), 0) + self.assertEqual(h.votes, []) + self.assertEqual(h.t, -1) + + def test_quantization_options(self): + h = Image(self.arr).Hough(ntheta=90, drho=2) + h.accumulator() + self.assertEqual(h.A.shape, (200, 90)) + + def test_extent_gives_the_edges_of_the_array(self): + left, right, bottom, top = self.hough.extent + self.assertAlmostEqual(left, -np.pi / 360) + self.assertAlmostEqual(right, np.pi - np.pi / 360) + # rho = 0 is the middle row, so the range is symmetric + self.assertAlmostEqual(bottom, -top) + self.assertAlmostEqual(top - bottom, self.hough.A.shape[0]) + + def test_skip_is_no_longer_accepted(self): + with self.assertRaises(TypeError): + self.hough.accumulator(skip=2) + + # ----------------------------------------------------------------------- # if __name__ == "__main__": unittest.main() diff --git a/tests/test_image_line_features_hough.py b/tests/test_image_line_features_hough.py index a32aa80d..2fb2c226 100644 --- a/tests/test_image_line_features_hough.py +++ b/tests/test_image_line_features_hough.py @@ -112,9 +112,9 @@ def test_attributes(self, h): # 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 + # the longest line has 80 votes, so it is found for any threshold + # below 80, and h.t records the last threshold that found a line + assert h.t == 79 def test_votes_never_increase_with_the_threshold(self, h): votes = np.array(h.votes) @@ -127,18 +127,10 @@ def test_peak_is_the_longest_line(self, h): 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 + # the longest line, 80 pixels, 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): diff --git a/tests/test_plot_titles.py b/tests/test_plot_titles.py index 5385f767..7ac4ffc8 100644 --- a/tests/test_plot_titles.py +++ b/tests/test_plot_titles.py @@ -156,9 +156,6 @@ def test_hough_accumulator_titles(): a[10:30, 20] = 255 im = Image(a) h = im.Hough() - # supply the accumulator, since computing it is deliberately slow - h.A = np.random.rand(10, 20) - h.extent = [0, np.pi, -20, 20] h.plot_accumulator() assert window_title() == "Hough Accumulator" h.plot_accumulator(title="mine")