def Geometry(*args, **kwargs): """Returns an ogr.Geometry instance optionally created from a geojson str or dict. The spatial reference may also be provided. """ # Look for geojson as a positional or keyword arg. arg = kwargs.pop('geojson', None) or len(args) and args[0] try: srs = kwargs.pop('srs', None) or arg.srs.wkt except AttributeError: srs = SpatialReference(4326) if hasattr(arg, 'keys'): geom = ogr.CreateGeometryFromJson(json.dumps(arg)) elif hasattr(arg, 'startswith'): if arg.startswith('{'): geom = ogr.CreateGeometryFromJson(arg) # WKB as hexadecimal string. elif ord(arg[0]) in [0, 1]: geom = ogr.CreateGeometryFromWkb(arg) elif arg.startswith('<gml'): geom = ogr.CreateGeometryFromGML(arg) elif hasattr(arg, 'wkb'): geom = ogr.CreateGeometryFromWkb(bytes(arg.wkb)) else: geom = ogr.Geometry(*args, **kwargs) if geom: if not isinstance(srs, SpatialReference): srs = SpatialReference(srs) geom.AssignSpatialReference(srs) return geom
def test_proj4(self): p4 = SpatialReference(2805).ExportToProj4() from_proj4 = SpatialReference(p4) self.assertEqual(from_proj4.proj4, p4) p4 = ('+proj=aea +lat_1=20 +lat_2=60 +lat_0=40 +lon_0=-96 +x_0=0 ' '+y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ') sref = SpatialReference(p4) self.assertEqual(sref.proj4, p4) # Spatial ref with no EPSG code defined is None. self.assertIs(sref.srid, None)
def test_serialize_queryset(self): serializer = RasterStoreSerializer(self.qs, many=True) data = serializer.data[0] self.assertEqual(data['image'], self.qs[0].image.name) expected = { 'geom': {'type': 'Polygon', 'coordinates': (((-120.0, 28.0), (-110.0, 28.0), (-110.0, 38.0), (-120.0, 38.0), (-120.0, 28.0)),)}, 'minval': 0.0, 'maxval': 24.0, 'nodata': None } self.assertEqual(SpatialReference(data['srs']), SpatialReference(4326)) self.assertDictContainsSubset(expected, data)
def SetProjection(self, sref): """Sets the spatial reference. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: sref -- SpatialReference or any format supported by the constructor """ if not hasattr(sref, 'ExportToWkt'): sref = SpatialReference(sref) self._sref = sref self.ds.SetProjection(sref.ExportToWkt())
def test_init_spatialref(self): epsg_id = 4326 sref = SpatialReference(epsg_id) geom = Geometry(self.gdict, srs=epsg_id) self.assertEqual(geom.GetSpatialReference(), sref) geom = Geometry(self.gdict, srs=sref) self.assertEqual(geom.GetSpatialReference(), sref)
def __init__(self, path, mode=gdalconst.GA_ReadOnly): """Initialize a Raster data set from a path or file Arguments: path -- path as str, file object, or gdal.Dataset Keyword args: mode -- gdal constant representing access mode """ if path and not isinstance(path, gdal.Dataset): # Get the name if we have a file-like object. dataset = gdal.Open(getattr(path, 'name', path), mode) else: dataset = path if not dataset: raise IOError('Failed to open: "%s"' % path) self.ds = dataset self.name = self.ds.GetDescription() # Bands are not zero based, available bands are a 1-based list of ints. self.bandlist = range(1, len(self) + 1) # Initialize attrs without calling their setters. self._affine = AffineTransform(*dataset.GetGeoTransform()) self._sref = SpatialReference(dataset.GetProjection()) #self.dtype = gdal_array.codes[self[0].DataType] self._nodata = None self._envelope = None self._driver = None self.closed = False # Closes the gdal.Dataset dataset = None
def warp(self, to_sref, dest=None, interpolation=gdalconst.GRA_NearestNeighbour): """Returns a new reprojected instance. Arguments: to_sref -- spatial reference as a proj4 or wkt string, or a SpatialReference Keyword args: dest -- filepath as str interpolation -- GDAL interpolation type """ if not hasattr(to_sref, 'ExportToWkt'): to_sref = SpatialReference(to_sref) dest_wkt = to_sref.ExportToWkt() dtype = self[0].DataType err_thresh = 0.125 # Determine new values for destination raster dimensions and # geotransform. vrt = gdal.AutoCreateWarpedVRT(self.ds, None, dest_wkt, interpolation, err_thresh) if vrt is None: raise ValueError('Could not warp %s to %s' % (self, dest_wkt)) warpsize = (vrt.RasterXSize, vrt.RasterYSize, len(self)) warptrans = vrt.GetGeoTransform() vrt = None if dest is None: imgio = MemFileIO() rwarp = self.driver.raster(imgio, warpsize, dtype) imgio.close() else: rwarp = self.driver.raster(dest, warpsize, dtype) rwarp.SetGeoTransform(warptrans) rwarp.SetProjection(to_sref) if self.nodata is not None: for band in rwarp: band.SetNoDataValue(self.nodata) band = None # Uses self and rwarp projection when set to None gdal.ReprojectImage(self.ds, rwarp.ds, None, None, interpolation) return rwarp
def to_internal_value(self, data): if sc.has_features(data): for feat in data['features']: return self.to_internal_value(feat) try: sref = SpatialReference(data['crs']['properties']['name']) except KeyError: sref = None # Force evaluation of fields property. if not self.fields and self.Meta.geom_field is None: raise exceptions.FieldDoesNotExist('Geometry field not found') record = {self.Meta.geom_field: data.get('geometry')} record.update(data.get('properties', {})) feature = super(FeatureSerializer, self).to_internal_value(record) if feature and sref: geom = feature[self.Meta.geom_field] geom.srid = sref.srid return feature
def srs(self): try: return SpatialReference(self['crs']['properties']['name']) except KeyError: return None
def test_transform_mask(self): sref = SpatialReference(3857) tr = transform(self.geom.ExportToWkb(), sref) self.assertEqual(tr.GetSpatialReference(), sref)
def test_wkt(self): sref = SpatialReference(osr.SRS_WKT_WGS84) self.assertEqual(sref.wkt, osr.SRS_WKT_WGS84) self.assertEqual(str(sref), osr.SRS_WKT_WGS84) wkt = unicode(osr.SRS_WKT_WGS84) self.assertEqual(str(SpatialReference(wkt)), wkt)
def test_equality(self): self.assertEqual(SpatialReference(3857), SpatialReference(3857)) self.assertNotEqual(SpatialReference(4326), SpatialReference(3857))
def test_named_crs(self): self.assertEqual( SpatialReference('urn:ogc:def:crs:OGC:1.3:CRS84').srid, 4326)
def test_epsg_strings(self): self.assertEqual(SpatialReference('EPSG:4269').srid, 4269) self.assertEqual(SpatialReference('4269').srid, 4269)
def test_epsg(self): epsg_id = 3310 from_epsg = SpatialReference(epsg_id) self.assertEqual(from_epsg.srid, epsg_id) self.assertEqual(SpatialReference().srid, None)