def from_array(cls, raster, geo_transform, proj4,
gdal_dtype=gdal.GDT_Float32, nodata=None):
""" Create a georaster object from numpy array and georeferencing information.
:param raster: 2-D NumPy array of raster to load
:type raster: np.array
:param geo_transform: a Geographic Transform tuple of the form \
(top left x, w-e cell size, 0, top left y, 0, n-s cell size (-ve))
:type geo_transform: tuple
:param proj4: a proj4 string representing the raster projection
:type proj4: str
:param gdal_dtype: a GDAL data type (default gdal.GDT_Float32)
:type gdal_dtype: int
:param nodata: None or the nodata value for this array
:type nodata: None, int, float, str
:returns: GeoRaster object
:rtype: GeoRaster
"""
if len(raster.shape) > 2:
nbands = raster.shape[2]
else:
nbands = 1
# Create a GDAL memory raster to hold the input array
mem_drv = gdal.GetDriverByName('MEM')
source_ds = mem_drv.Create('', raster.shape[1], raster.shape[0],
nbands, gdal_dtype)
# Set geo-referencing
source_ds.SetGeoTransform(geo_transform)
srs = osr.SpatialReference()
srs.ImportFromProj4(proj4)
source_ds.SetProjection(srs.ExportToWkt())
# Write input array to the GDAL memory raster
for b in range(0,nbands):
if nbands > 1:
r = raster[:,:,b]
else:
r = raster
source_ds.GetRasterBand(b+1).WriteArray(r)
if nodata != None:
source_ds.GetRasterBand(b+1).SetNoDataValue(nodata)
# Return a georaster instance instantiated by the GDAL raster
return cls(source_ds)
评论列表
文章目录