This is not too complicated.
Sort all edges in the direction. Look for a pair of ribs in one direction with the rotation of the other pair 90 degrees. Check the approximate proximity. If so, they probably form a rectangle. Check the distance between the edges to select squares from the rectangles and discard small squares. Check to see if you have large enough parts of the edge to make sure that the entire edge must exist. It is possible that the edge can be split into 2. Check if 4 edges are now found that have a fairly uniform area.
The last bit is a bit more complicated. This domain knows. Can there be other objects inside the square, and can they touch or overlap the edges of the square?
source share