python-3.xopencvdeep-learningcomputer-visionintrusion-detection

How to identify if the centroid point touches a line or not?


I am working with an intrusion detection algorithm which works on the basis of line crossing detection. I have developed a basic algorithm using the equation y = mx+c, but it is showing some wrong detection when the person reaches nearer to the line. I need some suggestion for making it a perfect line touching algorithm.

enter image description here

enter image description here


Solution

  • If your line has starting and ending points [x1, y1] and [x2, y2], then the line equation is:

    y - y1 = m * (x - x1), where m = (y2 - y1)/(x2-x1)

    Then you can check if a point belongs to the line or not, substituting either x or y, and checking if the other matches the line equation.

    In Pyhton:

    # the two points that define the line
    p1 = [1, 6]
    p2 = [3, 2]
    
    # extract x's and y's, just for an easy code reading
    x1, y1 = p1
    x2, y2 = p2
    
    m = (y2-y1)/(x2-x1)
    
    # your centroid
    centroid = [2,4]
    x3, y3 = centroid
    
    # check if centroid belongs to the line
    if (m * (x3-x1) + y1) == y3:
        print("Centroid belongs to line")
    
    

    But probably...

    ...you'll have better results calculating the distance between red dot and the line (distance from a point to a line), and then checking if it is near enough (i.e. distance less than some value).

    In Python:

    # points that define the line
    p1 = [1, 6]
    p2 = [3, 2]
    x1, y1 = p1
    x2, y2 = p2
    
    centroid = [2,4]
    x3, y3 = centroid
    
    # distance from centroid to line
    import math # to calculate square root
    dist = abs((y2-y1)*x3 - (x2-x1)*y3 + x2*y1 - y2*x1)/math.sqrt((y2-y1)**2 + (x2-x1)**2)
    
    if dist < some_value:
        print("Near enough")