RSGISLib Image Calculations Module

The imagecalc module contains functions for performing a number of calculating on images.

class rsgislib.imagecalc.BandDefn(bandName=None, fileName=None, bandIndex=None)

Create a list of these objects to pass to the bandMath function as the ‘bands’ parameter.

class rsgislib.imagecalc.StatsSummary(min=0.0, max=0.0, sum=0.0, median=0.0, stdDev=0.0, mean=0.0, calcMin=False, calcMax=False, calcSum=False, calcMean=False, calcStdDev=False, calcMedian=False)

This is passed to the imagePixelColumnSummary function

rsgislib.imagecalc.calcDist2ImgVals(inputValsImg, outputDistImg, pxlVals, valsImgBand=1, gdalFormat='KEA', maxDist=None, noDataVal=None, unitGEO=True)

A function to calculate the distance to the nearest pixel value with one of the specified values.

Where:

  • inputValsImg is a string specifying the input image file.
  • outputDistImg is a string specfiying the output image file.
  • pxlVals is a number of list of numbers specifying the features to which the distance from should be calculated.
  • valsImgBand is an integer specifying the image band of the input image to be used (Default = 1).
  • gdalFormat is a string specifying the output image format (Default = KEA)
  • maxDist is a number specifying the maximum distance to be calculated, if None not max value is used (Default = None).
  • noDataVal is the no data value in the input image for which distance should not be calculated for (Default = None; None = no specified no data value).
  • unitGEO is a boolean specifying the output distance units. True = Geographic units (e.g., metres), False is in Pixels (Default = True).

Example:

import rsgislib.imagecalc
cloudsImg = 'LS5TM_20110701_lat52lon421_r24p204_clouds.kea'
dist2Clouds = 'LS5TM_20110701_lat52lon421_r24p204_distclouds.kea'
# Pixel value 1 == Clouds
# Pixel value 2 == Cloud Shadows
rsgislib.imagecalc.calcDist2ImgVals(cloudsImg, dist2Clouds, pxlVals=[1,2])
rsgislib.imagecalc.calcDist2ImgValsTiled(inputValsImg, outputDistImg, pxlVals, valsImgBand=1, maxDist=1000, noDataVal=1000, gdalFormat='KEA', unitGEO=True, tmpDIR='./tmp', tileSize=2000, nCores=-1)

A function to calculate the distance to the nearest pixel value with one of the specified values.

Where:

  • inputValsImg is a string specifying the input image file.
  • outputDistImg is a string specfiying the output image file.
  • pxlVals is a number of list of numbers specifying the features to which the distance from should be calculated.
  • valsImgBand is an integer specifying the image band of the input image to be used (Default = 1).
  • gdalFormat is a string specifying the output image format (Default = KEA)
  • maxDist is a number specifying the maximum distance to be calculated, if None not max value is used (Default = None).
  • noDataVal is the no data value in the input image for which distance should not be calculated for (Default = None; None = no specified no data value).
  • unitGEO is a boolean specifying the output distance units. True = Geographic units (e.g., metres), False is in Pixels (Default = True).
  • tmpDIR is a directory to be used for storing the image tiles and other temporary files - if not directory does not exist it will be created and deleted on completion (Default: ./tmp).
  • tileSize is an int specifying in pixels the size of the image tiles used for processing (Default: 2000)
  • nCores is the number of processing cores which are available to be used for this processing. If -1 all available cores will be used. (Default: -1)

Example:

import rsgislib.imagecalc
cloudsImg = 'LS5TM_20110701_lat52lon421_r24p204_clouds.kea'
dist2Clouds = 'LS5TM_20110701_lat52lon421_r24p204_distclouds.kea'
# Pixel value 1 == Clouds
# Pixel value 2 == Cloud Shadows
rsgislib.imagecalc.calcDist2ImgValsTiled(cloudsImg, dist2Clouds, pxlVals=[1,2])
rsgislib.imagecalc.calcNDVI(image, rBand, nBand, outImage, stats=True, gdalFormat='KEA')

Helper function to calculate NDVI

Where:

  • image is a string specifying the input image file.
  • rBand is an int specifying the red band in the input image (band indexing starts at 1)
  • nBand is an int specifying the nir band in the input image (band indexing starts at 1)
  • outImage is a string specifying the output image file.
  • stats is a boolean specifying whether pyramids and stats should be calculated (Default: True)
  • gdalFormat is a string specifing the output image file format (Default: KEA)
rsgislib.imagecalc.calcWBI(image, bBand, nBand, outImage, stats=True, gdalFormat='KEA')

Helper function to calculate WBI

Where:

  • image is a string specifying the input image file.
  • bBand is an int specifying the blue band in the input image (band indexing starts at 1)
  • nBand is an int specifying the nir band in the input image (band indexing starts at 1)
  • outImage is a string specifying the output image file.
  • stats is a boolean specifying whether pyramids and stats should be calculated (Default: True)
  • gdalFormat is a string specifing the output image file format (Default: KEA)

