Monday, 2 May 2016

python - Equivalent function to shapely's envelope in ogr?


I wrote a very simple python function that gives me the envelope/bounding box/...based on two coordinate pairs (ower left and upper right corner):


# ...

def get_bounding_box(self, ll_corner, ur_corner):
try:
from shapely.geometry import MultiPoint
mp_env = MultiPoint([ll_corner, ur_corner]).envelope
return ogr.CreateGeometryFromWkt( mp_env.to_wkt() )

print mp_env
POLYGON ((4.8439699999999997 52.3661099999999990, 4.8469199999999999 52.3661099999999990, 4.8469199999999999 52.3706000000000031, 4.8439699999999997 52.3706000000000031, 4.8439699999999997 52.3661099999999990))

As you can see I'm returning an ogr geometry which I use, for instance, in this manner:



bbox = geo.get_bounding_box(lowerleft,upper_right) 
...
p=ogr.Geometry(ogr.wkbPoint)
p.AddPoint(x,y)
if p.Within(bbox):
....

Isn't there an equivalent function to shapely's envelope in ogr? Both .ConvexHull() and GetEnvelope() return only the two corner coordinate pairs.



Answer



The Ogr function GetEnvelope() returns "a tuple (minX, maxX, minY, maxY)" (from here), but what you want (from what I can understand) is a Polygon describing the envelope/bbox?



This is actually rather simple, as the tuple (minX, maxX, minY, maxY) is all you need to create a Polygon.


Just create a Polygon based these, like so:


from osgeo import ogr

def my_envelope(geom):
(minX, maxX, minY, maxY) = geom.GetEnvelope()

# Create ring
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(minX, minY)

ring.AddPoint(maxX, minY)
ring.AddPoint(maxX, maxY)
ring.AddPoint(minX, maxY)
ring.AddPoint(minX, minY)

# Create polygon
poly_envelope = ogr.Geometry(ogr.wkbPolygon)
poly_envelope.AddGeometry(ring)
return poly_envelope

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...