Search code examples
pythonopencvmathimage-processingcomputational-geometry

Approximately classify lines on image as vertical or horizontal


Suppose I have a list of coordinates for lines extracted with cv2.HoughLinesP from edge mask obtained from cv2.Canny edge detector.

lines = [[x1,y1,x2,y2] , ... ]

A line is classified as horizontal if its slope is within ±60◦ of the horizontal direction. All other slopes are discarded.

A line is classified as a vertical if its slope is within ±5◦ of the vertical direction. All other slopes are discarded.

import numpy as np
import cv2


def detect_line_angle(line):
    x1, y1, x2, y2 = line
    angle = np.arctan2(x2 - x1, y2 - y1)
    # angle = angle * 180 / 3.14
    return angle


def get_lines_from_edge_mask(edge_mask):
    result = []
    lines = cv2.HoughLinesP(edge_mask, 1, np.pi / 180, 30, maxLineGap=5)
    for line in lines:
        result.append(line[0])

    return result


def is_horizontal(theta, delta=1.05):
    return True if (np.pi - delta) <= theta <= (np.pi + delta) or (-1 * delta) <= theta <= delta else False


def is_vertical(theta, delta=0.09):
    return True if (np.pi / 2) - delta <= theta <= (np.pi / 2) + delta or (
            3 * np.pi / 2) - delta <= theta <= (
                           3 * np.pi / 2) + delta else False


def distance(line):
    dist = np.sqrt(((line[0] - line[2]) ** 2) + ((line[1] - line[3]) ** 2))
    return dist


def split_lines(lines):
    v_lines = []
    h_lines = []
    for line in lines:
        line_angle = detect_line_angle(line)

        dist = distance(line)
        if dist > 30:
            if is_vertical(line_angle):
                v_lines.append(line)

            if is_horizontal(line_angle):
                h_lines.append(line)

    return v_lines, h_lines

Is my function split_lines() correct with respect to the slope angle and h/v line direction?

EDIT: Test image shows that there are a lot of miss-classified lines: 1)all the horizontal lines were pained green. 2)all the vertical lines were painted magenta. example


Solution

  • Without intensive trigonometry using coordinate differences

    t5 = tan(5*Pi/180) calculated once
    t60 = Sqrt(3)/2 calculated once
    
    Vertical: dy != 0 and abs(dx/dy) < t5
    Horizontal: dx != 0 and abs(dy/dx) < t60