Search code examples
pythonimagenumpyscikit-imagehough-transform

code explanation about hough_line and hough_line_peaks


I was able to find this link: Calculating the angle between two lines in an image in Python which I then only took the code part that allows to calculate the angle:

import numpy as np
from skimage.transform import (hough_line, hough_line_peaks, probabilistic_hough_line)
from pylab import imread, gray, mean
import matplotlib.pyplot as plt

image = imread('D:\\Pictures\\PyTestPics\\oo.tiff')
image = np.mean(image, axis=2)

h, theta, d = hough_line(image)

angle = []
dist = []
for _, a, d in zip(*hough_line_peaks(h, theta, d)):
    angle.append(a)
    dist.append(d)

angle = [a*180/np.pi for a in angle]
angle_reel = np.max(angle) - np.min(angle)

print(angle_reel)

can anyone please explain me the code of the for loop and the angle_reel? because I couldn't understand how are there multiple angles and those multiple angles are formed between what line and what other object inside the image? It would be really appreciated.


Solution

  • Your image has two lines, I'll call them line a and line b. Each of those lines will have and angle. The angle between those lines will be the angle of line a - angle of line b.

    When your code iterates through the hough_line_peaks in the, it is actually iterating though the data for each line. Each line has a distance, and an angle.

    for _, a, d in zip(*hough_line_peaks(h, theta, d)):
        angle.append(a)
        dist.append(d)
    

    If there are two lines in your image, you will end up with a list of angles that has two values. Those two values will be the angles of the lines in reference to the edge of the image. To find the angle of the lines in reference to each other, subtract the values.

    Here is an example image:

    image with two lines

    The angles of the lines are: [1.3075343725834614, 0.48264691605429766]. That's in radians, so they are converted to degrees with the code: angle = [a*180/np.pi for a in angle]. In degrees the angles are [74.91620111731844, 27.65363128491619]. This seems pretty reasonable, one is a little more than 45 degrees and one is a little less. The angle between the lines is max(angles) - min(angles) or 47.262 degrees.

    This image shows the angles drawn on the image:

    angles on image