def resample(self, new_cellsize, method='bilinear'): """ Resample the raster object to a new resolution Args: new_cellsize: scalar, the resoltion of the new raster object method: string, one of the values including 'nearest', 'bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'gauss', 'max', 'min', 'med', 'q1', 'q3' Return: Raster object """ from rasterio.enums import Resampling method_list = [ 'nearest', 'bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'gauss', 'max', 'min', 'med', 'q1', 'q3' ] ind = method_list.index(method) upscale_factor = self.cellsize / new_cellsize ds_rio = self.to_rasterio_ds() new_shape = (1, int(ds_rio.height * upscale_factor), int(ds_rio.width * upscale_factor)) resampling_method = Resampling(ind) data = ds_rio.read(out_shape=new_shape, resampling=resampling_method) data = data[0] # scale image transform transform = ds_rio.transform * ds_rio.transform.scale( (ds_rio.width / data.shape[-1]), (ds_rio.height / data.shape[-2])) ds_rio.close() new_header = copy.deepcopy(self.header) new_header['cellsize'] = new_cellsize new_header['nrows'] = data.shape[0] new_header['ncols'] = data.shape[1] new_header['xllcorner'] = transform[2] new_header['yllcorner'] = transform[5] - data.shape[0] * new_cellsize obj_new = Raster(array=data, header=new_header) if hasattr(self, 'crs'): obj_new.crs = self.crs return obj_new
def reproject(source, destination, src_transform=None, gcps=None, src_crs=None, src_nodata=None, dst_transform=None, dst_crs=None, dst_nodata=None, resampling=Resampling.nearest, init_dest_nodata=True, **kwargs): """Reproject a source raster to a destination raster. If the source and destination are ndarrays, coordinate reference system definitions and affine transformation parameters or ground control points (gcps) are required for reprojection. If the source and destination are rasterio Bands, shorthand for bands of datasets on disk, the coordinate reference systems and transforms or GCPs will be read from the appropriate datasets. Parameters ------------ source, destination: ndarray or Band The source and destination are 2 or 3-D ndarrays, or a single or multiple Rasterio Band object. The dimensionality of source and destination must match, i.e., for multiband reprojection the lengths of the first axes of the source and destination must be the same. src_transform: affine.Affine(), optional Source affine transformation. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. An error will be raised if this parameter is defined together with gcps. gcps: sequence of GroundControlPoint, optional Ground control points for the source. An error will be raised if this parameter is defined together with src_transform. src_crs: CRS or dict, optional Source coordinate reference system, in rasterio dict format. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. Example: CRS({'init': 'EPSG:4326'}) src_nodata: int or float, optional The source nodata value.Pixels with this value will not be used for interpolation. If not set, it will be default to the nodata value of the source image if a masked ndarray or rasterio band, if available. dst_transform: affine.Affine(), optional Target affine transformation. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_crs: CRS or dict, optional Target coordinate reference system. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_nodata: int or float, optional The nodata value used to initialize the destination; it will remain in all areas not covered by the reprojected source. Defaults to the nodata value of the destination image (if set), the value of src_nodata, or 0 (GDAL default). resampling: int Resampling method to use. One of the following: Resampling.nearest, Resampling.bilinear, Resampling.cubic, Resampling.cubic_spline, Resampling.lanczos, Resampling.average, Resampling.mode, Resampling.max (GDAL >= 2.2), Resampling.min (GDAL >= 2.2), Resampling.med (GDAL >= 2.2), Resampling.q1 (GDAL >= 2.2), Resampling.q3 (GDAL >= 2.2) An exception will be raised for a method not supported by the running version of GDAL. init_dest_nodata: bool Flag to specify initialization of nodata in destination; prevents overwrite of previous warps. Defaults to True. kwargs: dict, optional Additional arguments passed to transformation function. Returns --------- out: None Output is written to destination. """ if src_transform and gcps: raise ValueError("src_transform and gcps parameters may not" "be used together.") # Resampling guard. try: if resampling == 7: # gauss resampling is not supported raise ValueError Resampling(resampling) except ValueError: raise ValueError("resampling must be one of: {0}".format(", ".join( ['Resampling.{0}'.format(r.name) for r in SUPPORTED_RESAMPLING]))) # If working with identity transform, assume it is crs-less data # and that translating the matrix very slightly will avoid #674 eps = 1e-100 if src_transform: src_transform = guard_transform(src_transform) # if src_transform is like `identity` with positive or negative `e`, # translate matrix very slightly to avoid #674 and #1272. if src_transform.almost_equals( identity) or src_transform.almost_equals( Affine(1, 0, 0, 0, -1, 0)): src_transform = src_transform.translation(eps, eps) if dst_transform: dst_transform = guard_transform(dst_transform) if dst_transform.almost_equals( identity) or dst_transform.almost_equals( Affine(1, 0, 0, 0, -1, 0)): dst_transform = dst_transform.translation(eps, eps) if src_transform: src_transform = guard_transform(src_transform).to_gdal() if dst_transform: dst_transform = guard_transform(dst_transform).to_gdal() # Passing None can cause segfault, use empty dict if src_crs is None: src_crs = {} if dst_crs is None: dst_crs = {} _reproject(source, destination, src_transform, gcps, src_crs, src_nodata, dst_transform, dst_crs, dst_nodata, resampling, init_dest_nodata, **kwargs)
def reproject(source, destination=None, src_transform=None, gcps=None, rpcs=None, src_crs=None, src_nodata=None, dst_transform=None, dst_crs=None, dst_nodata=None, dst_resolution=None, src_alpha=0, dst_alpha=0, resampling=Resampling.nearest, num_threads=1, init_dest_nodata=True, warp_mem_limit=0, **kwargs): """Reproject a source raster to a destination raster. If the source and destination are ndarrays, coordinate reference system definitions and affine transformation parameters or ground control points (gcps) are required for reprojection. If the source and destination are rasterio Bands, shorthand for bands of datasets on disk, the coordinate reference systems and transforms or GCPs will be read from the appropriate datasets. Parameters ------------ source: ndarray or Band The source is a 2 or 3-D ndarray, or a single or a multiple Rasterio Band object. The dimensionality of source and destination must match, i.e., for multiband reprojection the lengths of the first axes of the source and destination must be the same. destination: ndarray or Band, optional The destination is a 2 or 3-D ndarray, or a single or a multiple Rasterio Band object. The dimensionality of source and destination must match, i.e., for multiband reprojection the lengths of the first axes of the source and destination must be the same. src_transform: affine.Affine(), optional Source affine transformation. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. An error will be raised if this parameter is defined together with gcps. gcps: sequence of GroundControlPoint, optional Ground control points for the source. An error will be raised if this parameter is defined together with src_transform or rpcs. rpcs: RPC or dict, optional Rational polynomial coefficients for the source. An error will be raised if this parameter is defined together with src_transform or gcps. src_crs: CRS or dict, optional Source coordinate reference system, in rasterio dict format. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. Example: CRS({'init': 'EPSG:4326'}) src_nodata: int or float, optional The source nodata value. Pixels with this value will not be used for interpolation. If not set, it will default to the nodata value of the source image if a masked ndarray or rasterio band, if available. dst_transform: affine.Affine(), optional Target affine transformation. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_crs: CRS or dict, optional Target coordinate reference system. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_nodata: int or float, optional The nodata value used to initialize the destination; it will remain in all areas not covered by the reprojected source. Defaults to the nodata value of the destination image (if set), the value of src_nodata, or 0 (GDAL default). dst_resolution: tuple (x resolution, y resolution) or float, optional Target resolution, in units of target coordinate reference system. src_alpha : int, optional Index of a band to use as the alpha band when warping. dst_alpha : int, optional Index of a band to use as the alpha band when warping. resampling: int, rasterio.enums.Resampling Resampling method to use. Default is :attr:`rasterio.enums.Resampling.nearest`. An exception will be raised for a method not supported by the running version of GDAL. num_threads : int, optional The number of warp worker threads. Default: 1. init_dest_nodata: bool Flag to specify initialization of nodata in destination; prevents overwrite of previous warps. Defaults to True. warp_mem_limit : int, optional The warp operation memory limit in MB. Larger values allow the warp operation to be carried out in fewer chunks. The amount of memory required to warp a 3-band uint8 2000 row x 2000 col raster to a destination of the same size is approximately 56 MB. The default (0) means 64 MB with GDAL 2.2. kwargs: dict, optional Additional arguments passed to transformation function. Returns --------- destination: ndarray or Band The transformed narray or Band. dst_transform: Affine THe affine transformation matrix of the destination. """ # Only one type of georeferencing is permitted. if (src_transform and gcps) or (src_transform and rpcs) or (gcps and rpcs): raise ValueError("src_transform, gcps, and rpcs are mutually " "exclusive parameters and may not be used together.") # Guard against invalid or unsupported resampling algorithms. try: if resampling == 7: raise ValueError("Gauss resampling is not supported") Resampling(resampling) except ValueError: raise ValueError( "resampling must be one of: {0}".format(", ".join( ['Resampling.{0}'.format(r.name) for r in SUPPORTED_RESAMPLING]))) if destination is None and dst_transform is not None: raise ValueError("Must provide destination if dst_transform is provided.") # calculate the destination transform if not provided if dst_transform is None and (destination is None or isinstance(destination, np.ndarray)): src_bounds = tuple([None] * 4) if isinstance(source, np.ndarray): if source.ndim == 3: src_count, src_height, src_width = source.shape else: src_count = 1 src_height, src_width = source.shape # try to compute src_bounds if we don't have gcps if not (gcps or rpcs): src_bounds = array_bounds(src_height, src_width, src_transform) else: src_rdr, src_bidx, _, src_shape = source # dataset.bounds will return raster extents in pixel coordinates # if dataset does not have geotransform, which is not useful here. if not (src_rdr.transform.is_identity and src_rdr.crs is None): src_bounds = src_rdr.bounds src_crs = src_crs or src_rdr.crs if isinstance(src_bidx, int): src_bidx = [src_bidx] src_count = len(src_bidx) src_height, src_width = src_shape gcps = src_rdr.gcps[0] if src_rdr.gcps[0] else None dst_height = None dst_width = None dst_count = src_count if isinstance(destination, np.ndarray): if destination.ndim == 3: dst_count, dst_height, dst_width = destination.shape else: dst_count = 1 dst_height, dst_width = destination.shape left, bottom, right, top = src_bounds dst_transform, dst_width, dst_height = calculate_default_transform( src_crs=src_crs, dst_crs=dst_crs, width=src_width, height=src_height, left=left, bottom=bottom, right=right, top=top, gcps=gcps, rpcs=rpcs, dst_width=dst_width, dst_height=dst_height, resolution=dst_resolution) if destination is None: destination = np.empty((int(dst_count), int(dst_height), int(dst_width)), dtype=source.dtype) # Call the function in our extension module. _reproject( source, destination, src_transform=src_transform, gcps=gcps, rpcs=rpcs, src_crs=src_crs, src_nodata=src_nodata, dst_transform=dst_transform, dst_crs=dst_crs, dst_nodata=dst_nodata, dst_alpha=dst_alpha, src_alpha=src_alpha, resampling=resampling, init_dest_nodata=init_dest_nodata, num_threads=num_threads, warp_mem_limit=warp_mem_limit, **kwargs) return destination, dst_transform
def reproject(source, destination, src_transform=None, gcps=None, src_crs=None, src_nodata=None, dst_transform=None, dst_crs=None, dst_nodata=None, resampling=Resampling.nearest, init_dest_nodata=True, **kwargs): """Reproject a source raster to a destination raster. If the source and destination are ndarrays, coordinate reference system definitions and affine transformation parameters or ground control points (gcps) are required for reprojection. If the source and destination are rasterio Bands, shorthand for bands of datasets on disk, the coordinate reference systems and transforms or GCPs will be read from the appropriate datasets. Parameters ------------ source, destination: ndarray or Band The source and destination are 2 or 3-D ndarrays, or a single or multiple Rasterio Band object. The dimensionality of source and destination must match, i.e., for multiband reprojection the lengths of the first axes of the source and destination must be the same. src_transform: affine.Affine(), optional Source affine transformation. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. An error will be raised if this parameter is defined together with gcps. gcps: sequence of GroundControlPoint, optional Ground control points for the source. An error will be raised if this parameter is defined together with src_transform. src_crs: CRS or dict, optional Source coordinate reference system, in rasterio dict format. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. Example: CRS({'init': 'EPSG:4326'}) src_nodata: int or float, optional The source nodata value.Pixels with this value will not be used for interpolation. If not set, it will be default to the nodata value of the source image if a masked ndarray or rasterio band, if available. dst_transform: affine.Affine(), optional Target affine transformation. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_crs: CRS or dict, optional Target coordinate reference system. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_nodata: int or float, optional The nodata value used to initialize the destination; it will remain in all areas not covered by the reprojected source. Defaults to the nodata value of the destination image (if set), the value of src_nodata, or 0 (GDAL default). resampling: int Resampling method to use. One of the following: Resampling.nearest, Resampling.bilinear, Resampling.cubic, Resampling.cubic_spline, Resampling.lanczos, Resampling.average, Resampling.mode, Resampling.max (GDAL >= 2.2), Resampling.min (GDAL >= 2.2), Resampling.med (GDAL >= 2.2), Resampling.q1 (GDAL >= 2.2), Resampling.q3 (GDAL >= 2.2) An exception will be raised for a method not supported by the running version of GDAL. init_dest_nodata: bool Flag to specify initialization of nodata in destination; prevents overwrite of previous warps. Defaults to True. kwargs: dict, optional Additional arguments passed to transformation function. Returns --------- out: None Output is written to destination. """ # Only one type of georeferencing is permitted. if src_transform and gcps: raise ValueError("src_transform and gcps parameters may not" "be used together.") # Guard against invalid or unsupported resampling algorithms. try: if resampling == 7: raise ValueError("Gauss resampling is not supported") Resampling(resampling) except ValueError: raise ValueError("resampling must be one of: {0}".format(", ".join( ['Resampling.{0}'.format(r.name) for r in SUPPORTED_RESAMPLING]))) # Call the function in our extension module. _reproject(source, destination, src_transform, gcps, src_crs, src_nodata, dst_transform, dst_crs, dst_nodata, False, resampling, init_dest_nodata, **kwargs)
def reproject(source, destination, src_transform=None, src_crs=None, src_nodata=None, dst_transform=None, dst_crs=None, dst_nodata=None, resampling=Resampling.nearest, init_dest_nodata=True, **kwargs): """ Reproject a source raster to a destination raster. If the source and destination are ndarrays, coordinate reference system definitions and affine transformation parameters are required for reprojection. If the source and destination are rasterio Bands, shorthand for bands of datasets on disk, the coordinate reference systems and transforms will be read from the appropriate datasets. Parameters ------------ source: ndarray or rasterio Band Source raster. destination: ndarray or rasterio Band Target raster. src_transform: affine.Affine(), optional Source affine transformation. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. src_crs: CRS or dict, optional Source coordinate reference system, in rasterio dict format. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. Example: CRS({'init': 'EPSG:4326'}) src_nodata: int or float, optional The source nodata value. Pixels with this value will not be used for interpolation. If not set, it will be default to the nodata value of the source image if a masked ndarray or rasterio band, if available. Must be provided if dst_nodata is not None. dst_transform: affine.Affine(), optional Target affine transformation. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_crs: CRS or dict, optional Target coordinate reference system. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_nodata: int or float, optional The nodata value used to initialize the destination; it will remain in all areas not covered by the reprojected source. Defaults to the nodata value of the destination image (if set), the value of src_nodata, or 0 (GDAL default). resampling: int Resampling method to use. One of the following: Resampling.nearest, Resampling.bilinear, Resampling.cubic, Resampling.cubic_spline, Resampling.lanczos, Resampling.average, Resampling.mode init_dest_nodata: bool Flag to specify initialization of nodata in destination; prevents overwrite of previous warps. Defaults to True. kwargs: dict, optional Additional arguments passed to transformation function. Returns --------- out: None Output is written to destination. """ # Resampling guard. try: Resampling(resampling) if resampling == 7: raise ValueError except ValueError: raise ValueError("resampling must be one of: {0}".format(", ".join([ 'Resampling.{0}'.format(k) for k in Resampling.__members__.keys() if k != 'gauss' ]))) # If working with identity transform, assume it is crs-less data # and that translating the matrix very slightly will avoid #674 eps = 1e-100 if src_transform and guard_transform(src_transform).is_identity: src_transform = src_transform.translation(eps, eps) if dst_transform and guard_transform(dst_transform).is_identity: dst_transform = dst_transform.translation(eps, eps) if src_transform: src_transform = guard_transform(src_transform).to_gdal() if dst_transform: dst_transform = guard_transform(dst_transform).to_gdal() # Passing None can cause segfault, use empty dict if src_crs is None: src_crs = {} if dst_crs is None: dst_crs = {} _reproject(source, destination, src_transform, src_crs, src_nodata, dst_transform, dst_crs, dst_nodata, resampling, init_dest_nodata, **kwargs)
def reproject( source, destination, src_transform=None, src_crs=None, src_nodata=None, dst_transform=None, dst_crs=None, dst_nodata=None, resampling=Resampling.nearest, **kwargs): """ Reproject a source raster to a destination raster. If the source and destination are ndarrays, coordinate reference system definitions and affine transformation parameters are required for reprojection. If the source and destination are rasterio Bands, shorthand for bands of datasets on disk, the coordinate reference systems and transforms will be read from the appropriate datasets. Parameters ------------ source: ndarray or rasterio Band Source raster. destination: ndarray or rasterio Band Target raster. src_transform: affine transform object, optional Source affine transformation. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. src_crs: dict, optional Source coordinate reference system, in rasterio dict format. Required if source and destination are ndarrays. Will be derived from source if it is a rasterio Band. Example: {'init': 'EPSG:4326'} src_nodata: int or float, optional The source nodata value. Pixels with this value will not be used for interpolation. If not set, it will be default to the nodata value of the source image if a masked ndarray or rasterio band, if available. Must be provided if dst_nodata is not None. dst_transform: affine transform object, optional Target affine transformation. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_crs: dict, optional Target coordinate reference system. Required if source and destination are ndarrays. Will be derived from target if it is a rasterio Band. dst_nodata: int or float, optional The nodata value used to initialize the destination; it will remain in all areas not covered by the reprojected source. Defaults to the nodata value of the destination image (if set), the value of src_nodata, or 0 (GDAL default). resampling: int Resampling method to use. One of the following: Resampling.nearest, Resampling.bilinear, Resampling.cubic, Resampling.cubic_spline, Resampling.lanczos, Resampling.average, Resampling.mode kwargs: dict, optional Additional arguments passed to transformation function. Returns --------- out: None Output is written to destination. """ # Resampling guard. try: Resampling(resampling) if resampling == 7: raise ValueError except ValueError: raise ValueError( "resampling must be one of: {0}".format(", ".join( ['Resampling.{0}'.format(k) for k in Resampling.__members__.keys() if k != 'gauss']))) if src_transform: src_transform = guard_transform(src_transform).to_gdal() if dst_transform: dst_transform = guard_transform(dst_transform).to_gdal() _reproject( source, destination, src_transform, src_crs, src_nodata, dst_transform, dst_crs, dst_nodata, resampling, **kwargs)