Python-opencv calculates the angle of two straight lines or line segments

Python-opencv calculates the angle of two straight lines or line segments

method one

Calculated through the slope relationship, the formula is as follows:
Insert image description here
Be careful not to appear vertical when calculating the slope. Python calculations will report an error, but it should be possible to calculate infinite. Let’s leave it here for now. I will explain it later when I have time. reason.

#openpose求角度
def GetAngle(line1, line2):
    """
    计算两条线段之间的夹角,若已知两直线斜率:m1,m2
     angle = atan(abs((m2 - m1) / (1 + (m2 * m1)))
    :param line1:
    :param line2:
    :return:
    """
    dx1 = line1[0][0] - line1[1][0]
    dy1 = line1[0][1] - line1[1][1]
    dx2 = line2[0][0] - line2[1][0]
    dy2 = line2[0][1] - line2[1][1]

    #求斜率
    m1=dy1/dx1
    m2=dy2/dx2
    insideAngle=math.atan(abs((m2-m1)/(1+(m1*m2))))

    angle=insideAngle/math.pi*180
    if angle>-370 and angle<370:
        angle=int(angle)

    return angle

Method Two:

#openpose求角度
def GetAngle(line1, line2):
    """
    计算两条线段之间的夹角
    :param line1:
    :param line2:
    :return:
    """
    dx1 = line1[0][0] - line1[1][0]
    dy1 = line1[0][1] - line1[1][1]
    dx2 = line2[0][0] - line2[1][0]
    dy2 = line2[0][1] - line2[1][1]
    angle1 = math.atan2(dy1, dx1)
    angle1 = int(angle1 * 180 / math.pi)
    # print(angle1)
    angle2 = math.atan2(dy2, dx2)
    angle2 = int(angle2 * 180 / math.pi)
    # print(angle2)
    if angle1 * angle2 >= 0:
        insideAngle = abs(angle1 - angle2)
    else:
        insideAngle = abs(angle1) + abs(angle2)
        if insideAngle > 180:
            insideAngle = 360 - insideAngle
    insideAngle = insideAngle % 180
    return insideAngle

Method three

Calculate the angle of three points through the cosine theorem:
Insert image description here
If the three sides are a, b, c, then as shown in the figure, in △ABC:
Insert image description here
Prerequisite for use: Do not have 0 in the denominator.

Implementation: form a triangle through three points, first calculate the length of each side, and then use the cosine formula to solve the angle

def DIST(p1,p2):
    '''
    func:求两点间距离
    @para p1,p2:点坐标(x1,y1),(x2,y2)
    @para return:距离
    '''
    return math.sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1]))


# #openpose求角度
def GetAngle(p1,p2,p3):
    """
    若已知3点,求以中间点为原点的夹角
    :param p1,p2,p3:点坐标(x,y)
    :param return: 角度
    """
    #余弦定理求夹角
    A=DIST(p1,p2)
    B=DIST(p2,p3)
    C=DIST(p1,p3)

    angle=math.acos((A*A+B*B-C*C)/(2*A*B))
    return angle/math.pi*180

Guess you like

Origin blog.csdn.net/yohnyang/article/details/127600867