Band & Image Maths

rsgislib.imagecalc.bandMath(outputImage, expression, gdalformat, datatype, bandDefnSeq, useExpAsbandName)

Performs band math calculation.

Where:

  • outputImage is a string containing the name of the output file
  • expression is a string containing the expression to run over the images, uses muparser syntax.
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • bandDefnSeq is a sequence of rsgislib.imagecalc.BandDefn objects that define the inputs
  • useExpAsbandName is an optional bool specifying whether the band name should be the expression (Default = False).

Example:

import rsgislib
from rsgislib import imagecalc
from rsgislib.imagecalc import BandDefn
outputImage = './TestOutputs/PSU142_b1mb2.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
expression = 'b1*b2'
bandDefns = []
bandDefns.append(BandDefn('b1', inFileName, 1))
bandDefns.append(BandDefn('b2', inFileName, 2))
imagecalc.bandMath(outputImage, expression, gdalformat, datatype, bandDefns)
rsgislib.imagecalc.imageMath(inputImage, outputImage, expression, gdalformat, datatype, useExpAsbandName)

Performs image math calculation.

Where:

  • inimage is a string containing the name of the input file
  • outputImage is a string containing the name of the output file
  • expression is a string containing the expression to run over the images, uses myparser syntax.
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • useExpAsbandName is an optional bool specifying whether the band name should be the expression (Default = False).

Example:

import rsgislib
from rsgislib import imagecalc
outputImage = path + 'TestOutputs/PSU142_multi1000.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32UINT
expression = 'b1*1000'
imagecalc.imageMath(inFileName, outputImage, expression, gdalformat, datatype)
rsgislib.imagecalc.allBandsEqualTo(inputImage, imgValue, outputTrueVal, outputFalseVal, outputImage, gdalformat, datatype)

Tests whether all bands are equal to the same value

Where:

  • inputImage is a string containing the name of the input image file
  • imgValue is a float specifying the value against which others are tested for equality TODO: Check this and below
  • ouputTrueVal is a float specifying the value in the output image representing true
  • outputFalseVal is a float specifying the value in the output image representing false
  • outputImage is a string containing the name of the output image file
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
rsgislib.imagecalc.replaceValuesLessThan(inputImage, outputImage, threshold, value)

Replaces values in an image that are less than the provided, according to the provided threshold

Where:

  • inputImage is a string containing the name of the input image file
  • outputImage is a string containing the name of the output image file
  • threshold is a float containing the threshold to use
  • value is a float containing the value below which replacement will occur

Clustering

rsgislib.imagecalc.kMeansClustering(inputImage, outputMatrix, numClusters, maxIterations, subSample, ignoreZeros, degreeOfChange, initMethod)

Performs K Means Clustering and saves cluster centres to a text file.

Where:

  • inputImage is a string providing the input image
  • outputMatrix is a string providing the output matrix (text file) to save the cluster centres to.
  • numClusters is the number of clusters to use.
  • maxIterations is the maximum number of itterations.
  • subSample is an int specifying what fraction of the total pixels should be considered (e.g., 100 = 1/100 pixels).
  • ignoreZeros is a bool specifying if zeros in the image should be treated as no data.
  • degreeofChange is a float providing the minimum change between itterations before terminating.
  • initMethod the method for initialising the clusters and is one of INITCLUSTER_* values

Example:

import rsgislib
from rsgislib import imagecalc
inputImage = path + 'Rasters/injune_p142_casi_sub_right_utm.kea'
output = path + 'TestOutputs/kmeanscentres'
numClust = 10
maxIter = 200
degChange = 0.0025
subSample = 1
ignoreZeros = True
imagecalc.kMeansClustering(inputImage, output, numClust, maxIter, subSample, ignoreZeros, degChange, rsgislib.INITCLUSTER_DIAGONAL_FULL_ATTACH)
rsgislib.imagecalc.isoDataClustering(inputImage, outputMatrix, numClusters, maxIterations, subSample, ignoreZeros, degreeOfChange, initMethod, minDistBetweenClusters, minNumFeatures, maxStdDev, minNumClusters, startIteration, endIteration)

Performs ISO Data Clustering and saves cluster centres to a text file.

Where:

  • inputImage is a string providing the input image
  • outputMatrix is a string providing the output matrix (text file) to save the cluster centres to.
  • numClusters is the number of clusters to start with.
  • maxIterations is the maximum number of itterations.
  • subSample is an int specifying what fraction of the total pixels should be considered (e.g., 100 = 1/100 pixels).
  • ignoreZeros is a bool specifying if zeros in the image should be treated as no data.
  • initMethod the method for initialising the clusters and is one of INITCLUSTER_* values
  • minDistBetweenClusters is a float
  • minNumFeatures is an int
  • maxStdDev is a float
  • minNumClusters is an int
  • startIteration is an int
  • endIteration is an int

