Search code examples
pythonpython-3.xpython-2.7pointrectangles

How to check if centroid of one rectangle is present inside another rectangle?


I have a rectangle ABCD. I divide the rectangle into 9 equal parts by dividing the height and breadth by 3. Now I got 9 rectangles. If I consider one among these 9 rectangles ABCD_1 with coordinates = 166, 104, 332, 156. In addition to this I have another rectangle say PQRS whose centroid = 377.5, 489.0. I want to determine if the given centroid is present inside the rectangle ABCD_1. How to solve this.

I am a complete beginner in Python. Any help would be much appreciable. Thanks!!!


Solution

  • Assuming your rectangle coordinates are represented as an array [x1,y1,y2,x2] and point as [x,y] then we will first check if x lies between the x coordinates of the rectangle and if yes then we'll check if they lie between y coordinates if true then the point lies inside the rectangle else doesn't. below abcd is your rectangle and p is the point.

    abcd=[166, 104, 332, 156]
    p=[377.5, 489.0]
    
    if p[0]>=abcd[0] and p[0]<=abcd[3]:
        if p[1]>=abcd[1] and p[0]<=abcd[2]:
            print('Inside')
    else:
        print('Outside')