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

art*_*ski -1 python math opencv image-processing computational-geometry

假设我有用于与提取的行的坐标的列表cv2.HoughLinesP边缘掩模从获得的cv2.Canny边缘检测器。

lines = [[x1,y1,x2,y2] , ... ]
Run Code Online (Sandbox Code Playgroud)

如果一条线的斜率在±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

Run Code Online (Sandbox Code Playgroud)

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

编辑: 测试图像显示,有很多未分类的线条:1)所有水平线条都被涂上绿色。2)所有垂直线都涂成洋红色。 例

MBo*_*MBo 5

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

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
Run Code Online (Sandbox Code Playgroud)