Example:

import rsgislib
from rsgislib import imagecalc
inputImage = path + 'Rasters/injune_p142_casi_sub_right_utm.kea'
output = './TestOutputs/isocentres'
imagecalc.isoDataClustering(inputImage, output, 10, 200, 1, True, 0.0025, rsgislib.INITCLUSTER_DIAGONAL_FULL_ATTACH, 2, 5, 5, 5, 8, 50)

Spectral Unmixing

rsgislib.imagecalc.unconLinearSpecUnmix(inputImage, gdalformat, datatype, outputFile, endmembersFile, lsumGain, lsumOffset)

Performs unconstrained linear spectral unmixing of the input image for a set of endmembers. Endmember polygons are extracted using rsgislib.zonalstats.extractAvgEndMembers() where each polygon defines an endmember.

Where:

  • inputImage is a string containing the name of the input image file
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • outputFile is a string containing the name of the output file
  • endmembersFile is a string containing the names of the file containing the end members
  • lsumGain is a float specifying a gain which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 1.
  • lsumOffset is a float specifying an offset which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 0.

Example:

import rsgislib.zonalstats
import rsgislib.imagecalc
import rsgislib

imageLSImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl.kea"
unmixedImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl_unmix.kea"
roiSHP = "./ROIs.shp"
endmembersFile = "./endmembers"

rsgislib.zonalstats.extractAvgEndMembers(imageLSImage, roiSHP, endmembersFile)

lsumGain = 1.0
lsumOffset = 0.0

endmembersFile = "./endmembers.mtxt"
rsgislib.imagecalc.unconLinearSpecUnmix(imageLSImage, "KEA", rsgislib.TYPE_32FLOAT, unmixedImage, endmembersFile, lsumGain, lsumOffset)
rsgislib.imagecalc.exhconLinearSpecUnmix(inputImage, gdalformat, datatype, outputFile, endmembersFile, stepResolution, lsumGain, lsumOffset)

Performs an exhaustive constrained linear spectral unmixing of the input image for a set of endmembers

* this methods is slow (!!) to execute *

Endmember polygons are extracted using rsgislib.zonalstats.extractAvgEndMembers() where each polygon defines an endmember.

Where:

  • inputImage is a string containing the name of the input image file
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • outputFile is a string containing the name of the output file
  • endmembersFile is a string containing the names of the file containing the end members
  • stepResolution is a float specifying the gap between steps in the search space. Value needs to be between 0 and 1. (i.e., 0.05)
  • lsumGain is a float specifying a gain which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 1.
  • lsumOffset is a float specifying an offset which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 0.

Example:

import rsgislib.zonalstats
import rsgislib.imagecalc
import rsgislib

imageLSImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl.kea"
unmixedImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl_unmix.kea"
roiSHP = "./ROIs.shp"
endmembersFile = "./endmembers"

rsgislib.zonalstats.extractAvgEndMembers(imageLSImage, roiSHP, endmembersFile)

lsumGain = 1.0
lsumOffset = 0.0

endmembersFile = "./endmembers.mtxt"
stepResolution = 0.1
rsgislib.imagecalc.exhconLinearSpecUnmix(imageLSImage, "KEA", rsgislib.TYPE_32FLOAT, unmixedImage, endmembersFile, stepResolution, lsumGain, lsumOffset)
rsgislib.imagecalc.conSum1LinearSpecUnmix(inputImage, gdalformat, datatype, lsumWeight, outputFile, endmembersFile, lsumGain, lsumOffset)

Performs a partially constrained linear spectral unmixing of the input image for a set of endmembers where the sum of the unmixing will be approximately 1 Endmember polygons are extracted using rsgislib.zonalstats.extractAvgEndMembers() where each polygon defines an endmember.

Where:

  • inputImage is a string containing the name of the input image file
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • lsumWeight is a float specifying a weight which is added to the Least-Squares matrix to ensure summation to 1.
  • outputFile is a string containing the name of the output file
  • endmembersFile is a string containing the names of the file containing the end members
  • lsumGain is a float specifying a gain which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 1.
  • lsumOffset is a float specifying an offset which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 0.

Example:

import rsgislib.zonalstats
import rsgislib.imagecalc
import rsgislib

imageLSImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl.kea"
unmixedImage = "./LS8_20130519_lat52lon42_r24p204_rad_srefstdmdl_unmix.kea"
roiSHP = "./ROIs.shp"
endmembersFile = "./endmembers"

rsgislib.zonalstats.extractAvgEndMembers(imageLSImage, roiSHP, endmembersFile)

lsumGain = 1.0
lsumOffset = 0.0
lsumWeight = 40

