大致将图像上的线条分类为垂直或水平

Approximately classify lines on image as vertical or horizontal

假设我有一个用 cv2.HoughLinesP 边缘掩码 中提取的线的坐标列表 cv2.Canny 边缘检测器。

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

如果一条线的斜率在水平线的±60°以内,则该线被归类为水平线 方向。丢弃所有其他斜率。

如果一条线的斜率在垂直线的±5°以内,则该线被归类为垂直线 方向。丢弃所有其他斜率。

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

我的函数 split_lines() 在倾斜角度和 h/v 线方向方面是否正确?

编辑: 测试图像显示有很多错误分类的行: 1)所有的水平线都涂成绿色。 2)所有的垂直线都涂成洋红色。

没有使用坐标差的密集三角函数

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