# Removing thin rectangles from a shapely polygon

I am detecting rooftops and output them as shapley polygons in square, U and L shape. Sometimes the output is in U shape with a very thin rectangle on one side ( true shape is L shape) which needs to be cleaned. I have tried using perimeter/area ratio to detect such parts of a polygon and remove them but I am not able to implement it. An example is shown in figure below.

I am looking for a solution preferably with shapely.

The polygon in the example in GEOJSON can be found here.

• All thin rectangles have almost same thickness? Apr 23, 2018 at 13:54
• No, it can vary and I need to detect when it is highly unlikely to be a part of rooftop. Apr 24, 2018 at 15:12

If small changes in the shape that cannot be visually detected are not important, try this way:

``````from shapely.geometry import shape

test = {"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[6.980710220282101, 51.243221513354044], [6.980706911073409, 51.24322119551712], [6.9806699432069745, 51.24337283218559], [6.980864165775662, 51.24339148636556], [6.980901140490866, 51.24323981899073], [6.980795641198141, 51.24322968631755], [6.980776365429034, 51.243308752807856], [6.980690951372498, 51.243300549145346], [6.980710220282101, 51.243221513354044]]]}}]}
poly = shape(test["features"][0]["geometry"])

d = 0.00001 # distance
cf = 1.3  # cofactor
p = poly.buffer(-d).buffer(d*cf).intersection(poly).simplify(d)
``````

You may need to change `d` and `cf` values. This is not a perfect solution but it can solve your thin rectangle problem by small changes.