endmembersFile = "./endmembers.mtxt"
rsgislib.imagecalc.conSum1LinearSpecUnmix(imageLSImage, "KEA", rsgislib.TYPE_32FLOAT, lsumWeight, unmixedImage, endmembersFile, lsumGain, lsumOffset)
rsgislib.imagecalc.nnConSum1LinearSpecUnmix(inputImage, gdalformat, datatype, lsumWeight, outputFile, endmembersFile, lsumGain, lsumOffset)

Performs a constrained linear spectral unmixing of the input image for a set of endmembers where the sum of the unmixing will be approximately 1 and non-negative. Endmember polygons are extracted using rsgislib.zonalstats.extractAvgEndMembers() where each polygon defines an endmember.

Where:

  • inputImage is a string containing the name of the input image file
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • lsumWeight is a float specifying a weight which is added to the Least-Squares matrix to ensure summation to 1.
  • outputFile is a string containing the name of the output file
  • endmembersFile is a string containing the names of the file containing the end members
  • lsumGain is a float specifying a gain which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 1.
  • lsumOffset is a float specifying an offset which can be applied to the output pixel values (outvalue = offset + (gain * value)). Optional, default = 0.

Statistics

rsgislib.imagecalc.imageStats(inputImage, outputFile, ignoreZeros)

Calculates statistics for an image across all bands

Where:

  • inputImage is a string containing the name of the input image file
  • outputFile is a string containing the name of the output file
  • ignoreZeros is a boolean defining whether zeros are ignored in the statistic calculation
rsgislib.imagecalc.imageBandStats(inputImage, outputFile, ignoreZeros)

Calculates statistics for individuals bands of an image

Where:

  • inputImage is a string containing the name of the input image file
  • outputFile is a string containing the name of the output file
  • ignoreZeros is a boolean defining whether zeros are ignored in the statistic calculation
rsgislib.imagecalc.meanVector(inputImage, outputMatrix)

Calculates the mean vector of an image

Where:

  • inputImage is a string containing the name of the input image file
  • outputMatrix is a string containing the name of the output matrix
rsgislib.imagecalc.imagePixelLinearFit(inputImage, outputImage, gdalFormat, bandValues, noDataValue, useNoDataValue)

Performs a linear regression on each column of pixels.

Where:

  • inputImage is a string containing the name of the input file
  • outputImage is a string containing the name of the output file
  • gdalFormat is a string containing the GDAL format for the output file - eg ‘KEA’
  • bandValues is text file containing the value of each band (e.g. wavelength, day of year) with a separate line for each band
  • noDataValue is a float specifying what value is used to signify no data
  • useNoDataValue is a boolean specifying whether the noDataValue should be used

Example:

image = 'injune_p142_casi_sub_utm.kea'
output = 'injune_p142_casi_sub_utm_linear_fit.kea'
gdalformat = 'KEA'
bandValues = [446,530,549,569,598,633,680,696,714,732,741,752,800,838]

bandValuesFile =  'injune_p142_casi_wavelengths.txt'

with open(bandValuesFile,'w') as f:
    for bandVal in bandValues:
        f.write(str(bandVal) + '\n')

imagecalc.imagePixelLinearFit(image, output, gdalformat, bandValuesFile, 0, True)
rsgislib.imagecalc.pca(eigenVectors, inputImage, outputImage, numComponents)

Performs a principal components analysis of an image

Where:

  • eigenVectors is a string containing the name of the file of eigen vectors for the PCA
  • inputImage is a string containing the name of the input image file
  • outputImage is a string containing the name of the output image file
  • numComponents is an int containing number of components to use for PCA
rsgislib.imagecalc.calculateRMSE(inputImageA, inputBandA, inputImageB, inputBandB)

Calculates the root mean squared error between two images

Where:

  • inputImageA is a string containing the name of the first input image file
  • inputBandA is an integer defining which band should be processed from inputImageA
  • inputImageB is a string containing the name of the second input image file
  • inputBandB is an integer defining which band should be processed from inputImageB
rsgislib.imagecalc.bandPercentile(inputImage, percentile, noDataValue)

Calculates image band percentiles for the input image and results a list of values

Where:

  • inputImage is a string containing the name of the input image file
  • percentile is a float between 0 – 1 specifying the percentile to be calculated.
  • noDataValue is a float specifying the value used to represent no data (used None when no value is to be specified).
rsgislib.imagecalc.covariance(inputImageA, inputImageB, inputMatrixA, inputMatrixB, shouldCalcMean, outputMatrix)

Calculates the covariance between two images

Where:

  • inputImageA is a string containing the name of the first input image file
  • inputImageB is a string containing the name of the second input image file
  • inputMatrixA is a string containing the name of the first input matrix file
  • inputMatrixB is a string containing the name of the second input matrix file
  • shouldCalcMean is a boolean defining whether the mean should be calculated TODO: check
  • outputMatrix is a string containing the name of the output matrix
rsgislib.imagecalc.histogram(inputImage, imageMask, outputFile, imgBand, imgValue, binWidth, calcInMinMax, inMin, inMax)

