本文整理汇总了Python中osgeo.gdal.Dataset方法的典型用法代码示例。如果您正苦于以下问题:Python gdal.Dataset方法的具体用法?Python gdal.Dataset怎么用?Python gdal.Dataset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类osgeo.gdal
的用法示例。
在下文中一共展示了gdal.Dataset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: spectra_at_xy
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def spectra_at_xy(rast, xy, gt=None, wkt=None, dd=False):
'''
Returns the spectral profile of the pixels indicated by the longitude-
latitude pairs provided. Arguments:
rast A gdal.Dataset or NumPy array
xy An array of X-Y (e.g., longitude-latitude) pairs
gt A GDAL GeoTransform tuple; ignored for gdal.Dataset
wkt Well-Known Text projection information; ignored for
gdal.Dataset
dd Interpret the longitude-latitude pairs as decimal degrees
Returns a (q x p) array of q endmembers with p bands.
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
gt = rast.GetGeoTransform()
wkt = rast.GetProjection()
rast = rast.ReadAsArray()
# You would think that transposing the matrix can't be as fast as
# transposing the coordinate pairs, however, it is.
return spectra_at_idx(rast.transpose(), xy_to_pixel(xy,
gt=gt, wkt=wkt, dd=dd))
示例2: ogr_copy_layer
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def ogr_copy_layer(src_ds, index, dst_ds, reset=True):
""" Copy OGR.Layer object.
Copy OGR.Layer object from src_ds gdal.Dataset to dst_ds gdal.Dataset
Parameters
----------
src_ds : gdal.Dataset
object
index : int
layer index
dst_ds : gdal.Dataset
object
reset : bool
if True resets src_layer
"""
# get and copy src geometry layer
src_lyr = src_ds.GetLayerByIndex(index)
if reset:
src_lyr.ResetReading()
src_lyr.SetSpatialFilter(None)
src_lyr.SetAttributeFilter(None)
dst_ds.CopyLayer(src_lyr, src_lyr.GetName())
示例3: raster_to_polyvert
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def raster_to_polyvert(dataset):
"""Get raster polygonal vertices from gdal dataset.
Parameters
----------
dataset : gdal.Dataset
raster image with georeferencing (GeoTransform at least)
Returns
-------
polyvert : :class:`numpy:numpy.ndarray`
A N-d array of polygon vertices with shape (..., 5, 2).
"""
rastercoords = read_gdal_coordinates(dataset, mode="edge")
polyvert = georef.grid_to_polyvert(rastercoords)
return polyvert
示例4: open_raster
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def open_raster(filename, driver=None):
"""Open raster file, return gdal.Dataset
Parameters
----------
filename : string
raster file name
driver : string
gdal driver string
Returns
-------
dataset : gdal.Dataset
dataset
"""
dataset = gdal.OpenEx(filename)
if driver:
gdal.GetDriverByName(driver)
return dataset
示例5: get_geo_transform
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def get_geo_transform(raster_src):
"""Get the geotransform for a raster image source.
Arguments
---------
raster_src : str, :class:`rasterio.DatasetReader`, or `osgeo.gdal.Dataset`
Path to a raster image with georeferencing data to apply to `geom`.
Alternatively, an opened :class:`rasterio.Band` object or
:class:`osgeo.gdal.Dataset` object can be provided. Required if not
using `affine_obj`.
Returns
-------
transform : :class:`affine.Affine`
An affine transformation object to the image's location in its CRS.
"""
if isinstance(raster_src, str):
affine_obj = rasterio.open(raster_src).transform
elif isinstance(raster_src, rasterio.DatasetReader):
affine_obj = raster_src.transform
elif isinstance(raster_src, gdal.Dataset):
affine_obj = Affine.from_gdal(*raster_src.GetGeoTransform())
return affine_obj
示例6: as_raster
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def as_raster(path):
'''
A convenience function for opening a raster and accessing its spatial
information; takes a single string argument. Arguments:
path The path of the raster file to open as a gdal.Dataset
'''
ds = gdal.Open(path)
gt = ds.GetGeoTransform()
wkt = ds.GetProjection()
return (ds, gt, wkt)
示例7: cfmask
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def cfmask(mask, mask_values=(1,2,3,4,255), nodata=-9999):
'''
Returns a binary mask according to the CFMask algorithm results for the
image; mask has True for water, cloud, shadow, and snow (if any) and False
everywhere else. More information can be found:
https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment
Landsat 4-7 Pre-Collection pixel_qa values to be masked:
mask_values = (1, 2, 3, 4)
Landsat 4-7 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
mask_values = (1, 68, 72, 80, 112, 132, 136, 144, 160, 176, 224)
Landsat 8 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
mask_values = (1, 324, 328, 386, 388, 392, 400, 416, 432, 480, 832, 836, 840, 848, 864, 880, 900, 904, 912, 928, 944, 992, 1024)
Arguments:
mask A gdal.Dataset or a NumPy array
mask_path The path to an EOS HDF4 CFMask raster
mask_values The values in the mask that correspond to NoData pixels
nodata The NoData value; defaults to -9999.
'''
if not isinstance(mask, np.ndarray):
maskr = mask.ReadAsArray()
else:
maskr = mask.copy()
# Mask according to bit-packing described here:
# https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment
maskr = np.in1d(maskr.reshape((maskr.shape[0] * maskr.shape[1])), mask_values)\
.reshape((1, maskr.shape[0], maskr.shape[1])).astype(np.int0)
return maskr
示例8: clean_mask
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def clean_mask(rast):
'''
Clips the values in a mask to the interval [0, 1]; values larger than 1
become 1 and values smaller than 0 become 0.
Arguments:
rast An input gdal.Dataset or numpy.array instance
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
rastr = rast.ReadAsArray()
else:
rastr = rast.copy()
return np.clip(rastr, a_min=0, a_max=1)
示例9: copy_nodata
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def copy_nodata(source, target, nodata=-9999):
'''
Copies the NoData values from a source raster or raster array into a
target raster or raster array. That is, source's NoData values are
embedded in target. This is useful, for instance, when you want to mask
out dropped scanlines in a Landsat 7 image; these areas are NoData in the
EOS HDF but they are not included in the QA mask. Arguments:
source A gdal.Dataset or a NumPy array
target A gdal.Dataset or a NumPy array
nodata The NoData value to look for (and embed)
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(source, np.ndarray):
source = source.ReadAsArray()
if not isinstance(target, np.ndarray):
target = target.ReadAsArray()
else:
target = target.copy()
assert source.ndim == target.ndim, "Source and target rasters must have the same number of axes"
if source.ndim == 3:
assert source.shape[1:] == target.shape[1:], "Source and target rasters must have the same shape (not including band axis)"
return np.where(source[0,...] == nodata, nodata, target)
else:
assert source.shape == target.shape, "Source and target rasters must have the same shape"
return np.where(source == nodata, nodata, target)
示例10: dump_raster
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def dump_raster(rast, rast_path, driver='GTiff', gdt=None, nodata=None):
'''
Creates a raster file from a given gdal.Dataset instance. Arguments:
rast A gdal.Dataset; does NOT accept NumPy array
rast_path The path of the output raster file
driver The name of the GDAL driver to use (determines file type)
gdt The GDAL data type to use, e.g., see gdal.GDT_Float32
nodata The NoData value; defaults to -9999.
'''
if gdt is None:
gdt = rast.GetRasterBand(1).DataType
driver = gdal.GetDriverByName(driver)
sink = driver.Create(
rast_path, rast.RasterXSize, rast.RasterYSize, rast.RasterCount, int(gdt))
assert sink is not None, 'Cannot create dataset; there may be a problem with the output path you specified'
sink.SetGeoTransform(rast.GetGeoTransform())
sink.SetProjection(rast.GetProjection())
for b in range(1, rast.RasterCount + 1):
dat = rast.GetRasterBand(b).ReadAsArray()
sink.GetRasterBand(b).WriteArray(dat)
sink.GetRasterBand(b).SetStatistics(*map(np.float64,
[dat.min(), dat.max(), dat.mean(), dat.std()]))
if nodata is None:
nodata = rast.GetRasterBand(b).GetNoDataValue()
if nodata is None:
nodata = -9999
sink.GetRasterBand(b).SetNoDataValue(np.float64(nodata))
sink.FlushCache()
示例11: mask_by_query
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def mask_by_query(rast, query, invert=False, nodata=-9999):
'''
Mask pixels (across bands) that match a query in any one band or all
bands. For example: `query = rast[1,...] < -25` queries those pixels
with a value less than -25 in band 2; these pixels would be masked
(if `invert=False`). By default, the pixels that are queried are
masked, but if `invert=True`, the query serves to select pixels NOT
to be masked (`np.invert()` can also be called on the query before
calling this function to achieve the same effect). Arguments:
rast A gdal.Dataset or numpy.array instance
query A NumPy boolean array representing the result of a query
invert True to invert the query
nodata The NoData value to apply in the masking
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
rastr = rast.ReadAsArray()
else:
rastr = rast.copy()
shp = rastr.shape
if query.shape != rastr.shape:
assert len(query.shape) == 2 or len(query.shape) == len(shp), 'Query must either be 2-dimensional (single-band) or have a dimensionality equal to the raster array'
assert shp[-2] == query.shape[-2] and shp[-1] == query.shape[-1], 'Raster and query must be conformable arrays in two dimensions (must have the same extent)'
# Transform query into a 1-band array and then into a multi-band array
query = query.reshape((1, shp[-2], shp[-1])).repeat(shp[0], axis=0)
# Mask out areas that match the query
if invert:
rastr[np.invert(query)] = nodata
else:
rastr[query] = nodata
return rastr
示例12: saturation_mask
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def saturation_mask(rast, saturation_value=10000, nodata=-9999):
'''
Returns a binary mask that has True for saturated values (e.g., surface
reflectance values greater than 16,000, however, SR values are only
considered valid on the range [0, 10,000]) and False everywhere else.
Arguments:
rast A gdal.Dataset or NumPy array
saturation_value The value beyond which pixels are considered
saturated
nodata The NoData value; defaults to -9999.
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
rastr = rast.ReadAsArray()
else:
rastr = rast.copy()
# Create a baseline "nothing is saturated in any band" raster
mask = np.empty((1, rastr.shape[1], rastr.shape[2]))
mask.fill(False)
# Update the mask for saturation in any band
for i in range(rastr.shape[0]):
np.logical_or(mask, rastr[i,...] > saturation_value, out=mask)
return mask
示例13: subarray
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def subarray(rast, filtered_value=-9999, indices=False):
'''
Given a (p x m x n) raster (or array), returns a (p x z) subarray where
z is the number of cases (pixels) that do not contain the filtered value
(in any band, in the case of a multi-band image). Arguments:
rast The input gdal.Dataset or a NumPy array
filtered_value The value to remove from the raster array
indices If True, return a tuple: (indices, subarray)
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
rastr = rast.ReadAsArray()
else:
rastr = rast.copy()
shp = rastr.shape
if len(shp) == 1:
# If already raveled
return rastr[rastr != filtered_value]
if len(shp) == 2 or shp[0] == 1:
# If a "single-band" image
arr = rastr.reshape(1, shp[-2]*shp[-1])
return arr[arr != filtered_value]
# For multi-band images
arr = rastr.reshape(shp[0], shp[1]*shp[2])
idx = (arr != filtered_value).any(axis=0)
if indices:
# Return the indices as well
rast_shp = (shp[-2], shp[-1])
return (np.indices(rast_shp)[:,idx.reshape(rast_shp)], arr[:,idx])
return arr[:,idx]
示例14: normalize_reflectance_within_image
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def normalize_reflectance_within_image(
rast, band_range=(0, 5), nodata=-9999, scale=100):
'''
Following Wu (2004, Remote Sensing of Environment), normalizes the
reflectances in each pixel by the average reflectance *across bands.*
This is an attempt to mitigate within-endmember variability. Arguments:
rast A gdal.Dataset or numpy.array instance
nodata The NoData value to use (and value to ignore)
scale (Optional) Wu's definition scales the normalized reflectance
by 100 for some reason; another reasonable value would
be 10,000 (approximating scale of Landsat reflectance units);
set to None for no scaling.
'''
# Can accept either a gdal.Dataset or numpy.array instance
if not isinstance(rast, np.ndarray):
rastr = rast.ReadAsArray()
else:
rastr = rast.copy()
shp = rastr.shape
b0, b1 = band_range # Get the beginning, end of band range
b1 += 1 # Ranges in Python are not inclusive, so add 1
rastr_normalized = np.divide(
rastr.reshape((shp[0], shp[1]*shp[2])),
rastr[b0:b1,...].mean(axis=0).reshape((1, shp[1]*shp[2])).repeat(shp[0], axis=0))
# Recover original shape; scale if necessary
rastr_normalized = rastr_normalized.reshape(shp)
if scale is not None:
rastr_normalized = np.multiply(rastr_normalized, scale)
# Fill in the NoData areas from the original raster
np.place(rastr_normalized, rastr == nodata, nodata)
return rastr_normalized
示例15: test_file_raster_and_array_access
# 需要导入模块: from osgeo import gdal [as 别名]
# 或者: from osgeo.gdal import Dataset [as 别名]
def test_file_raster_and_array_access(self):
'''
Tests that essential file reading and raster/array conversion utilities
are working properly.
'''
from_as_array = as_array(os.path.join(self.test_dir, 'multi3_raster.tiff'))
from_as_raster = as_raster(os.path.join(self.test_dir, 'multi3_raster.tiff'))
self.assertTrue(len(from_as_array) == len(from_as_raster) == 3)
self.assertTrue(isinstance(from_as_array[0], np.ndarray))
self.assertTrue(isinstance(from_as_raster[0], gdal.Dataset))