pyprecag.raster_ops

pyprecag.raster_ops.calculate_image_indices(image_file, band_map, out_image_file, indices=[], out_nodata=-9999)[source]

Creates a multi-band image where each band represents a calculated index.

Rasterio’s band tags are used to document which band represents which index.

The band mapping matches a band number to a band type ie band 3 is the Red band to enable the index calculation to occur. It also identifies a band where the nodata value removes the non-vine or bare earth signal. This nodata is assigned to the output image.

Indices currently supported are:
NDVI - Normalised difference vegetation index PCD - Plant cell density index GNDVI - Green normalised difference vegetation index CHLRE - Chlorophyll red-edge index NDRE - Normalised difference red-edge index
Parameters:
  • image_file (str) – image_file (str): the input image file
  • band_map (pyprecag.bandops.BandMapping) – a Band mapping matching a band number to band type.
  • out_image_file (str) – the name and location of the output image file.
  • indices (List[str]) – indices (List[str]): The list of indices to calculate.
  • out_nodata (int) – the value to use in the output image for the nodata
Returns:

Return type:

None

pyprecag.raster_ops.create_raster_transform(bounds, pixel_size, snap_extent_to_pixel=True, buffer_by_pixels=0)[source]
Create parameters required for creating a new raster file based on a known extent and pixel
size.
snap_extent_to_pixel can be used to ensure the bounding coordinates are a divisible of the
pixel size.
Parameters:
  • bounds (float, float, float, float) – the bounding box coordinates (xmin, ymin, xmax, ymax)
  • pixel_size (int, float) – the required pixel size
  • snap_extent_to_pixel (bool) – round the extent coordinates to be divisible by the pixel size
  • buffer_by_pixels (int) – The number of pixels to buffer the input bounding box by.
Returns:

the Rasterio Transformation object int: the width or number of columns int: the height or number of rows. [float, float, float, float]: new bounding box coordinates updated if snapping was used.

Return type:

affine.Affine

pyprecag.raster_ops.focal_statistics(raster, band_num=1, ignore_nodata=True, size=3, function=<function nanmean>, clip_to_mask=False, out_colname=None)[source]

Derives for each pixel a statistic of the values with the specified neighbourhood.

Currently the neighbourhood is restricted to square neighbourhoods ie 3x3 size.

Any numpy statistical functions are supported along with custom functions.

Nodata values are converted to np.nan and will be excluded from the statistical calculation. Nodata pixels may be assigned a value if at least one pixel in the neighbourhood has a valid value. To remove/mask these values from the final output, set the clip_to_mask setting to True.

Using a size of 1 returns the selected band with the converted nodata values. No statistical functions are applied.

An string out_colname is returned and can be used as a filename or column name during future analysis. If None, it is derived from the input raster, size and statistical function used.

For single band inputs <stat><size>x<size>_<raster name>
eg. mean3x3_area1_yield apply a mean 3x3 filter for raster area1_yield
For multi band inputs <function><size>x<size>bd<band_num>_<raster name>
eg. mean3x3b3_area2 apply a mean 3x3 filter for band 3 of the raster area2

Source: https://stackoverflow.com/a/30853116/9567306 https://stackoverflow.com/questions/46953448/local-mean-filter-of-a-numpy-array-with-missing-data/47052791#47052791

Parameters:
  • raster (rasterio.io.DatasetReader) – Raster file opened using rasterio.open(os.path.normpath())
  • band_num (int) – The band number to apply focal statistics to.
  • ignore_nodata (bool) – If true, the nodata value of the raster will be converted to np.nan and excluded from statistical calculations.
  • size (int) – Size of the neighbourhood filter used for statistics calculations. Currently restricted to a square neighbourhood ie 3x3, 5x5 etc.
  • function (function) – a functions to apply to the raster. These can include numpy functions like np.nanmean or custom ones.
  • clip_to_mask (bool) – If true, remove values assigned to nodata pixels
  • out_colname (str) – An output string used to describe the filter result and can be used as a column or filename If NONE, then it will be derived.
Returns:

A 1D numpy array of double (float32) values str: a string representation of the inputs

Return type:

numpy.ndarray

pyprecag.raster_ops.nancv(x)[source]

A function used with scipy.ndimage.generic_filter to calculate the coefficient variant of pixels/values excluding nan (nodata) values. It can be used in conjunction with

focal_statistics.

example using a 3x3: generic_filter(band,nancv, mode=’constant’, cval=np.nan, size=3)

A variation of https://stackoverflow.com/a/14060024

pyprecag.raster_ops.normalise(raster, band_num=1, ignore_nodata=True)[source]

Normalise a single band by adjusting to a mean of zero and standard deviation of 1

If ignore_nodata is used, then the selected band will be opened as a numpy masked array and the specified nodata values will be excluded from calculations