Generates a histogram for the region of the mask selected

Where:

  • inputImage is a string containing the name of the input image file
  • imageMask is a string containing the name of the image mask file
  • outputFile is a string containing the name of the file for histogram output
  • imgValue is a float
  • binWidth is a float specifying the width of the histogram bins
  • calcInMinMax is a boolean specifying whether inMin and inMax should be calculated
  • inMin is a float for the minimum image value to be included in the histogram
  • inMax is a floatf or the maximum image value to be included in the histogram
rsgislib.imagecalc.getHistogram(inputImage, imgBand, binWidth, calcInMinMax, inMin, inMax)

Generates and returns a histogram for the image.

Where:

  • inputImage is a string containing the name of the input image file
  • imgBand is an unsigned int specifying the image band starting from 1.
  • binWidth is a float specifying the width of the histogram bins
  • calcInMinMax is a boolean specifying whether inMin and inMax should be calculated
  • inMin is a float for the minimum image value to be included in the histogram
  • inMax is a floatf or the maximum image value to be included in the histogram

returns:

  • returns a list
rsgislib.imagecalc.get2DImageHistogram(inputImage1, inputImage2, outputImage, gdalFormat, img1Band, img2Band, numBins, img1Min, img1Max, img2Min, img2Max, normOutput)

Calculates at 2D histogram between two bands of two input images

Where:

  • inputImage1 is a string containing the name of the first input image file

  • inputImage2 is a string containing the name of the second input image file

  • outputImage is a string containing the name of the output image file containing the histogram.

  • gdalFormat is a string specifying output image format.

  • img1Band is an unsigned integer specifying the image band from image 1 to be used.

  • img2Band is an unsigned integer specifying the image band from image 2 to be used.

  • numBins is an unsigned integer specifying the number of bins to be used on each histogram axis

    (it’ll produce a square histogram).

  • img1Min is a double specifying the minimum image value for image 1 to be used in the histogram.

  • img1Max is a double specifying the maximum image value for image 1 to be used in the histogram.

  • img2Min is a double specifying the minimum image value for image 2 to be used in the histogram.

  • img2Max is a double specifying the maximum image value for image 2 to be used in the histogram.

  • normOutput is a boolean specifying whether the output histogram should be normalised to unit volume.

Returns:

  • double with bin width of the axis of image 1.
  • double with bin width of the axis of image 2.
rsgislib.imagecalc.correlation(imageA, imageB, outmatrixfile=None)

Calculates the correlation between two images

Where:

  • inputImageA is a string containing the name of the first input image file
  • inputImageB is a string containing the name of the second input image file
  • outputMatrix is a string containing the basename of the output matrix (optional)

Returns:

  • Correlation matrix (tuple of tuples)

Example:

from rsgislib import imagecalc
inImageA = 'imageA.kea'
inImageB = 'imageB.kea'
outMatrixBase = 'imageABCorrelation'
outMatrix = imagecalc.correlation(inImage, inImage, outMatrixBase)
rsgislib.imagecalc.correlationWindow(inputImage, outputImage, windowSize, bandA, bandB, gdalformat, datatype)

Tests whether all bands are equal to the same value

Where:

  • inputImage is a string containing the name of the input image file
  • outputImage is a string containing the name of the output image file
  • windowSize is an int providing the size of the window to calculate the correlation over
  • bandA is an int providing the first band to use.
  • bandB is an int providing the second band to use.
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • datatype is an containing one of the values from rsgislib.TYPE_*

Example:

image = path + 'injune_p142_casi_sub_utm.kea'
output = path + 'injune_p142_casi_sub_utm_correlation.kea'
window = 9
bandA = 1
bandB = 1
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imagecalc.correlationWindow(image, output, window, bandA, bandB, gdalformat, datatype)
rsgislib.imagecalc.getImageBandModeInEnv(inputImage, imgBand, binWidth, noDataVal, latMin, latMax, longMin, longMax)

Calculates and returns the image mode for a region. defined by the bounding box (latMin, latMax, longMin, longMax) which is specified geographic latitude and longitude. The coordinates are converted to the projection of the input image at runtime (if required) and therefore the image projection needs to be correctly defined so please check this is the case and define it if necessary.

Where:

  • inputImage is a string containing the name of the input image file

  • imgBand is an unsigned int specifying the image band starting from 1.

  • binWidth is a float specifying the binWidth for the histogram generated to calculate the mode.

  • noDataVal is a float specifying a no data value, to be ignored in the calculation.

    If a value of ‘None’ is provided then a no data value is not used.

  • latMin is a double specifying the minimum latitude of the BBOX

  • latMax is a double specifying the maximum latitude of the BBOX

  • longMin is a double specifying the minimum longitude of the BBOX

  • longMax is a double specifying the maximum longitude of the BBOX

Returns:

  • float with image mode for the region within the BBOX.
