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.
ImageBandRescale
(band=0, inMin=0.0, inMax=0.0, inNoData=0, outMin=0.0, outMax=0.0, outNoData=0.0)¶ Data structure for rescaling information for rescaleImgPxlVals function. :param band: specified image band (band numbering starts at 1). :param inMin: the input image band minimum value for rescaling. :param inMax: the input image band maximum value for rescaling. :param inNoData: no data value for the input image band. :param outMin: the output image band minimum value for rescaling. :param outMax: the output image band maximum value for rescaling. :param outNoData: no data value for the output image band.
- Parameters
band – specified image band (band numbering starts at 1).
inMin – the input image band minimum value for rescaling.
inMax – the input image band maximum value for rescaling.
inNoData – no data value for the input image band.
outMin – the output image band minimum value for rescaling.
outMax – the output image band maximum value for rescaling.
outNoData – no data value for the output image band.
-
class
rsgislib.imagecalc.
StatsSummary
(min=0.0, max=0.0, sum=0.0, median=0.0, stdDev=0.0, mean=0.0, mode=0.0, calcMin=False, calcMax=False, calcSum=False, calcMean=False, calcStdDev=False, calcMedian=False, calcMode=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:
- Parameters
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.
- Parameters
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.
calcHistograms4MskVals
(inputImg, imgBand, imgMsk, mskBand, minVal, maxVal, binWidth, mskvals=None)¶ A function which reads the image bands (values and mask) into memory and creates a histogram for each value within the mask value. Within the mask 0 is considered to be no data.
- Parameters
inputImg – image values image file path.
imgBand – values image band
imgMsk – file path for image mask.
mskBand – mask image band
minVal – minimum value for the histogram bins
maxVal – maximum value for the histogram bins
binWidth – the width of the histograms bins.
mskvals – a list of values within the mask can be provided to just consider a limited number of mask values when calculating the histograms. If None (default) then calculated for all mask values.
- Returns
returns a dict of mask values with an array for the histogram.
-
rsgislib.imagecalc.
calcImgBasicStats4RefRegion
(ref_img, stats_imgs, output_img, gdalformat='KEA')¶ A function which calculates the mean and standard deviation through a series of input images. The region for processing is defined by the reference image and images padded with no-data where no data is present.
The output image has twice the number of bands as the input image providing a mean and standard deviation for each input band.
If the input images has 2 bands then the output bands will have the following order:
band 1 mean
band 1 std dev
band 2 mean
band 2 std dev
- Parameters
ref_img – reference image which defines the output image
stats_imgs – a list of input images over which the stats will be calculated.
output_img – the output image path and file name
gdalformat – the output image file format. Default KEA.
-
rsgislib.imagecalc.
calcImgsPxlMode
(inputImgs, outputImg, gdalformat, no_data_val=0)¶ Function which calculates the mode of a group of images.
Warning, this function can be very slow. Use rsgislib.imagecalc.imagePixelColumnSummary
- Parameters
inputImgs – the list of images
outputImg – the output image file name and path (will be same dimensions as the input)
gdalformat – the GDAL image file format of the output image file.
-
rsgislib.imagecalc.
calcPPI
(inputimg, outputimg, gdalformat, niters=1000, lthres=0, uthres=0, img_gain=1, seed=None, calcstats=True)¶ A function which calculate the pixel purity index (PPI). Using an appropriate number of iterations this can take a little while to run. Note, the whole input image is read into memory.
It is recommended that you use the an MNF/PCA output and rescale that so all bands have the same range to improve the PPI result.
- Boardman J.W., Kruse F.A, and Green R.O., “Mapping Target Signatures via
Partial Unmixing of AVIRIS Data,” Pasadena, California, USA, 23 Jan 1995, URI: http://hdl.handle.net/2014/33635
- Parameters
inputImg – image values image file path.
outputimg – output image
gdalformat – GDAL file format (e.g., KEA) of the output image.
niters – number of iterations
thres – a threshold in the image space (after again as been applied) to select more pixels around the extreme (e.g., 1% reflectance)
img_gain – the gain by which the image was multipled, reflectance images are typically multiplied by 1000 or 10000. The result should be an image with a range 0-1.
seed – seed for the random squence of numbers being generated. Using the same seed will result in the same seqence and therefore the same output.
calcstats – whether to calculate image statistics and pyramids on the output image.
-
rsgislib.imagecalc.
calcWSG84PixelArea
(img, out_img, scale=10000, gdalformat='KEA')¶ A function which calculates the area (in metres) of the pixel projected in WGS84.
- Parameters
img – input image, for which the per-pixel area will be calculated.
out_img – output image file.
scale – scale the output area to unit of interest. Scale=10000(Ha), Scale=1(sq m), Scale=1000000(sq km), Scale=4046.856(Acre), Scale=2590000(sq miles), Scale=0.0929022668(sq feet)
-
rsgislib.imagecalc.
calc_fill_regions_knn
(ref_img, ref_no_data, fill_regions_img, fill_region_val, out_img, k=5, summary=1, gdalformat='KEA', datatype=3)¶ A function will fills regions (defined by having a value == fill_region_val) of the fill_regions_img image using a KNN approach based of pixels within the ref_img image. The KNN distance is the spatial distance based off the pixel locations.
The ref_img and fill_regions_img must both be in the same projection.
- Parameters
ref_img – The reference image (can be a different resolution) from which the KNN will be trained.
ref_no_data – The no data value used within the reference image.
fill_regions_img – A mask image defining the regions to be filled.
fill_region_val – The pixel value specifying the pixels in the fill_regions_img image for the KNN value will be calculated.
out_img – The output image file name and path.
k – The k parameter of the KNN.
summary – Summary method (rsgislib.SUMTYPE_*) to be used (Default is Mode). Options: Mode, Median, Sum, Mean, Range, Min, Max.
gdalformat – output file format (default: KEA)
datatype – is a rsgislib.TYPE_* value providing the data type of the output image.
-
rsgislib.imagecalc.
countPxlsOfVal
(inputImg, vals=[0])¶ Function which counts the number of pixels of a set of values returning a list in the same order as the list of values provided.
- Parameters
inputImg – the input image
vals – is a list of pixel values to be counted
-
rsgislib.imagecalc.
getPCAEigenVector
(inputImg, pxlNSample, noData=None, outMatrixFile=None)¶ A function which takes a sample from an input image and uses it to generate eigenvector for a PCA. Note. this can be used as input to rsgislib.imagecalc.pca
- Parameters
inputImg – the image from which the random sample will be taken.
pxlNSample – the sample to be taken (e.g., a value of 100 will sample every 100th pixel)
noData – provide a no data value which is to be ignored during processing. If None then ignored (Default: None)
outMatrixFile – path and name for the output rsgislib matrix file. If None file is not created (Default: None)
- Returns
array with the eigenvector, 2. array with the ratio of the explained variance
-
rsgislib.imagecalc.
mask_bzero_vals
(input_img, output_img, gdalformat, out_val=1)¶ Function which identifies image pixels which have a value of zero all bands which are defined as true ‘no data’ regions while other pixels have a value of zero or less then zero for one or few pixels which causes confusion between valid data pixel and no data pixels. This function will identify and define those pixels which are valid but with a value <= 0 for isolate bands to a new output value (out_val).
This function might be used for surface reflectance data where the atmospheric correction has resulted in value <=0 which isn’t normally possible and where 0 is commonly used as a no data value. In this case setting those pixel band values to 1 (if data has been multiplied by 100, 1000, or 10000, for example) or a small fraction (e.g., 0.001) if values are between 0-1.
- Parameters
input_img – the input image
output_img – the output image file name and path
gdalformat – the GDAL image file format of the output image file.
out_val – Output pixel band value (default: 1)
-
rsgislib.imagecalc.
normalise_image_band
(input_img, band, output_img, gdal_format='KEA')¶ Perform a simple normalisation a single image band (val - min)/range.
- Parameters
input_img – The input image file.
band – the image band (starts at 1) to be normalised
output_img – the output image file (will just be a single band).
gdal_format – The output image format.
-
rsgislib.imagecalc.
performImageMNF
(inputImg, outputImg, nComponents=None, pxlNSample=100, in_img_no_data=None, tmp_dir='./tmp', gdalformat='KEA', datatype=9, calcStats=True)¶ A function which takes a sample from an input image and uses it to generate eigenvector for a MNF. Note. this can be used as input to rsgislib.imagecalc.pca
- Parameters
inputImg – the image to which the MNF will be applied
outputImg – the output image file with the MNF result
nComponents – the number of components to be outputted
pxlNSample – the sample to be taken (e.g., a value of 100 will sample every 100th pixel) for the PCA
in_img_no_data – provide a no data value which is to be ignored during processing. If None then try to read from input image.
tmp_dir – a directory where temporary output files will be stored. If it doesn’t exist it will be created.
gdalformat – output image file format
datatype – data type for the output image. Note, it is common to have negative values.
calcStats – whether image statistics and pyramids could be calculated.
- Returns
array with the ratio of the explained variance
-
rsgislib.imagecalc.
performImagePCA
(inputImg, outputImg, eigenVecFile, nComponents=None, pxlNSample=100, gdalformat='KEA', datatype=7, noData=None, calcStats=True)¶ A function which performs a PCA on the input image.
- Parameters
inputImg – the image from which the random sample will be taken.
outputImg – the output image transformed using the calculated PCA
eigenVecFile – path and name for the output rsgislib matrix file containing the eigenvector for the PCA.
nComponents – the number of PCA compoents outputted. A value of None is all components (Default: None)
pxlNSample – the sample to be taken (e.g., a value of 100 will sample every 100th pixel) (Default: 100)
gdalformat – the output gdal supported file format (Default KEA)
datatype – the output data type of the input image (Default: rsgislib.TYPE_32UINT)
noData – provide a no data value which is to be ignored during processing. If None then ignored (Default: None)
calcStats – Boolean specifying whether pyramids and statistics should be calculated for the output image. (Default: True)
- Returns
an array with the ratio of the explained variance per band.
-
rsgislib.imagecalc.
recodeIntRaster
(input_img, output_img, recode_dict, keepvalsnotindict=True, gdalformat='KEA', datatype=3)¶ A function recodes an input image. Assuming image only has a single image band so it will be band 1 which is recoded. The recode is provided as a dict where the key is the value to be recoded and the value of the dict is the output value.
- Parameters
input_img – Input image file.
output_img – Output image file.
recode_dict – dict for recode (key: int to be recoded, value: int to recode to)
keepvalsnotindict – boolean whether pixels not being recoded should be copied to the output (True) or whether only those pixels recoded should be outputted (False) (default: True)
gdalformat – output file format (default: KEA)
datatype – is a rsgislib.TYPE_* value providing the data type of the output image.
-
rsgislib.imagecalc.
rescaleImgPxlVals
(inputImg, outputImg, gdalformat, datatype, bandRescale, trim2Limits=True)¶ Function which rescales an input image base on a list of rescaling parameters.
- Parameters
inputImg – the input image
outputImg – the output image file name and path (will be same dimensions as the input)
gdalformat – the GDAL image file format of the output image file.
bandRescale – list of ImageBandRescale objects
trim2Limits – whether to trim the output to the output min/max values.
Band & Image Maths¶
-
rsgislib.imagecalc.
bandMath
(outputimg, exp, gdalformat, datatype, banddefseq, expbandname, outputexists)¶ Performs band math calculation. The syntax for the expression is from the muparser library (‘http://muparser.beltoforion.de <http://muparser.beltoforion.de>`): see here <http://beltoforion.de/article.php?a=muparser&hl=en&p=features&s=idPageTop> . Where:
- Parameters
outputimg – is a string containing the name of the output file
exp – 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_*
banddefseq – is a sequence of rsgislib.imagecalc.BandDefn objects that define the inputs
expbandname – is an optional bool specifying whether the band name should be the expression (Default = False).
outputexists – is an optional bool specifying whether the output image already exists and it should be editted rather than overwritten (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) ################## If Statement Example ######################### import rsgislib from rsgislib import imagecalc bandDefns = [] bandDefns.append(BandDefn('b1', inFileName, 1)) bandDefns.append(BandDefn('b2', inFileName, 2)) bandDefns.append(BandDefn('b3', inFileName, 3)) imagecalc.bandMath('out.kea', ‘(b1==1) || (b2==1) || (b3==1)?1:0', 'KEA', rsgislib.TYPE_8UINT, bandDefns)
-
rsgislib.imagecalc.
imageMath
(inputimg, outputimg, exp, gdalformat, datatype, expbandname, outputexists)¶ Performs image math calculations. Produces an output image file with the same number of bands as the input image. This function applies the same calculation to each image band (i.e., b1 is the only variable). The syntax for the expression is from the muparser library (‘http://muparser.beltoforion.de <http://muparser.beltoforion.de>`): see here <http://beltoforion.de/article.php?a=muparser&hl=en&p=features&s=idPageTop> . Where:
- Parameters
inputimg – is a string containing the name of the input file
outputimg – is a string containing the name of the output file
exp – 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_*
expbandname – is an optional bool specifying whether the band name should be the expression (Default = False).
outputexists – is an optional bool specifying whether the output image already exists and it should be editted rather than overwritten (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.
imageBandMath
(inputimg, outputimg, exp, gdalformat, datatype, expbandname, outputexists)¶ Performs image band math calculations. Produces a single output file with a single image band. The image bands can be referred to individually using b1, b2 … bn. where n is the number of image bands, starting at 1. The syntax for the expression is from the muparser library (‘http://muparser.beltoforion.de <http://muparser.beltoforion.de>`): see here <http://beltoforion.de/article.php?a=muparser&hl=en&p=features&s=idPageTop> . Where:
- Parameters
inputimg – is a string containing the name of the input file
outputimg – is a string containing the name of the output file
exp – 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_*
expbandname – is an optional bool specifying whether the band name should be the expression (Default = False).
outputexists – is an optional bool specifying whether the output image already exists and it should be editted rather than overwritten (Default=False).
Example:
import rsgislib from rsgislib import imagecalc outputImage = path + 'TestOutputs/PSU142_vismean.kea' gdalformat = 'KEA' datatype = rsgislib.TYPE_32UINT expression = '(b1+b2+b3+b4)/4' imagecalc.imageBandMath(inFileName, outputImage, expression, gdalformat, datatype) ################## If Statement Example ######################### import rsgislib from rsgislib import imagecalc imagecalc.imageBandMath('in.kea', 'out.kea', '(b1==1) || (b2==1) || (b3==1)?1:0', 'KEA', rsgislib.TYPE_8UINT)
-
rsgislib.imagecalc.
allBandsEqualTo
(inputImage, imgValue, outputTrueVal, outputFalseVal, outputImage, gdalformat, datatype)¶ Tests whether all bands are equal to the same value
Where:
- Parameters
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:
- Parameters
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:
- Parameters
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:
- Parameters
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 iterations.
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_:param 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:
- Parameters
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.
Warning. This methods is slow (!!) to execute
Endmember polygons are extracted using rsgislib.zonalstats.extractAvgEndMembers() where each polygon defines an endmember.
Where:
- Parameters
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:
- Parameters
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.specunmixing.
rescale_unmixing_results
(input_img, output_img, gdalformat='KEA', calc_stats=True)¶ A function which rescales an output from a spectral unmixing (e.g., rsgislib.imagecalc.specunmixing.spec_unmix_spts_ucls) so that negative values are removed (set to 0) and each pixel sums to 1.
- Parameters
inputImg – Input image with the spectral unmixing result (pixels need to range from 0-1)
outputImg – Output image with the result of the rescaling (pixel values will be in range 0-1 without scale factor > 1)
gdalformat – the file format of the output file.
calc_stats – if true then image statistics and pyramids for the output image.
Statistics¶
-
rsgislib.imagecalc.
getImageBandMinMax
(inputImage, imageBand, useNoDataVal, noDataVal)¶ Calculate and reutrn the maximum and minimum values of the input image.
Where:
- Parameters
inputImage – is a string containing the name of the input file
imageBand – is an int specifying the image band
useNoDataVal – is a boolean specifying whether the no data value should be used (Optional, default is False)
noDataVal – is a string containing the GDAL format for the output file - eg ‘KEA’
Example:
import rsgislib from rsgislib import imagecalc inputImage = 'LS8_20131111_lat29lon8717_r40p140_vmsk_rad_srefdem.kea' imgBand = 1 minMaxVals = imagecalc.getImageBandMinMax(inputImage, imgBand) print('MIN: ', minMaxVals[0]) print('MAX: ', minMaxVals[1])
-
rsgislib.imagecalc.
imageStats
(inputImage, outputFile, ignoreZeros)¶ Calculates statistics for an image across all bands
Where:
- Parameters
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:
- Parameters
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:
- Parameters
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:
- Parameters
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
(inputImage, eigenVectors, outputImage, numComponents, gdalformat, dataType)¶ Performs a principal components analysis of an image using a defined set of eigenvectors. The eigenvectors can be calculated using the rsgislib.imagecalc.getPCAEigenVector function.
Where:
- Parameters
inputImage – is a string containing the name of the input image file
eigenVectors – is a string containing the name of the file of eigen vectors for the PCA
outputImage – is a string containing the name of the output image file
numComponents – is an int containing number of components to use for PCA
gdalformat – is a string containing the GDAL format for the output file - eg ‘KEA’
datatype – is an int containing one of the values from rsgislib.TYPE_*
Example:
import rsgislib.imageutils import rsgislib.imagecalc inputImg = 'Input.kea' eigenVecFile = 'EigenVec.mtxt' outputImg = './Output.kea' eigenVec, varExplain = rsgislib.imagecalc.getPCAEigenVector(inputImg, 1000, None, eigenVecFile) rsgislib.imagecalc.pca(inputImg, eigenVecFile, outputImg, varExplain.shape[0], 'KEA', rsgislib.TYPE_32FLOAT) rsgislib.imageutils.popImageStats(outputImg, usenodataval, nodataval, True)
-
rsgislib.imagecalc.
getPCAEigenVector
(inputImg, pxlNSample, noData=None, outMatrixFile=None)¶ A function which takes a sample from an input image and uses it to generate eigenvector for a PCA. Note. this can be used as input to rsgislib.imagecalc.pca
- Parameters
inputImg – the image from which the random sample will be taken.
pxlNSample – the sample to be taken (e.g., a value of 100 will sample every 100th pixel)
noData – provide a no data value which is to be ignored during processing. If None then ignored (Default: None)
outMatrixFile – path and name for the output rsgislib matrix file. If None file is not created (Default: None)
- Returns
array with the eigenvector, 2. array with the ratio of the explained variance
-
rsgislib.imagecalc.
performImagePCA
(inputImg, outputImg, eigenVecFile, nComponents=None, pxlNSample=100, gdalformat='KEA', datatype=7, noData=None, calcStats=True)¶ A function which performs a PCA on the input image.
- Parameters
inputImg – the image from which the random sample will be taken.
outputImg – the output image transformed using the calculated PCA
eigenVecFile – path and name for the output rsgislib matrix file containing the eigenvector for the PCA.
nComponents – the number of PCA compoents outputted. A value of None is all components (Default: None)
pxlNSample – the sample to be taken (e.g., a value of 100 will sample every 100th pixel) (Default: 100)
gdalformat – the output gdal supported file format (Default KEA)
datatype – the output data type of the input image (Default: rsgislib.TYPE_32UINT)
noData – provide a no data value which is to be ignored during processing. If None then ignored (Default: None)
calcStats – Boolean specifying whether pyramids and statistics should be calculated for the output image. (Default: True)
- Returns
an array with the ratio of the explained variance per band.
-
rsgislib.imagecalc.
calculateRMSE
(inputImageA, inputBandA, inputImageB, inputBandB)¶ Calculates the root mean squared error between two images
Where:
- Parameters
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
- Returns
float
-
rsgislib.imagecalc.
bandPercentile
(inputImage, percentile, noDataValue)¶ Calculates image band percentiles for the input image and results a list of values
Where:
- Parameters
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).
- Returns
list of floats
-
rsgislib.imagecalc.
covariance
(inputImageA, inputImageB, inputMatrixA, inputMatrixB, shouldCalcMean, outputMatrix)¶ Calculates the covariance between two images
Where:
- Parameters
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:
- Parameters
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:
- Parameters
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
list of ints
-
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:
- Parameters
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:
- Parameters
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:
- Parameters
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, longMin, longMax, latMin, latMax)¶ Calculates and returns the image mode for a region. defined by the bounding box (longMin, longMax, latMin, latMax) 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:
- Parameters
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.
longMin – is a double specifying the minimum longitude of the BBOX
longMax – is a double specifying the maximum longitude of the BBOX
latMin – is a double specifying the minimum latitude of the BBOX
latMax – is a double specifying the maximum latitude of the BBOX
- Returns
float with image mode for the region within the BBOX.
-
rsgislib.imagecalc.
getImageStatsInEnv
(inputImage, imgBand, noDataVal, longMin, longMax, latMin, latMax)¶ Calculates and returns statistics (min, max, mean, stddev, sum) for a region. defined by the bounding box (longMin, longMax, latMin, latMax) 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:
- Parameters
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.
longMin – is a double specifying the minimum longitude of the BBOX
longMax – is a double specifying the maximum longitude of the BBOX
latMin – is a double specifying the minimum latitude of the BBOX
latMax – is a double specifying the maximum latitude 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, 30.0, 31.0, -7.0, -8.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:
- Parameters
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:
- Parameters
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:
- Parameters
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).
-
rsgislib.imagecalc.
calcImageDifference
(inputImage1, inputImage2, outputImage, gdalformat, datatype)¶ Calculate the difference between two images (Image1 - Image2). Note the two images must have the same number of image bands.
Where:
- Parameters
inputImage1 – is a string containing the name of the first input file
inputImage2 – is a string containing the name of the second 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’
datatype – is an containing one of the values from rsgislib.TYPE_*
Example:
import rsgislib from rsgislib import imagecalc from rsgislib import imageutils inputImage1 = 'output_orig/LS8_20131111_lat29lon8717_r40p140_vmsk_rad_srefdem.kea' inputImage2 = 'output_lutinterp/LS8_20131111_lat29lon8717_r40p140_vmsk_rad_srefdem.kea' outputImage = 'LS8_20131111_lat29lon8717_r40p140_srefdemDiff.kea' imagecalc.calcImageDifference(inputImage1, inputImage2, outputImage, 'KEA', rsgislib.TYPE_32FLOAT) imageutils.popImageStats(outputImage, usenodataval=False, nodataval=0, calcpyramids=True)
-
rsgislib.imagecalc.
getImgIdxForStat
(inimages=list, outimage=string, gdalformat=string, nodata=float, stat=rsgislib.SUMTYPE_)¶ A function which calculates the index (starting at 1) of the image in the list of input images which has the stat selected. The output image can be used within the rsgislib.imageutils.createMaxNDVICompositeImg function. Where:
- Parameters
inimages – is a list of input images, which must each just have single image band.
outputImage – is a string with the name and path of the output image. No data value is 0 and indexes start at 1.
gdalformat – is a string with the GDAL output file format.
nodata – is the no data value in the input images (all images have the same no data value).
stat – is of type rsgislib.SUMTYPE_* and specifies how the index is calculated. Available options are: rsgislib.SUMTYPE_MEDIAN, rsgislib.SUMTYPE_MIN, rsgislib.SUMTYPE_MAX.
Example:
import rsgislib import rsgislib.imagecalc import rsgislib.imageutils import rsgislib.rastergis import glob import os.path # Get List of input images: inImages = glob.glob('./Outputs/*stdsref.kea') # Generate Comp Ref layers: refLyrsLst = [] refLayerPath = './CompRefLyrs/' idx = 1 for img in inImages: print('In Image ('+str(idx) + '): ' + img) baseImgName = os.path.splitext(os.path.basename(img))[0] refLyrImg = os.path.join(refLayerPath, baseImgName+'_ndvi.kea') rsgislib.imagecalc.calcNDVI(img, 3, 4, refLyrImg) refLyrsLst.append(refLyrImg) idx = idx + 1 # Create REF Image pxlRefImg = 'LS5TM_19851990CompRefImg_lat7lon3896_r65p166_vmsk_mclds_topshad_rad_srefdem_stdsref.kea' rsgislib.imagecalc.getImgIdxForStat(refLyrsLst, pxlRefImg, 'KEA', -999, rsgislib.SUMTYPE_MAX) # Pop Ref Image with stats rsgislib.rastergis.populateStats(pxlRefImg, True, True, True) # Create Composite Image outCompImg = 'LS5TM_19851990CompRefImgMAX_lat7lon3896_r65p166_vmsk_mclds_topshad_rad_srefdem_stdsref.kea' rsgislib.imageutils.createRefImgCompositeImg(inImages, outCompImg, pxlRefImg, 'KEA', rsgislib.TYPE_16UINT, 0.0) # Calc Stats rsgislib.imageutils.popImageStats(outCompImg, usenodataval=True, nodataval=0, calcpyramids=True)
-
rsgislib.imagecalc.
countPxlsOfVal
(inputImg, vals=[0])¶ Function which counts the number of pixels of a set of values returning a list in the same order as the list of values provided.
- Parameters
inputImg – the input image
vals – is a list of pixel values to be counted
-
rsgislib.imagecalc.
getImgSumStatsInPxl
(refimage=string, statsimage=string, outimage=string, gdalformat=string, datatype=int, sumstats=list, statsimageband=int, usenodata=bool, iogridx=int, iogridy=int)¶ A function which calculates a summary of the pixel values from the high resolution statsimage for the regions defined by the pixels in the lower resolution refimage. This is similar to zonal stats. Please note that the statsimage needs to have a pixel size which is a multiple of the refimage pixel size. For example, is the ref image has a resolution of 10 m the statsimage can have a resolution of 1 or 2 m but not 3 m for this function to work.
Where:
- Parameters
refimage – is a string specifying the name and path for the reference image. Note, this is only used to define the summary areas and output image extent.
statsimage – is a string specifying the name and path to the higher resolution image which will be summarised.
outimage – is a string specifying the output image file name and path.
gdalformat – is a string with the GDAL output file format.
datatype – is an containing one of the values from rsgislib.TYPE_*
sumstats – is a list of the type rsgislib.SUMTYPE_* and specifies the summary is calculated. Each summary statastic is saved as a different image band.:param statsimageband: is an integer specifying the image band in the stats image to be used for the analysis. (Default: 1)
usenodata – is a boolean specifying whether the image band no data value should be used. (Default: True)
iogridx – and iogridy are integers which control the image processing block size. The unit is pixels in the refimage. (Default: 16) where the pixel resolution between the two images is closer together these values can be increased but but where the statsimage pixel size is much smaller than the ref image reducing this will reduce the memory footprint significantly.
-
rsgislib.imagecalc.
calcImgMeanInMask
(inputimg=string, inputImgMsk=string, mskValue=int, bands=list, nodataval=float, usenodata=boolean)¶ A function to calculate the mean value of all the pixels specified within the mask and across all the image bounds.
Where:
- Parameters
inputimg – is a string specifying input image file.
inputImgMsk – is a string specifying image with the mask file.
mskValue – the mask value (integer), within the input image mask, specifying the pixels over which the mean will be taken.
bands – is a list of image bands (indexing starts at 1).
nodataval – is a float specifying the no data value.
usenodata – is a boolean specifiying whether to use the no data value.
- Returns
float with mean value.
-
rsgislib.imagecalc.
identifyMinPxlValueInWin
(inputimg=string, outimage=string, outrefimg=string, bands=list, winsize=int, gdalformat=string, nodataval=float, usenodata=boolean)¶ A function to identify the minimum value across the image bands specified within a window.
Where:
- Parameters
inputimg – is a string specifying input image file.
outimage – is a string specifying image with the minimum pixel value.
outrefimg – is a string specifying the output file for the reference image - i.e., the band index.
bands – is a list of image bands (indexing starts at 1).
winsize – is an integer specifying the window size (must be an odd number).
gdalformat – is a string with the GDAL output file format.
nodataval – is a float specifying the no data value.
usenodata – is a boolean specifiying whether to use the no data value.
Normalise¶
-
rsgislib.imagecalc.
standardise
(meanVector, inputImage, outputImage)¶ Generates a standardised image using the mean vector provided
Where:
- Parameters
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:
- Parameters
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 input minumum value
inMax – is a float specifying the input maximum value
outMin – is a float specifying the output minumum value
outMax – is a float specifying the output maximum value
-
rsgislib.imagecalc.
rescaleImgPxlVals
(inputImg, outputImg, gdalformat, datatype, bandRescale, trim2Limits=True)¶ Function which rescales an input image base on a list of rescaling parameters.
- Parameters
inputImg – the input image
outputImg – the output image file name and path (will be same dimensions as the input)
gdalformat – the GDAL image file format of the output image file.
bandRescale – list of ImageBandRescale objects
trim2Limits – whether to trim the output to the output min/max values.
-
rsgislib.imagecalc.
calcImageRescale
(inputImgs, outputImage, gdalformat, datatype, cNoDataVal, cOffset, cGain, nNoDataVal, nOffset, nGain)¶ A function which can take either a list of images or a single image to produce a single stacked output image. The image values are rescaled applying the input (current; c) gain and offset and then applying the new (n) gain and offset to the output image. Note, the nodata image value is also defined and can be changed. For reference gain/offset are applied as: ImgVal = (gain x DN) + offset
Where:
- Parameters
inputImgs – can be either a single input image file or a list of images to be stacked.
outputImage – is the output image file.
gdalformat – output raster format (e.g., KEA)
datatype – is an containing one of the values from rsgislib.TYPE_
cNoDataVal – is a float for the current (existing) no-data value for the imagery (note, all input images have the same no-data value).
cOffset – is a float for the current offset value.
:param cGain:is a float for the current gain value. :param nNoDataVal: is a float for the new no-data value for the imagery (note, all input images have the same no-data value). :param nOffset: is a float for the new offset value. :param nGain: is a float for the new gain value.
Geometry¶
-
rsgislib.imagecalc.
dist2Geoms
(inputVector, imageResolution, outputImage)¶ Calculates the distance to the nearest geometry for every pixel in an image
Where:
- Parameters
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:
- Parameters
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 geometries
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, datatype)¶ Performs mahalanobis distance window filter.
Where:
- Parameters
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’
dataType – is an int containing one of the values from rsgislib.TYPE_*
-
rsgislib.imagecalc.
mahalanobisDist2ImgFilter
(inputImage, outputImage, windowSize, gdalformat, datatype)¶ Performs mahalanobis distance image to window filter.
Where:
- Parameters
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’
datatype – is an int containing one of the values from rsgislib.TYPE_*
-
rsgislib.imagecalc.
imageCalcDistance
(inputImage, outputImage, gdalformat)¶ Performs image calculate distance command.
Where:
- Parameters
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:
- Parameters
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.
- Parameters
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.calcindices.
calcNDVI
(image, rBand, nBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate NDVI ((NIR-RED)/(NIR+RED)), note the output no data value is -999.
- Parameters
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.calcindices.
calcWBI
(image, bBand, nBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate WBI (Blue/NIR), note the output no data value is -999.
- Parameters
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)
-
rsgislib.imagecalc.calcindices.
calcNDWI
(image, nBand, sBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate NDWI ((NIR-SWIR)/(NIR+SWIR)), note the output no data value is -999.
- See: Xu, H. (2006). Modification of normalised difference water index (NDWI) to enhance open water
features in remotely sensed imagery. International Journal of Remote Sensing, 27(14), 3025–3033. http://doi.org/10.1080/01431160600589179
Where:
- Parameters
image – is a string specifying the input image file.
nBand – is an int specifying the nir band in the input image (band indexing starts at 1)
sBand – is an int specifying the swir band (e.g., Landsat TM Band 5) 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.calcindices.
calcGNDWI
(image, gBand, nBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate NDWI ((GREEN-NIR)/(GREEN+NIR)), note the output no data value is -999.
- See: Xu, H. (2006). Modification of normalised difference water index (NDWI) to enhance open water
features in remotely sensed imagery. International Journal of Remote Sensing, 27(14), 3025–3033. http://doi.org/10.1080/01431160600589179
Where:
- Parameters
image – is a string specifying the input image file.
gBand – is an int specifying the green 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.calcindices.
calcGMNDWI
(image, gBand, sBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate NDWI ((GREEN-SWIR)/(GREEN+SWIR)), note the output no data value is -999.
- See: Xu, H. (2006). Modification of normalised difference water index (NDWI) to enhance open water
features in remotely sensed imagery. International Journal of Remote Sensing, 27(14), 3025–3033. http://doi.org/10.1080/01431160600589179
Where:
- Parameters
image – is a string specifying the input image file.
gBand – is an int specifying the green band in the input image (band indexing starts at 1)
sBand – is an int specifying the swir band (e.g., Landsat TM Band 5) 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.calcindices.
calcWhiteness
(image, bBand, gBand, rBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate whiteness, note the output no data value is -999.
Where:
- Parameters
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)
gBand – is an int specifying the green band in the input image (band indexing starts at 1)
rBand – is an int specifying the red 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.calcindices.
calcBrightness
(image, bBand, gBand, rBand, outImage, stats=True, gdalformat='KEA', scalefac=1000)¶ Helper function to calculate visable brightness, note the output no data value is -999.
Where:
- Parameters
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)
gBand – is an int specifying the green band in the input image (band indexing starts at 1)
rBand – is an int specifying the red 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)
scalefac – is a float which can be used retirved reflectance between 0-1 (Default: 1000 to match rsgislib/arcsi)
-
rsgislib.imagecalc.calcindices.
calcBrightnessScaled
(image, bBand, gBand, rBand, outImage, stats=True, gdalformat='KEA', scalefac=1000)¶ Helper function to calculate visable brightness, note the output no data value is -999.
Where:
- Parameters
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)
gBand – is an int specifying the green band in the input image (band indexing starts at 1)
rBand – is an int specifying the red 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)
scalefac – is a float which can be used retirved reflectance between 0-1 (Default: 1000 to match rsgislib/arcsi)
-
rsgislib.imagecalc.calcindices.
calcCTVI
(image, bBand, nBand, outImage, stats=True, gdalformat='KEA')¶ Helper function to calculate Corrected Transformed Vegetation Index ((NDVI + 0.5)/sqrt(abs(NDVI + 0.5))), note the output no data value is -999.
Where:
- Parameters
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:
- Parameters
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, datatype, noDataValue, useNoDataValue)¶ Calculates summary statistics for a column of pixels.
Where:
- Parameters
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 * calcMode: boolean defining if the mode value should be calculated; warning can be slow. * 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 * mode: float defining the mode value to use
gdalformat – is a string containing the GDAL format for the output file - eg ‘KEA’
datatype – 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:
- Parameters
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:
- Parameters
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
-
rsgislib.imagecalc.leastcostpath.
performLeastCostPathCalc
(costSurfaceImg, outputPathImg, startCoord, stopCoord, gdalformat='KEA', costImgBand=1)¶ Calculates least cost path for a raster surface from start coord to stop coord:
Version of code from: https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html#create-least-cost-path
- Parameters
costSurfaceImg – Input image to calculate cost path from
outputPathImg – Output image
startCoord – Start coordinate (e.g., (263155.9, 291809.1))
stopCoord – End coordinate (e.g., (263000.1, 292263.7))
gdalformat – GDAL format (default=KEA)
costImgBand – Band in input image to use for cost analysis (default=1)