Opencv-python 计算线段的夹角与交叉点

Opencv-python 计算线段的夹角与交叉点

代码:

import numpy as np
import cv2 as cv


def lines_intersection(l1, l2):
    x1, y1 = l1[0], l1[1]
    x2, y2 = l1[2], l1[3]

    a1 = -(y2 - y1)
    b1 = x2 - x1
    c1 = (y2 - y1) * x1 - (x2 - x1) * y1

    x3, y3 = l2[0], l2[1]
    x4, y4 = l2[2], l2[3]

    a2 = -(y4 - y3)
    b2 = x4 - x3
    c2 = (y4 - y3) * x3 - (x4 - x3) * y3

    r = False
    if b1 == 0 and b2 != 0:
        r = True
    elif b1 != 0 and b2 == 0:
        r = True
    elif b1 != 0 and b2 != 0 and a1 / b1 != a2 / b2:
        r = True

    if r:
        x0 = (b1 * c2 - b2 * c1) / (a1 * b2 - a2 * b1)
        y0 = (a1 * c2 - a2 * c1) / (a2 * b1 - a1 * b2)
        # print(x0, y0)
        a = np.sqrt((x4 - x2) ** 2 + (y4 - y2) ** 2)
        b = np.sqrt((x4 - x0) ** 2 + (y4 - y0) ** 2)
        c = np.sqrt((x2 - x0) ** 2 + (y2 - y0) ** 2)
        angle = np.arccos((b * b + c * c - a * a) / (2 * b * c)) * 180 / np.pi
        # print(angle)
        return (x0, y0), angle


def main():
    # 初始化线段1,2
    line1_p = (100, 200, 400, 200)
    line2_p = (100, 100, 400, 400)

    # 计算 线段夹角与交叉点
    cross_p, angle = lines_intersection(line1_p, line2_p)
    print('Cross point:', cross_p)
    print('Angle:', angle)

    # 显示线段 交叉点
    img_show = np.zeros((500, 500, 3), dtype=np.uint8)
    cv.line(img_show, (line1_p[0], line1_p[1]),
            (line1_p[2], line1_p[3]), (255, 0, 0), 2)
    cv.line(img_show, (line2_p[0], line2_p[1]),
            (line2_p[2], line2_p[3]), (0, 0, 255), 2)

    cv.circle(img_show, (int(cross_p[0]), int(cross_p[1])), 5, (0, 255, 255), -1)

    cv.imshow('img_show', img_show)
    cv.imwrite('img_show.jpg', img_show)
    cv.waitKey()
    cv.destroyAllWindows()


if __name__ == '__main__':
    main()

Opencv-python 计算线段的夹角与交叉点_第1张图片

共点的夹角计算

    @staticmethod
    def get_cross_angle(l1, l2):
        l1_p1, l1_p2 = l1
        l2_p1, l2_p2 = l2
        l1_p1_x, l1_p1_y = l1_p1
        l1_p2_x, l1_p2_y = l1_p2

        l2_p1_x, l2_p1_y = l2_p1
        l2_p2_x, l2_p2_y = l2_p2

        arr_a = np.array([(l1_p2_x - l1_p1_x), (l1_p2_y - l1_p1_y)])  # 向量a
        arr_b = np.array([(l2_p2_x - l2_p1_x), (l2_p2_y - l2_p1_y)])  # 向量b
        cos_value = (float(arr_a.dot(arr_b)) / (np.sqrt(arr_a.dot(arr_a)) * np.sqrt(arr_b.dot(arr_b))))  # 注意转成浮点数运算
        return np.arccos(cos_value) * (180 / np.pi)

顺时针 角度差

  @staticmethod
  def clockwise_angle(line1, line2):
      p1, c1 = line1 // 中心点坐标 c1 == c2 相等
      p2, c2 = line2 // 中心点坐标 c1 == c2 相等
      c1 = np.array(c1)
      v1 = [p1[0] - c1[0], p1[1] - c1[1]]
      v2 = [p2[0] - c1[0], p2[1] - c2[1]]
      x1, y1 = v1
      x2, y2 = v2
      dot = x1 * x2 + y1 * y2
      det = x1 * y2 - y1 * x2
      theta = np.arctan2(det, dot)
      theta = theta if theta > 0 else 2 * np.pi + theta
      return theta * (180 / np.pi)

你可能感兴趣的:(Opencv-python,opencv,python,计算机视觉)