rsgislib.imagecalc.getImageStatsInEnv(inputImage, imgBand, noDataVal, latMin, latMax, longMin, longMax)

Calculates and returns statistics (min, max, mean, stddev, sum) for a region. defined by the bounding box (latMin, latMax, longMin, longMax) which is specified geographic latitude and longitude. The coordinates are converted to the projection of the input image at runtime (if required) and therefore the image projection needs to be correctly defined so please check this is the case and define it if necessary.

Where:

  • inputImage is a string containing the name of the input image file
  • imgBand is an unsigned int specifying the image band starting from 1.
  • noDataVal is a float specifying a no data value, to be ignored in the calculation. If a value of ‘None’ is provided then a no data value is not used.
  • latMin is a double specifying the minimum latitude of the BBOX
  • latMax is a double specifying the maximum latitude of the BBOX
  • longMin is a double specifying the minimum longitude of the BBOX
  • longMax is a double specifying the maximum longitude of the BBOX

Returns:

  • list with 5 values (min, max, mean, stddev, sum)

Example:

import rsgislib.imagecalc
stats = rsgislib.imagecalc.getImageStatsInEnv("./FinalSRTMTanzaniaDEM_30m.kea", 1, -32767.0, -7.0, -8.0, 30.0, 31.0)
print("Min: ", stats[0])
print("Max: ", stats[1])
print("Mean: ", stats[2])
print("StdDev: ", stats[3])
print("Sum: ", stats[4])
rsgislib.imagecalc.calcPropTrueExp(expression, bandDefnSeq, validImgMask)

Calculates the proportion of the image where the expression is true. Optionally a mask defining the valid area can be used to restrict the area of the image used as the total number of pixels within the scene.

Where:

  • expression is a string containing the expression to run over the images, uses muparser syntax. Must output a value of 1 to be true.
  • bandDefnSeq is a sequence of rsgislib.imagecalc.BandDefn objects that define the inputs
  • validImgMask is an optional string specifying a valid area image mask. If not specified then it won’t be used.

Returns:

  • Returns a float value with the proportion

Example:

from rsgislib import imagecalc
from rsgislib.imagecalc import BandDefn
expression = 'b1<20?1:b2>100?1:0'
bandDefns = []
bandDefns.append(BandDefn('b1', inFileName, 1))
bandDefns.append(BandDefn('b2', inFileName, 2))
prop = imagecalc.calcPropTrueExp(bandDefns, expression)
print(prop)
rsgislib.imagecalc.calcMultiImgBandStats(inputImages, outputImage, summaryStatOption, gdalFormat, datatype, noDataVal, useNoDataVal)

Calculates the summary statistic (rsgislib.SUMTYPE_*) across multiple images on a per band basis .For example, if rsgislib.SUMTYPE_MIN is selected then for all the images the minimum value for band 1 (across all the images) and then band 2 etc. will be outputted as a new image with the same number of bands as the inputs (Note. all the input images must have the same number of bands).

Where:

  • inputImages is a list of input images (note. all inputs must have the same number of image bands).
  • outputImage is a string with the name and path of the output image.
  • summaryStatOption is of type rsgislib.SUMTYPE_* and specifies which summary statistic is used to sumamrise the images.
  • gdalFormat is a string specifying the output image format (e.g., KEA).
  • datatype is an containing one of the values from rsgislib.TYPE_*
  • noDataVal float with the value of the no data value, the same value for all the input images (Optional)
  • useNoDataVal is a boolean specifying whether the no data value should be used (Optional, default False)
rsgislib.imagecalc.calcMaskImgPxlValProb(inputImage, inImgBands, maskImg, maskImgVal, outputImage, gdalFormat, histBinWidths, useImgNoData, rescaleProbs)

Calculates the probability of each image pixel value occuring as defined by the distrubution of image pixel values within the masked region of the image.