Returns calculated single band that can be written to file using
rasterio.open(os.path.normpath(),’w’)
Parameters:
  • raster (rasterio.io.DatasetReader) – Raster file opened by rasterio.open(os.path.normpath())
  • band_num (int) – The band number to apply rescaling too.
  • ignore_nodata (bool) –

    Ignore nodata values during rescaling. If False, nodata pixels and values will be used during the calculation If True, band will be read as a masked array and nodata pixels

    and values excluded.
Returns:

A single band as a numpy array. or numpy.ma.core.MaskedArray: A single band as a numpy array with nodata being stored in

the mask

Return type:

numpy.ndarray

pyprecag.raster_ops.pixelcount(x)[source]

A function used with scipy.ndimage.generic_filter to count the number of real values/pixels (ie not nan) when applying a NxN filter.

A Count of 0 will be replace by np.nan. It can be used in conjunction with focal statistics. A variation of https://stackoverflow.com/a/14060024

pyprecag.raster_ops.raster_snap_extent(x_min, y_min, x_max, y_max, pixel_size)[source]

Calculate a new raster extent where bounding coordinates are a divisible of the pixel size.

The LL will be rounded down, and the UR will be rounded up.

Using this function will ensure that rasters have the same pixel origin, when they are created which in the long run, will save resampling when multiple raster with the same pixel size are compared.

Args:
x_min (float): x_min coordinate will be rounded down to the nearest pixel edge y_min (float): y_min coordinate will be rounded down to the nearest pixel edge x_max (float): x_max coordinate will be rounded up to the nearest pixel edge y_max (float): y_max coordinate will be rounded up to the nearest pixel edge pixel_size (float): The pixel size representing the divisor
Returns:
List[float]]: Representing the Bounding box (xmin, ymin, xmax, ymax)
pyprecag.raster_ops.reproject_image(image_file, out_imagefile, out_epsg, band_nums=[], image_epsg=0, image_nodata=None, resampling=<Resampling.nearest: 0>)[source]

Reproject selected image bands from one coordinate system to another.

“image_epsg” and “image_nodata” can be used to set the coordinate system and image nodata values when they are not already specified within the image file.

Parameters:
  • image_file (str) – An input image path and name
  • out_imagefile (str) – An output image path and name
  • out_epsg (int) – The epsg number representing output coordinate system
  • band_nums (List) – The bands to reproject. If list is empty, all bands will be used
  • image_epsg (int) – the epsg number for the image. Only used if not provided by the image.
  • image_nodata (int) – the nodata value for the image. Only used if not provided by the image.
  • resampling (rasterio.enums.Resampling) – The resampling technique to use during reprojection.
Returns:

Return type:

None

pyprecag.raster_ops.rescale(raster, min_value, max_value, band_num=1, ignore_nodata=True)[source]

Rescale a single band between a set number of values.

If ignore_nodata is used, then the selected band will be opened as a numpy masked array and the specified nodata values will be excluded

It returns the calculated single band and can be written to file using rasterio.open(os.path.normpath(),’w’)

Parameters:
  • raster (rasterio.io.DatasetReader) – Raster file opened by rasterio.open(os.path.normpath())
  • min_value (int) – The lower/min value to use during rescaling
  • max_value (int) – The Upper/max value to use during rescaling
  • band_num (int) – The band number to apply rescaling too.
  • ignore_nodata (bool) – Ignore nodata values during rescaling. If False, the nodata pixels and values will be used during the calculation If True, band is read as a masked array and nodata pixels and values excluded
Returns:

A single band as a numpy array. or numpy.ma.core.MaskedArray: Single band numpy array with nodata being stored in the mask

Return type:

numpy.ndarray

pyprecag.raster_ops.save_in_memory_raster_to_file(memory_raster, out_image)[source]

Save a rasterio memory file as a TIF to disk

if out_image does not contain a path, it will be save to the Temp Dir.

Parameters:
  • memory_raster (rasterio.io.MemoryFile) –
  • out_image (str) – the tif image name.
Returns:

the image path and name.

Return type:

str

pyprecag.raster_ops.stack_and_clip_rasters(raster_files, use_common=True, output_tif=None)[source]

Combine multiple single band files into a single multi band raster where one band represents one file. The filename will be saved in the bands tag. Optionally a minimum common area mask can be applied.

All input rasters MUST be of the same coordinate system and pixel size.

Parameters:
  • raster_files (List[str]) – list of raster files to process
  • use_common (bool) – if true input rasters will be masked to the minimum common data area
  • output_tif (str) – output tif name. if omitted will be created in TEMPDIR
Returns:

The output tif file list(): A list of the band tags. (ie order of allocation to bands)

Return type:

str()

pyprecag.raster_ops.update_band_statistics_GDAL(raster_file)[source]

update band statistics using GDAL. Not yet built into rasterio