2線分の交点

2019/01/16

Python2.7.8

# -*- coding: utf-8 -*-

def intersection_line_segments((p0,p1),(p2,p3)): #p=(x,y)
    d = float((p1[0]-p0[0])*(p3[1]-p2[1])-(p1[1]-p0[1])*(p3[0]-p2[0]))
    if d == 0:
        return False
    ac = (p2[0]-p0[0],p2[1]-p0[1])
    t0 = ((p3[1]-p2[1])*ac[0] - (p3[0]-p2[0])*ac[1]) / d
    t1 = ((p1[1]-p0[1])*ac[0] - (p1[0]-p0[0])*ac[1]) / d
    if t0 < 0 or 1 < t0:
        return False
    if t1 < 0 or 1 < t1:
        return False
    x = p0[0] + t0*(p1[0] - p0[0])
    y = p0[1] + t0*(p1[1] - p0[1])
    p = [x,y,t0,t1]
    return p

def main():
    import Tkinter
    window = Tkinter.Tk()
    canvas = Tkinter.Canvas(window,width=300,height=200)
    canvas.pack()

    line_seg0 = [[20,20],[290,90]]
    line_seg1 = [[80,190],[290,50]]
    r = 3
    for p0,p1 in [line_seg0,line_seg1]:
        canvas.create_line(p0[0],p0[1],p1[0],p1[1])

    cp = intersection_line_segments(line_seg0,line_seg1)
    if cp:
        canvas.create_oval(cp[0]-r,cp[1]-r,cp[0]+r,cp[1]+r)

    window.mainloop()

if __name__ == '__main__':
    main()

2線分の交点 https://www.hiramine.com/programming/graphics/2d_segmentintersection.html