# Library for minimum bounding box “by width” in JavaScript or Python

I'm looking for a library (or at least a code snippet) to calculate the minimum bounding box "by width" in JavaScript or Python. Below is an illustration from the ArcGIS documentation of that functionality. Ideally the function would give me also the angle, width and height of the bounding box. Any pointers? Image courtesy of the ArcGIS documentation

• OpenCV has a module of that sort docs.opencv.org/modules/imgproc/doc/… – mlai Dec 13 '14 at 3:34
• Thanks for the OpenCV pointer but I believe this function does a "Rectangle by Area" and not a "by width" approach. – Benedikt Groß Dec 13 '14 at 11:45
• Is this what you tried to achieve in JS/Python? gis.stackexchange.com/q/260488/122597 – Stefan Jan 16 '19 at 15:41
• Check out turfjs.org bbox and envelope modules, maybe they fit your needs. – Nick LeBlanc Mar 22 '19 at 1:34
• QGIS has a "Minimum bounding geometry" tool that do exactly that (and a few of the other possibilities) you may have a look at the algorithm it use (it seem to be using python) – J.R May 10 at 15:24

``````import fiona

import fiona.crs

from shapely.geometry import mapping,Polygon

import numpy as np

path = "D:\Python\BuildingInstanceSegmentation\TestShapeFile\TestDHA.shp"

polygons = fiona.open(path)

for idx,feat in enumerate(polygons):
Temp=feat.get('geometry')
TempC=Temp['coordinates']
if idx==0:
MBB=Polygon(TempC).minimum_rotated_rectangle
else:
MBB=MBB.union(Polygon(TempC).minimum_rotated_rectangle)

schema = {
'geometry': 'Polygon',
'properties': {'id': 'int'},
}
crs = fiona.crs.from_epsg(32643)
# Write a new Shapefile
with fiona.open('my_shp2.shp', 'w', 'ESRI Shapefile', crs=crs, schema=schema) as c:
c.write({
'geometry': mapping(MBB),
'properties': {'id': 123},
})
``````
• Thank you but no that is just the RECTANGLE_BY_AREA above, not what was asked for. – bugmenot123 May 9 at 14:52
• it's output is rectangle_by_width. Please check it. it is what is required. thank you. – Rizwan Hassan May 10 at 15:34
• No, your code calculates the minimum rotated rectangle which is not the rectangle the asker wants. They are looking for an enclosing rectangle that is oriented along the longest axis through the geometry. – bugmenot123 May 10 at 16:29