1
votes

I am suprised by the fact that I can't seem to find any online implementation of the Hough Transform algorithm as described here. Opencv implements a line detector using the Hough Transform but does not provide any function that performs the transformation into the Hough Space without the line detection after.

So I implemented a naive version myself where seg_map is a numpy array containing 0 and 1:

def hough_transform(seg_map):
   rho_step = 5
   phi_step = 20 * np.pi/180
   n_points_min = 2*rho_step
   diag_length = np.sqrt(seg_map.shape[0]**2 + seg_map.shape[1]**2)
   hough_map = np.zeros( (int(2*np.pi/phi_step),int(diag_length/rho_step)) )

   Y, X = np.where(seg_map>0)
   for x, y in zip(X, Y):
      theta = np.arctan2(y, x)
      r = np.sqrt(x**2+y**2)
      for i in range(hough_map.shape[0]):
          phi = i * phi_step - np.pi/2
          rho = r * np.cos(theta-phi)
          if rho>0:
              rho_discretized = int(rho/rho_step)
              hough_map[i, rho_discretized] += 1
   return hough_map

However, it's pretty slow (for the inputs I have, the cv2 functions is 200 times faster for the Hough transform + line detection than my Hough Transform algorithm).

So I actually have two questions :

  • Did I miss an of-the-shelf python algorithm to perform only the Hough Transform without Line detection ? I know that the OpenCV version of the code is open source, but it's implemented in C++.

  • Apart from parallelization or non-Python implementation, is there something in my code that is inefficient and should be changed ?

2
Part of the problem, besides speed, is that this does not handle vertical lines very well. It's the right idea, but the target cells in the accumulator are better computed as a function of theta, independetly of pixel location - Mad Physicist

2 Answers

0
votes

OpenCV is open source. Please, check their code and see how they did implement it. Borrow the code, if needed. The URL is here: https://github.com/opencv/opencv

0
votes

You missed scikit-image. It is an addition to scipy exactly for addtional basic transforms and similar. Specifically, the hough_line function performs the transform. You can find an example here: https://scikit-image.org/docs/dev/auto_examples/edges/plot_line_hough_transform.html.

If you do decide to go with @lennik's advice, the standard Hough transform is implemented in C++ here: https://github.com/opencv/opencv/blob/3.4/modules/imgproc/src/hough.cpp#L163 (permalink). It has the same functionality as the one Cython implementation in scikit image: https://github.com/scikit-image/scikit-image/blob/v0.18.x/skimage/transform/_hough_transform.pyx#L245 (permalink).