# How to calculate the Oriented Bounding Box (OBB) of a polygon or point set?

I'd like to calculate the "Oriented Bounding Box" (OBB) which is the enclosing rectangle aligned to the longest extent of a point set (which is not necessarily aligned with the axes of the co-ordinate system).

The solution could be similar to Finding minimum-area-rectangle for given points? but I'm looking for a robust solution in PostGIS SQL (and PL/Python if necessary).

• That's a hard one.. I've done it for polygons in C# (or was the VB.net?) but not for points. You could start with a convex hull and find the longest axis I suppose. Do you have any other geometry tools available or just python/PostGIS? What part of the linked question isn't suitable? – Michael Stimson Feb 6 '15 at 0:36
• I'm looking for a fast implementation in PL/pgSQL and tought to reuse ST_ConvexHull(). – Stefan Feb 6 '15 at 0:52
• From the Convex Hull do some rotations and pick the smallest box to cover all the points. The hull (geometry) might have an extent property which is already the bounding box then it's a matter of recording the dimensions and angle, picking the smallest box and rotating the central line using the reverse matrix. – Michael Stimson Feb 6 '15 at 0:58
• Centre of the envelope is ( XMax + XMin ) / 2, ( YMax + YMin ) / 2. Rotation with a matrix will allow rotation more than 90 deg - I wouldn't assume symmetry as your points may not be symmetric around the centre point. – Michael Stimson Feb 6 '15 at 1:18
• Ok. But I still think there's potential for optimization, especially for avoiding to rotate 360 degrees. What about starting with ST_LongestLine (using the same geometry twice as input, as mentioned in linked question)? Then, only +/- 90 degrees need to be rotated? – Stefan Feb 7 '15 at 14:39

This seems to be peanuts for JTS. Let's hope that the method is ported into GEOS so that you can enjoy from it with Python and PostGIS.

JTS has a minimum diameter method tsusiatsoftware.net/jts/javadoc/com/vividsolutions/jts/… that can also directly return "the minimum rectangular Polygon which encloses the input geometry". Convert you point set into multipoint and run the function. But based on your screen capture you may have a polygon to start with, and that you can use directly as input.

I just was pointed to an answer by Rémi-C over at PostGIS mailinglist. He wrote:

"Here is a working solution in plpgsql, designed to be fast to code (and slow to execute :-/)"

https://github.com/Remi-C/PPPP_utilities/blob/6e9e8524812961b013b899466fe833dfa5d926e9/postgis/rc_oriented_bbox_deom_axis.sql

That function rc_BboxOrientedFromGeom(geom) does the job in PL/pgsql. Thanks to Rémi-C!

As he said and as I suggested above, most probably there exist more efficient solutions.