def point_to_pixel_geometry(points, source_epsg=None, target_epsg=None, pixel_side_length=30):
'''
Where points is a list of X,Y tuples and X and Y are coordinates in
meters, returns a series of OGR Polygons where each Polygon is the
pixel extent with a given point at its center. Assumes square pixels.
Arguments:
points Sequence of X,Y numeric pairs or OGR Point geometries
source_epsg The EPSG code of the source projection (Optional)
target_epsg The EPSG code of the target projection (Optional)
pixel_side_length The length of one side of the intended pixel
'''
polys = []
# Convert points to atomic X,Y pairs if necessary
if isinstance(points[0], ogr.Geometry):
points = [(p.GetX(), p.GetY()) for p in points]
source_ref = target_ref = None
if all((source_epsg, target_epsg)):
source_ref = osr.SpatialReference()
target_ref = osr.SpatialReference()
source_ref.ImportFromEPSG(source_epsg)
target_ref.ImportFromEPSG(target_epsg)
transform = osr.CoordinateTransformation(source_ref, target_ref)
for p in points:
r = pixel_side_length / 2 # Half the pixel width
ring = ogr.Geometry(ogr.wkbLinearRing) # Create a ring
vertices = [
(p[0] - r, p[1] + r), # Top-left
(p[0] + r, p[1] + r), # Top-right, clockwise from here...
(p[0] + r, p[1] - r),
(p[0] - r, p[1] - r),
(p[0] - r, p[1] + r) # Add top-left again to close ring
]
# Coordinate transformation
if all((source_ref, target_ref)):
vertices = [transform.TransformPoint(*v)[0:2] for v in vertices]
for vert in vertices:
ring.AddPoint(*vert)
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
polys.append(poly)
return polys
评论列表
文章目录