Where:

  • inputImage is a string containing the name/path of the input image file.

  • inImgBands is a list containing the image bands for which the probability will be calculated.

    (Note. number of output bands will equal number of bands specified here.

  • maskImg is a string containing the name/path of the input mask image file.

  • maskImgVal is an integer corresponding to the pixel value in the mask image defining mask used for this calculation.

  • outputImage is a string containing the name of the output image file.

  • gdalFormat is a string specifying output image format.

  • histBinWidths is list of floating point values for the width of the histogram bins used to calculate the probability (one value for each band specified)

    (Note. larger bin widths will increase the difference between high and low probabilities) This parameter is optional and if not specified or value is less than 0 then the bin width will be estimated from the data.

  • useImgNoData is a boolean specifying whether (if specified) the no data value specified in the band header

    should be excluded from the histogram (Optional and if not specfied defaults to True).

  • rescaleProbs is a boolean specifying whether the probabilities should be rescaled to a range of 0-1 as values

    can be very small when a number of variables are used. (Optional and if not specified the default is True).

Normalise

rsgislib.imagecalc.standardise(meanVector, inputImage, outputImage)

Generates a standardised image using the mean vector provided

Where:

  • meanVector is a string containing the name of the file containing the mean vector TODO: check
  • inputImage is a string containing the name of the input image file
  • outputImage is a string containing the name of the output image file
rsgislib.imagecalc.normalisation(inputImages, outputImages, calcInMinMax, inMin, inMax, outMin, outMax)

Performs image normalisation

Where:

  • inputImages is a sequence of strings containing the names of the input files
  • outputImages is a sequence of strings containing the names of the output files
  • calcInMinMax is a boolean specifying whether to calculate inMin and inMax values TODO: Check’
  • inMin is a float specifying the TODO
  • inMax is a float specifying the TODO
  • outMin is a float specifying the TODO
  • outMax is a float specifying the TODO

Geometry

rsgislib.imagecalc.dist2Geoms(inputVector, imageResolution, outputImage)

Calculates the distance to the nearest geometry for every pixel in an image

Where:

  • inputVector is a string defining the geometry TODO: Check this and find out about input image
  • imageResolution is a float defining the resolution of which to process the image
  • outputImage is a string containing the name of the file for the output image
rsgislib.imagecalc.imageDist2Geoms(inputImage, inputVector, gdalformat, outputImage)

Calculates the distance to the nearest geometry for every pixel in an image

Where:

  • inputImage is a string containing the name of the input image file
  • inputVector is a string containing the name of the input vector file containing the geometry TODO: check this
  • gdalformat is a string containing the GDAL format for the output file - eg ‘KEA’
  • outputImage is a string containing the name of the output image file
rsgislib.imagecalc.mahalanobisDistFilter(inputImage, outputImage, windowSize, gdalFormat, gdalDataType)

Performs mahalanobis distance window filter.

Where:

  • inputImage is a string containing the name of the input file
  • outputImage is a string containing the name of the output file
  • windowSize is an int defining the size of the window to be used
  • gdalFormat is a string containing the GDAL format for the output file - eg ‘KEA’
  • gdalDataType is an int containing one of the values from rsgislib.TYPE_*
rsgislib.imagecalc.mahalanobisDist2ImgFilter(inputImage, outputImage, windowSize, gdalFormat, gdalDataType)

Performs mahalanobis distance image to window filter.

Where:

  • inputImage is a string containing the name of the input file
  • outputImage is a string containing the name of the output file
  • windowSize is an int defining the size of the window to be used
  • gdalFormat is a string containing the GDAL format for the output file - eg ‘KEA’
  • gdalDataType is an int containing one of the values from rsgislib.TYPE_*
rsgislib.imagecalc.imageCalcDistance(inputImage, outputImage, gdalFormat)

Performs image calculate distance command.

Where:

  • inputImage is a string containing the name of the input file
  • outputImage is a string containing the name of the output file
  • gdalFormat is a string containing the GDAL format for the output file - eg ‘KEA’
rsgislib.imagecalc.calcDist2ImgVals(inputValsImg, outputDistImg, pxlVals, valsImgBand=1, gdalFormat='KEA', maxDist=None, noDataVal=None, unitGEO=True)

A function to calculate the distance to the nearest pixel value with one of the specified values.

Where:

  • inputValsImg is a string specifying the input image file.
  • outputDistImg is a string specfiying the output image file.
  • pxlVals is a number of list of numbers specifying the features to which the distance from should be calculated.
  • valsImgBand is an integer specifying the image band of the input image to be used (Default = 1).
  • gdalFormat is a string specifying the output image format (Default = KEA)
  • maxDist is a number specifying the maximum distance to be calculated, if None not max value is used (Default = None).
  • noDataVal is the no data value in the input image for which distance should not be calculated for (Default = None; None = no specified no data value).
  • unitGEO is a boolean specifying the output distance units. True = Geographic units (e.g., metres), False is in Pixels (Default = True).

Example:

import rsgislib.imagecalc
cloudsImg = 'LS5TM_20110701_lat52lon421_r24p204_clouds.kea'
dist2Clouds = 'LS5TM_20110701_lat52lon421_r24p204_distclouds.kea'
# Pixel value 1 == Clouds
# Pixel value 2 == Cloud Shadows
rsgislib.imagecalc.calcDist2ImgVals(cloudsImg, dist2Clouds, pxlVals=[1,2])
rsgislib.imagecalc.calcDist2ImgValsTiled(inputValsImg, outputDistImg, pxlVals, valsImgBand=1, maxDist=1000, noDataVal=1000, gdalFormat='KEA', unitGEO=True, tmpDIR='./tmp', tileSize=2000, nCores=-1)

A function to calculate the distance to the nearest pixel value with one of the specified values.

Where:

  • inputValsImg is a string specifying the input image file.
  • outputDistImg is a string specfiying the output image file.
  • pxlVals is a number of list of numbers specifying the features to which the distance from should be calculated.
  • valsImgBand is an integer specifying the image band of the input image to be used (Default = 1).
  • gdalFormat is a string specifying the output image format (Default = KEA)
  • maxDist is a number specifying the maximum distance to be calculated, if None not max value is used (Default = None).
  • noDataVal is the no data value in the input image for which distance should not be calculated for (Default = None; None = no specified no data value).
  • unitGEO is a boolean specifying the output distance units. True = Geographic units (e.g., metres), False is in Pixels (Default = True).
  • tmpDIR is a directory to be used for storing the image tiles and other temporary files - if not directory does not exist it will be created and deleted on completion (Default: ./tmp).
  • tileSize is an int specifying in pixels the size of the image tiles used for processing (Default: 2000)
  • nCores is the number of processing cores which are available to be used for this processing. If -1 all available cores will be used. (Default: -1)

Example:

import rsgislib.imagecalc
cloudsImg = 'LS5TM_20110701_lat52lon421_r24p204_clouds.kea'
dist2Clouds = 'LS5TM_20110701_lat52lon421_r24p204_distclouds.kea'
# Pixel value 1 == Clouds
# Pixel value 2 == Cloud Shadows
rsgislib.imagecalc.calcDist2ImgValsTiled(cloudsImg, dist2Clouds, pxlVals=[1,2])

Image Indices

rsgislib.imagecalc.calcNDVI(image, rBand, nBand, outImage, stats=True, gdalFormat='KEA')

Helper function to calculate NDVI

Where:

  • image is a string specifying the input image file.
  • rBand is an int specifying the red band in the input image (band indexing starts at 1)
  • nBand is an int specifying the nir band in the input image (band indexing starts at 1)
  • outImage is a string specifying the output image file.
  • stats is a boolean specifying whether pyramids and stats should be calculated (Default: True)
  • gdalFormat is a string specifing the output image file format (Default: KEA)
rsgislib.imagecalc.calcWBI(image, bBand, nBand, outImage, stats=True, gdalFormat='KEA')

Helper function to calculate WBI

Where:

  • image is a string specifying the input image file.
  • bBand is an int specifying the blue band in the input image (band indexing starts at 1)
  • nBand is an int specifying the nir band in the input image (band indexing starts at 1)
  • outImage is a string specifying the output image file.
  • stats is a boolean specifying whether pyramids and stats should be calculated (Default: True)
  • gdalFormat is a string specifing the output image file format (Default: KEA)

Other

rsgislib.imagecalc.countValsInCols(inputImage, upper, lower, outputImage)

Counts the number of values within a given range for each column

Where:

  • inputImage is a string containing the name of the input image file
  • upper is a float containing the upper limit of values to count
  • lower is a float containing the lower limit of values to count
  • outputImage is a string containing the name of the output image file
rsgislib.imagecalc.imagePixelColumnSummary(inputImage, outputImage, summaryStats, gdalFormat, gdalDataType, noDataValue, useNoDataValue)

Calculates summary statistics for a column of pixels.

Where:

  • inputImage is a string containing the name of the input file

  • outputImage is a string containing the name of the output file

  • summaryStats is an rsgislib.imagecalc.StatsSummary object that has attributes matching rsgis.cmds.RSGISCmdStatsSummary
    • calcMin: boolean defining if the min value should be calculated
    • calcMax: boolean defining if the max value should be calculated
    • calcSum: boolean defining if the sum value should be calculated
    • calcMean: boolean defining if the mean value should be calculated
    • calcStdDev: boolean defining if the standard deviation should be calculated
    • calcMedian: boolean defining if the median value should be calculated
    • min: float defining the min value to use
    • max: float defining the max value to use
    • mean: float defining the mean value to use
    • sum: float defining the sum value to use
    • stdDev: float defining the standard deviation value to use
    • median: float defining the median value to use
  • gdalFormat is a string containing the GDAL format for the output file - eg ‘KEA’

  • gdalDataType is an int containing one of the values from rsgislib.TYPE_*

  • noDataValue is a float specifying what value is used to signify no data

  • useNoDataValue is a boolean specifying whether the noDataValue should be used

rsgislib.imagecalc.movementSpeed(inputImages, imageBands, imageTimes, upper, lower, outputImage)

Calculates the speed of movement in images (mean, min and max)

Where:

  • inputImages is a python sequence of strings of the input image files
  • imageBands is a python sequence of integers defining the band of each image to use
  • imageTimes is a python sequence of floats defining the time corresponding to each image
  • upper is a float TODO: expand
  • lower is a float TODO: expand
  • outputImage is a string defining the output image file name
rsgislib.imagecalc.unitArea(inputImage, outputImage, inputMatrixFile)

Converts the image spectra to unit area

Where:

  • inputImage is a string containing the name of the input image file
  • outputImage is a string containing the name of the output image file
  • inputMatrixFile is a string containing the name of the input matrix file TODO: check