Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get center of a square based on the 4 corners

I have a problem with my code, which should give me the center of a square. The square is saved as it's corners in an double[][] array.

static double[] getMid(double[][] points){
    double[] mid = new double[2];
    double a = Math.sqrt( (points[0][0] - points[1][0]) * (points[0][0] - points[1][0]) 
                        + (points[0][1] - points[1][1]) * (points[0][1] - points[1][1]) );
    a/=2;
    double c = a / Math.sin(Math.toRadians(45));

    mid[0] = Math.sin(Math.toRadians(45)) * c + points[1][0];
    mid[1] = Math.cos(Math.toRadians(45)) * c + points[1][1];

    StdDraw.point(mid[0], mid[1]);

    return mid;
}

My initial idea was to calculate the distance of the center and the corner and then calculate the centerpoint with the distance and the angle. This works fine when the square is in a normal position, but once it's rotated the center is way off.

The dots represent the calculated centers.

The dots represent the calculated centers.

like image 339
Julian Veerkamp Avatar asked Oct 24 '25 06:10

Julian Veerkamp


2 Answers

I think the code is much too complicate for what it does. If you know the figure is a square, all you need to do to find the centre is compute the midpoint between any two opposite corners.

mid[0] = (points[0][0] + points[2][0]) / 2;
mid[1] = (points[0][1] + points[2][1]) / 2;
like image 159
NPE Avatar answered Oct 26 '25 18:10

NPE


Because it's a square, you can find the center by taking the average of the x coordinates of the corners, and then take the average of the y coordinates of the corners. This will give you the x and y coordinates of the center of the square. I believe this also works for rectangles.

like image 45
shieldgenerator7 Avatar answered Oct 26 '25 20:10

shieldgenerator7