Search code examples
python-2.7numpyhough-transform

Why does hough transform for lines returning sinusoids divided halfway?


I've been implementing the standard Hough Transform for line detection using Python and numpy.

I've succeeded in implementing the algorithm, but it's output has the resulting sinusoids divided in half. One half is in one extreme of the resulting image and the rest is in another part of the image.

Here's an example of the output I'm getting:

This is the result of the algorithm.

Here's my code:

def houghTransf(img, r_ro, r_theta,thrs):

    linhas, colunas =img.shape

    theta = np.linspace(0.0,180.0,np.ceil(180.0/r_theta)+1)

    max_rho = np.sqrt((linhas**2)+(colunas**2))

    rho = np.linspace(0.0,max_rho,np.ceil(max_rho/r_ro)+1)


    res = np.zeros((len(theta),len(rho)))

    # Hough Transform

    for i in range(linhas):
        for j in range(colunas):
            if(img[i,j]<>0):
                for k in theta:
                    v_rho = i*np.sin(k*(np.pi/180)) + j*np.cos(k*(np.pi/180))
                    res[k,v_rho] += 1

    return res

I suspect that the problem is somewhere in the definition of the hough space (definitions of theta and rho), but changing the minimum limit in the linspace of each doesn't seem to help.

Is there any way to show the sinusoids without having them divided like in the image?

Can adjusting the range of rho and theta help in any way?

EDIT:

I've also tried to run the algorithm with only one line.

enter image description here

Here's the output of my implementation of the algorithm for the case in which there's only one line:

enter image description here


Solution

  • Note that after this line:

    v_rho = i*np.sin(k*(np.pi/180)) + j*np.cos(k*(np.pi/180))
    

    v_rho can end up negative. You should add half of the range to it, something like this:

    v_rho = 1.0*len(rho)/2 + i*np.sin(k*(np.pi/180)) + j*np.cos(k*(np.pi/180))
    

    (you need to verify if the range is all right, perhaps rho needs to be twice as large now, not sure).

    The problem was hidden from you, because Python and numpy allow indexing arrays with negative numbers. This fix will translate your sinusoids half of the range to the right, so they won't be split anymore.