RSGISLib Image Utilities Module

The imageutils module contains general utilities for applying to images.

class rsgislib.imageutils.ImageBandInfo(fileName=None, name=None, bands=None)

Create a list of these objects to pass to the extractZoneImageBandValues2HDF function

Parameters
  • fileName – is the input image file name and path.

  • name – is a name associated with this layer - doesn’t really matter what you use but needs to be unique; this is used as a dict key in some functions.

  • bands – is a list of image bands within the fileName to be used for processing (band numbers start at 1).

  • fileName – is the input image file name and path.

  • name – is a name associated with this layer - doesn’t really matter what you use but needs to be unique; this is used as a dict key in some functions.

  • bands – is a list of image bands within the fileName to be used for processing (band numbers start at 1).

class rsgislib.imageutils.RSGISTimeseriesFillInfo(year=1900, day=0, compImg=None, imgRef=None, outRef=False)

Create a list of these objects to pass to the fillTimeSeriesGaps function

Parameters
  • year – year the composite represents.

  • day – the (nominal) day within the year the composite represents (a value of zero and day will not be used)

  • compImg – The input compsite image which has been generated.

  • imgRef – The reference layer (e.g., from createMaxNDVIComposite or createMaxNDVINDWICompositeLandsat) with zero for no data regions

  • outRef – A boolean variable specify which layer a fill reference layer is to be produced.

  • year – year the composite represents.

  • day – the (nominal) day within the year the composite represents (a value of zero and day will not be used)

  • compImg – The input compsite image which has been generated.

  • imgRef – The reference layer (e.g., from createMaxNDVIComposite or createMaxNDVINDWICompositeLandsat) with zero for no data regions

  • outRef – A boolean variable specify which layer a fill reference layer is to be produced.

class rsgislib.imageutils.SharpBandInfo(band=None, status=None, name=None)

Create a list of these objects to pass to the sharpenLowResBands function.

Parameters
  • band – is the band number (band numbering starts at 1).

  • status – needs to be either rsgislib.SHARP_RES_IGNORE, rsgislib.SHARP_RES_LOW or rsgislib.SHARP_RES_HIGH lowres bands will be sharpened using the highres bands and ignored bands will just be copied into the output image.

  • name – is a name associated with this image band - doesn’t really matter what you put in here.

  • band – is the band number (band numbering starts at 1).

  • status – needs to be either ‘ignore’, ‘lowres’ or ‘highres’ - lowres bands will be sharpened using the highres bands and ignored bands will just be copied into the output image.

  • name – is a name associated with this image band - doesn’t really matter what you put in here.

Image Stats and Pyramids

rsgislib.imageutils.popImageStats(image, usenodataval=True, nodataval=0, calcpyramids=True, pyscales=list)

Calculate the image statistics and build image pyramids populating the image file.

Where:

Parameters
  • image – is a string containing the name of the input file

  • usenodataval – is a boolean stating whether the no data value is to be used (default=True).

  • nodataval – is a floating point value to be used as the no data value (default=0.0).

  • calcpyramids – is a boolean stating whether image pyramids should be calculated (default=True).

  • pyscales – is a list which allows the levels of the image pyramid to be specified. If not provided then levels automatically calculated.

Example:

from rsgislib import imageutils
inputImage = './TestOutputs/injune_p142_casi_sub_utm.kea'
imageutils.popImageStats(inputImage,True,0.,True)
# OR Define the pyramids levels.
imageutils.popImageStats(inputImage,True,0.,True, [4,8,16,32,64,128])
rsgislib.imageutils.combineImageOverviews(base=string, images=list, pyscales=list)

A function to combine (mosaic) the image overviews (pyramids) from the list of input images and add them to the base image, enables pyramids to be created using a tiled processing chain for large images. Note. For small images use rsgislib.imageutils.popImageStats.

Where:

Parameters
  • base – is a string containing the name of the input image file the overviews will be added to

  • images – is a list of input images that have the same number of bands and overviews and are within the extent of the base image.

  • pyscales – is a list specifying the scales (levels) of the pyramids which will be defined in the base image (Note. the input images need to have the same pyramids scales; use rsgislib.imageutils.popImageStats).

Example:

from rsgislib import imageutils
baseImage = './TestOutputs/injune_p142_casi_sub_utm.kea'
imgTiles = ['./TestOutputs/injune_p142_casi_sub_utm_tile1.kea', './TestOutputs/injune_p142_casi_sub_utm_tile2.kea']
imageutils.combineImageOverviews(baseImage, imgTiles, [4,8,16,32,64,128])

Projection

rsgislib.imageutils.assignProj(inputImage, wktString, wktFile)

Assign a projection to the input GDAL image file.

Where:

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

  • wktString – is the wkt string to be assigned to the image. If None then it will be read from the wktStringFile.

  • wktFile – is a file path to a text file containing the WKT string to be assigned. This is ignored if wktString is not None.

Example:

from rsgislib import imageutils
wktString = '''PROJCS["WGS 84 / UTM zone 55S",
 GEOGCS["WGS 84",
     DATUM["WGS_1984",
         SPHEROID["WGS 84",6378137,298.257223563,
             AUTHORITY["EPSG","7030"]],
         AUTHORITY["EPSG","6326"]],
     PRIMEM["Greenwich",0],
     UNIT["degree",0.0174532925199433],
     AUTHORITY["EPSG","4326"]],
 PROJECTION["Transverse_Mercator"],
 PARAMETER["latitude_of_origin",0],
 PARAMETER["central_meridian",147],
 PARAMETER["scale_factor",0.9996],
 PARAMETER["false_easting",500000],
 PARAMETER["false_northing",10000000],
 UNIT["metre",1,
     AUTHORITY["EPSG","9001"]],
 AUTHORITY["EPSG","32755"]]'''
inputImage = './TestOutputs/injune_p142_casi_sub_utm.kea'
imageutils.assignProj(inputImage, wktString)
rsgislib.imageutils.assignSpatialInfo(inputImage, tlX, tlY, resX, resY, rotX, rotY)

Assign the spatial information to an input GDAL image file.

Where:

Parameters
  • inputImage – is a string containing the name and path of the input file

  • tlX – is a double representing the top left X coordinate of the image.

  • tlY – is a double representing the top left Y coordinate of the image.

  • resX – is a double representing X resolution of the image.

  • resY – is a double representing Y resolution of the image.

  • rotX – is a double representing X rotation of the image.

  • rotY – is a double representing Y rotation of the image.

rsgislib.imageutils.copyProjFromImage(inputImage, refImage)

Copy the projection from a reference image to an input GDAL image file.

Where:

Parameters
  • inputImage – is a string containing the name and path of the input file

  • refImage – is a string containing the name and path of the reference image.

rsgislib.imageutils.copySpatialAndProjFromImage(inputImage, refImage)

Copy the spatial information and projection from a reference image to an input GDAL image file.

Where:

Parameters
  • inputImage – is a string containing the name and path of the input file

  • refImage – is a string containing the name and path of the reference image.

rsgislib.imageutils.resampleImage2Match(inRefImg, inProcessImg, outImg, gdalformat, interpMethod, datatype=None, noDataVal=None, multicore=False)

A utility function to resample an existing image to the projection and/or pixel size of another image.

Where:

Parameters
  • inRefImg – is the input reference image to which the processing image is to resampled to.

  • inProcessImg – is the image which is to be resampled.

  • outImg – is the output image file.

  • gdalformat – is the gdal format for the output image.

  • interpMethod – is the interpolation method used to resample the image [bilinear, lanczos, cubicspline, nearestneighbour, cubic, average, mode]

  • datatype – is the rsgislib datatype of the output image (if none then it will be the same as the input file).

  • multicore – use multiple processing cores (Default = False)

rsgislib.imageutils.reprojectImage(inputImage, outputImage, outWKT, gdalformat='KEA', interp='cubic', inWKT=None, noData=0.0, outPxlRes='image', snap2Grid=True, multicore=False)

This function provides a tool which uses the gdalwarp function to reproject an input image.

Where:

Parameters
  • inputImage – the input image name and path

  • outputImage – the output image name and path

  • outWKT – a WKT file representing the output projection

  • gdalformat – the output image file format (Default is KEA)

  • interp – interpolation algorithm. Options are: near, bilinear, cubic, cubicspline, lanczos, average, mode. (Default is cubic)

  • inWKT – if input image is not well defined this is the input image projection as a WKT file (Default is None, i.e., ignored)

  • noData – float representing the not data value (Default is 0.0)

  • outPxlRes – three inputs can be provided 1) ‘image’ where the output resolution will match the input (Default is image) 2) ‘auto’ where an output resolution maintaining the image size of the input image will be used 3) provide a floating point value for the image resolution (note. pixels will be sqaure)

  • snap2Grid – is a boolean specifying whether the TL pixel should be snapped to a multiple of the pixel resolution (Default is True).

  • nCores – the number of processing cores available for processing (-1 is all cores: Default=-1)

rsgislib.imageutils.getWKTProjFromImage(inImg)

A function which returns the WKT string representing the projection of the input image.

Parameters

inImg – input image from which WKT string will be read.

Mosaic

rsgislib.imageutils.createImageMosaic(inputimagelist, outputimage, backgroundVal, skipVal, skipBand, overlapBehaviour, gdalformat, datatype)

Create mosaic from list of input images.

Where

Parameters
  • inputimagelist – is a list of input images.

  • outputimage – is a string containing the name of the output mosaic

  • backgroundVal – is a float providing the background (nodata) value for the mosaic

  • skipVal – is a float providing the value to be skipped (nodata values) in the input images

  • skipBand – is an integer providing the band to check for skipVal

  • overlapBehaviour – is an integer specifying the behaviour for overlaping regions * 0 - Overwrite * 1 - Overwrite if value of new pixel is lower (minimum) * 2 - Overwrite if value of new pixel is higher (maximum)

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

import rsgislib
from rsgislib import imageutils
import glob

# Search for all files with the extension 'kea'
inputList = glob.glob('./TestOutputs/Tiles/*.kea')
outImage = './TestOutputs/injune_p142_casi_sub_utm_mosaic.kea'
backgroundVal = 0.
skipVal = 0.
skipBand = 1
overlapBehaviour = 0
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.createImageMosaic(inputList, outImage, backgroundVal, skipVal, skipBand, overlapBehaviour, gdalformat, datatype)
rsgislib.imageutils.includeImages(baseImage, inputImages, inputBands=None, skipVal=None)

Create mosaic from list of input images.

Where:

Parameters
  • baseImage – is a string containing the name of the input image to add image to

  • inputimagelist – is a list of input images

  • inputBands – is a subset of input bands to use (optional)

  • skipVal – is a float specifying a value which should be ignored and not copied into the new image (optional). To use you must also provided a list of subset image bands.

Example:

import rsgislib
from rsgislib import imageutils
import glob
# Search for all files with the extension 'kea'
baseImage = './TestOutputs/injune_p142_casi_sub_utm_mosaic.kea'
inputList = glob.glob('./TestOutputs/Tiles/*.kea')
imageutils.includeImages(baseImage, inputList)
rsgislib.imageutils.includeImagesWithOverlap(baseImage, inputImages, pxlOverlap)

Create mosaic from list of input images where the input images have an overlap.

Where:

Parameters
  • baseImage – is a string containing the name of the input image to add image to

  • inputimagelist – is a list of input images

  • inputBands – is a subset of input bands to use (optional)

Example:

     import rsgislib
     from rsgislib import imageutils
     import glob
inputImg = 'LandsatImg.kea'
tilesImgBase = './tiles/LandsatTile'
outputImg = 'LandsatImgProcessed.kea'
imageutils.createTiles(inputImg, tilesImgBase, 1000, 1000, 10, False, 'KEA', rsgislib.TYPE_32FLOAT, 'kea')
# Do some processing on the tiles... 
imageutils.createCopyImage(inputImg, outputImg, 6, 0, 'KEA', rsgislib.TYPE_32FLOAT)
     inputList = glob.glob('./tiles/LandsatTile*.kea')
     imageutils.includeImagesWithOverlap(outputImg, inputList, 10)
rsgislib.imageutils.includeImagesIndImgIntersect(baseImage, inputImages)

Create mosaic from list of input images written to the base image. The no data value will be honered and values over written.

Where:

Parameters
  • baseImage – is a string containing the name of the input image to add image to

  • inputimagelist – is a list of input images

Example:

import rsgislib
from rsgislib import imageutils
import glob
# Search for all files with the extension 'kea'
baseImage = './TestOutputs/injune_p142_casi_sub_utm_mosaic.kea'
inputList = glob.glob('./TestOutputs/Tiles/*.kea')
imageutils.includeImagesIndImgIntersect(baseImage, inputList)
rsgislib.imageutils.combineImages2Band(inimages=list, outimage=string, gdalformat=string, datatype=int, nodata=float)

Combine images together into a single image band by excluding the no data value.

Where:

Parameters
  • inimages – is a list of strings containing the names and paths of the input image files

  • outimage – is a string containing the name of the output file.

  • gdalformat – is a string with the GDAL output file format.

  • datatype – is an containing one of the values from rsgislib.TYPE_*

  • nodata – is the no data value which will be ignored (Default is 0)

Example:

from rsgislib import imageutils
inputImages = ['./forest.kea', './urban.kea', './water.kea']
outputImage = './classes.kea'
datatype = rsgislib.TYPE_8UINT
format = 'KEA'
imageutils.combineImages2Band(inputImages, outputImage, format, datatype, 0.0)

Composite

rsgislib.imageutils.imagecomp.createMaxNDVIComposite(inImgsPattern, rBand, nBand, outRefImg, outCompImg, tmpPath='./tmp', gdalformat='KEA', dataType=None, calcStats=True)

Create an image composite from multiple input images where the pixel brought through into the composite is the one with the maximum NDVI.

Parameters
  • inImgsPattern – is a pattern (ready for glob.glob(inImgsPattern)) so needs an ‘*’ within the pattern to find the input image files.

  • rBand – is the image band within the input images (same for all) for the red band - note band indexing starts at 1.

  • nBand – is the image band within the input images (same for all) for the nir band - note band indexing starts at 1.

  • outRefImg – is the output reference image which details which input image is forming the output image pixel value (Note. this file will always be a KEA file as RAT is used).

  • outCompImg – is the output composite image for which gdalformat and dataType define the format and data type.

  • tmpPath – is a temp path for intemediate files, if this path doesn’t exist is will be created and deleted at runtime.

  • gdalformat – is the output file format of the outCompImg, any GDAL compatable format is OK (Defaut is KEA).

  • dataType – is the data type of the output image (outCompImg). If None is provided then the data type of the first input image will be used (Default None).

  • calcStats – calculate image statics and pyramids (Default=True)

rsgislib.imageutils.imagecomp.createMaxNDVINDWIComposite(refImg, inImages, rBand, nBand, sBand, outRefImg, outCompImg, outMskImg, tmpPath='./tmp', gdalformat='KEA', dataType=None, calcStats=True, reprojmethod='cubic', use_mode=True)

Create an image composite from multiple input images where the pixel brought through into the composite is the one with the maximum NDVI over land and NDWI over water. A mask of land and water regions is also produced. The reference image is used to define the spatial extent of the output images and spatial projection.

Parameters
  • refImg – is a reference image with any number of bands and data type which is used to define the output image extent and projection.

  • inImages – a list of all the input images being used to build the composite.

  • rBand – is an integer specifying the red band in the input images (starts at 1), used in the NDVI index.

  • nBand – is an integer specifying the NIR band in the input images (starts at 1), used in the NDVI and NDWI index.

  • sBand – is an integer specifying the SWIR band in the input images (starts at 1), used in the NDVI and NDWI index.

  • outRefImg – is the output reference image which details which input image is forming the output image pixel value (Note. this file will always be a KEA file as RAT is used).

  • outCompImg – is the output composite image for which gdalformat and dataType define the format and data type.

  • outMskImg – is the output mask image for regions of water and land where ndvi vs ndwi are used (0=nodata, 1=land, 2=water)

  • tmpPath – is a temp path for intemediate files, if this path doesn’t exist is will be created and deleted at runtime.

  • gdalformat – is the output file format of the outCompImg, any GDAL compatable format is OK (Defaut is KEA).

  • dataType – is the data type of the output image (outCompImg). If None is provided then the data type of the first input image will be used (Default None).

  • calcStats – calculate image statics and pyramids (Default=True)

:param reprojmethod : specifies the interpolation method used to reproject the input images which are in a different projection and/or pixel size as the reference image (default: cubic). :param use_mode: True: the land/water masks are combined using the mode and False: the land water masks are combined using median.

rsgislib.imageutils.imagecomp.createMaxNDVINDWICompositeLandsat(inImgsPattern, outRefImg, outCompImg, outMskImg, tmpPath='./tmp', gdalformat='KEA', dataType=None, calcStats=True, use_mode=True)

Create an image composite from multiple input images where the pixel brought through into the composite is the one with the maximum NDVI over land and NDWI over water. A mask of land and water regions is also produced. Landsat 8 images are identified as image file names are expected to start ‘LS8’. If composite includes a mix of LS8 and LS7 images then the LS8 images are submitted to match the images bands of LS7 (i.e., coastal band removed).

Parameters
  • inImgsPattern – is a pattern (ready for glob.glob(inImgsPattern)) so needs an ‘*’ within the pattern to find the input image files.

  • outRefImg – is the output reference image which details which input image is forming the output image pixel value (Note. this file will always be a KEA file as RAT is used).

  • outCompImg – is the output composite image for which gdalformat and dataType define the format and data type.

  • outMskImg – is the output mask image for regions of water and land where ndvi vs ndwi are used (0=nodata, 1=land, 2=water)

  • tmpPath – is a temp path for intemediate files, if this path doesn’t exist is will be created and deleted at runtime.

  • gdalformat – is the output file format of the outCompImg, any GDAL compatable format is OK (Defaut is KEA).

  • dataType – is the data type of the output image (outCompImg). If None is provided then the data type of the first input image will be used (Default None).

  • calcStats – calculate image statics and pyramids (Default=True)

  • use_mode – True: the land/water masks are combined using the mode and False: the land water masks are combined using median.

rsgislib.imageutils.imagecomp.checkBuildLS8VRTs(in_imgs, outdir)

A function which checks for Landsat 8 (LS8) images in the input list and creates a band subset (i.e., removes the coastal (1) band). This function should be used ahead of createMaxNDVINDWIComposite when combining LS8 with earlier landsat (i.e., LS5 and LS7) data. Note, files who’s file name contain ‘LS8’ are considered to be Landsat 8 images.

Parameters
  • in_imgs – input list of image file paths.

  • outdir – output directory for the VRT images (Note. an absolute path to the input image is used when building the VRT.)

rsgislib.imageutils.genTimeseriesFillCompositeImg(compInfo=list, validMask=string, outRefFillImg=string, outCompImg=string, gdalformat=string, datatype=int)

A function which aids the creation of timeseries composites. This function uses reference images to identify which pixels should be used to in-fill composite gaps.

Where:

Parameters
  • compInfo – is a list of rsgislib.imageutils.RSGISTimeseriesFillInfo objects

  • validMask – is a string with the name and path to an image specifying the valid area within which the compsites are being generated.

  • outRefFillImg

  • outCompImg

  • outCompRefImg

  • gdalformat – is a string with the GDAL outCompImg file format.

  • datatype – is an integer containing one of the values from rsgislib.TYPE_*, used for outCompImg

rsgislib.imageutils.createRefImgCompositeImg(inimages=list, outimage=string, refimg=string, gdalformat=string, datatype=int, outnodata=float)

A function which creates a composite image where the pixel values going into the output image by the reference image. The reference image can be created using the rsgislib.imagecalc.getImgIdxForStat function.

Where:

Parameters
  • inimages – is a list of input images, each image must have the same number of bands in the same order.

  • outputImage – is a string with the name and path of the output image.

  • refimg – is an image which specifies index of the image in inimages for which output pixel will be derived. Indexes start at 1, where 0 is no data.

  • gdalformat – is a string with the GDAL output file format.

  • datatype – is an integer containing one of the values from rsgislib.TYPE_*

  • outnodata – is the value which will be given to no data pixels in the output image.

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.imageutils.combineBinaryMasks(msk_imgs_dict, out_img, output_lut, gdalformat='KEA')

A function which combines up to 8 binary image masks to create a single output image with a unique value for each combination of intersecting masks. A JSON LUT is also generated to identify the image values to a ‘class’.

Parameters
  • msk_imgs_dict – dict of input images.

  • out_img – output image file.

  • output_lut – output file path to JSON LUT file identifying the image values.

  • gdalformat – output GDAL format (e.g., KEA)

rsgislib.imageutils.exportSingleMergedImgBand(inputImg=string, inputBandRefImg=string, outputImg=string, gdalformat=string, datatype=int)

A function which exports a single image band where the reference image specifies from which image band the output pixel is extracted from.

Where:

Parameters
  • inputImg – is a string for the full (multi-band) image.

  • inputBandRefImg – is a string with the reference image specifying the band to be outputted for each pixel.

  • outputImg – is a string for the single band output image.

  • gdalformat – is a string with the GDAL outCompImg file format.

  • datatype – is an integer containing one of the values from rsgislib.TYPE_*, used for outCompImg

Tile

rsgislib.imageutils.createTiles(inputimage, baseimage, width, height, overlap, offsettiling, gdalformat, datatype, ext)

Create tiles from a larger image, useful for splitting a large image into multiple smaller ones for processing.

Where

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

  • baseimage – is a string containing the base name of the output file the number of the tile and file extension will be appended.

  • width – is the width of each tile, in pixels.

  • height – is the height of each tile, in pixels.

  • overlap – is the overlap between tiles, in pixels

  • offsettiling – is a bool, determining if tiles should start halfway into the image useful for generating overlapping sets of tiles.

  • gdalformat – is a string providing the output gdalformat of the tiles (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the output data type of the tiles.

  • ext – is a string providing the extension for the tiles (as required by the specified data type).

Returns

list of tile file names

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outBase = './TestOutputs/Tiles/injune_p142_casi_sub_utm'
width = 100
height = width
overlap = 5
offsettiling = False
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32INT
ext='kea'
tiles = imageutils.createTiles(inputImage, outBase, width, height, overlap, offsettiling, gdalformat, datatype, ext)
rsgislib.imageutils.createTilesMultiCore(inputimage, baseimage, width, height, gdalformat, datatype, ext, ncores=1)

Function to generate a set of tiles for the input image.

Parameters
  • inputimage – input image to be subset.

  • baseimage – output image files base path.

  • width – width in pixels of the tiles.

  • height – height in pixels of the tiles.

  • gdalformat – output image file format

  • datatype – datatype is a rsgislib.TYPE_* value providing the data type of the output image.

  • ext – output file extension to be added to the baseimage path (e.g., kea)

  • ncores – number of cores to be used; uses python multiprocessing module.

rsgislib.imageutils.tilingutils.createMinDataTiles(inputImage, outshp, outclumpsFile, width, height, validDataThreshold, maskIntersect=None, offset=False, force=True, tmpdir='tilestemp', inImgNoDataVal=0.0)

A function to create a tiling for an input image where each tile has a minimum amount of valid data.

Where:

Parameters
  • inputImage – is a string for the image to be tiled

  • outshp – is a string for the output shapefile the tiling will be written to (if None a shapefile won’t be outputted).

  • outclumpsFile – is a string for the output image file containing the tiling

  • width – is an int for the width of the tiles

  • height – is an int for the height of the tiles

  • validDataThreshold – is a float (0-1) with the proportion of valid data needed within a tile.

  • force – is a boolean (default True) to delete the output shapefile if it already exists.

  • tmpdir – is a string with a temporary directory for temp outputs to be stored (they will be deleted). if tmpdir doesn’t exist it will be created and then deleted during the processing.

  • inImgNoDataVal – is a float for providing the input image no data value (Default: 0.0)

rsgislib.imageutils.tilingutils.createTileMaskImagesFromShp(inputImage, tileShp, tilesNameBase, tilesMaskDIR, tmpdir='tilestemp', imgFormat='KEA')

A function to create individual image masks from the tiles shapefile which can be individually used to mask (using rsgislib mask function) each tile from the inputimage.

Where:

Parameters
  • inputImage – is the input image being tiled.

  • tileShp – is a shapefile containing the shapefile tiles.

  • tilesNameBase – is the base file name for the tile masks

  • tilesMaskDIR – is the directory where the output images will be outputted

  • tmpdir – is a string with a temporary directory for temp outputs to be stored (they will be deleted) If tmpdir doesn’t exist it will be created and then deleted during the processing.

rsgislib.imageutils.tilingutils.createTileMaskImagesFromClumps(clumpsImage, tilesNameBase, tilesMaskDIR, gdalformat='KEA')

A function to create individual image masks from the tiles shapefile which can be individually used to mask (using rsgislib mask function) each tile from the inputimage.

Where:

Parameters
  • clumpsImage – is an image file with RAT where each clump represented a tile region.

  • tilesNameBase – is the base file name for the tile masks

  • tilesMaskDIR – is the directory where the output images will be outputted

  • gdalformat – is the output image file format of the tile masks

rsgislib.imageutils.tilingutils.createTilesFromMasks(inputImage, tilesBase, tilesMetaDIR, tilesImgDIR, datatype, gdalformat)

A function to apply the image tile masks defined in createTileMaskImages to the input image to extract the individual tiles.

Where:

Parameters
  • inputImage – is the input image being tiled.

  • tileMasksBase – is the base path for the tile masks. glob will be used to find them with *.kea added to the end.

  • outTilesBase – is the base file name for the tiles.

Visualisation / Normalisation

rsgislib.imageutils.stretchImage(inputimage, outputimage, saveoutstats, outstatsfile, ignorezeros, onepasssd, gdalformat, datatype, stretchtype, stretchparam)

Stretches (scales) pixel values to a range of 0 - 255, which is typically for visualisation but the function can also be used for normalisation.

Where:

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

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

  • saveoutstats – is a bool specifying if stats should be saved to a text file.

  • outstatsfile – is a string providing the name of the file to save stats to.

  • ignorezeros – is a bool specifying if pixels with a value of zero should be ignored.

  • onepasssd – is a bool specifying if is single pass should be used for calculating standard deviation (faster but less accurate)

  • gdalformat – is a string providing the output gdalformat of the tiles (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the output data type.

  • stretchtype – is a STRETCH_* value providing the type of stretch, options are: * imageutils.STRETCH_LINEARMINMAX - Stretches between min and max. * imageutils.STRETCH_LINEARPERCENT - Stretches between percentage of image range. Parameter defines percent. * imageutils.STRETCH_LINEARSTDDEV - Stretches between mean - sd to mean + sd. Parameter defines number of standard deviations. * imageutils.STRETCH_EXPONENTIAL - Exponential stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_LOGARITHMIC - Logarithmic stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_POWERLAW - Power law stretch between mean - 2*sd to mean + 2*sd. Parameter defines power.

  • stretchparam – is a float, providing the input parameter to the stretch (if required).

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_2sd.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_8INT
imageutils.stretchImage(inputImage, outputImage, False, '', True, False, gdalformat, datatype, imageutils.STRETCH_LINEARSTDDEV, 2)
rsgislib.imageutils.stretchImageWithStats(inputimage, outputimage, instatsfile, gdalformat, datatype, stretchtype, stretchparam)

Stretches (scales) pixel values to a range of 0 - 255, which is typically for visualisation but the function can also be used for normalisation. This function uses pre-calculated statistics - normally from rsgislib.imageutils.stretchImage.

Where:

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

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

  • instatsfile – is a string providing the name of the file to read stats from.

  • ignorezeros – is a bool specifying if pixels with a value of zero should be ignored.

  • onepasssd – is a bool specifying if is single pass should be used for calculating standard deviation (faster but less accurate)

  • gdalformat – is a string providing the output gdalformat of the tiles (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the output data type.

  • stretchtype – is a STRETCH_* value providing the type of stretch, options are: * imageutils.STRETCH_LINEARMINMAX - Stretches between min and max. * imageutils.STRETCH_LINEARPERCENT - Stretches between percentage of image range. Parameter defines percent. * imageutils.STRETCH_LINEARSTDDEV - Stretches between mean - sd to mean + sd. Parameter defines number of standard deviations. * imageutils.STRETCH_EXPONENTIAL - Exponential stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_LOGARITHMIC - Logarithmic stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_POWERLAW - Power law stretch between mean - 2*sd to mean + 2*sd. Parameter defines power.

  • stretchparam – is a float, providing the input parameter to the stretch (if required).

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
inputImageStats = './Rasters/injune_p142_casi_sub_utm_stats.txt'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_2sd.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_8UINT
imageutils.stretchImageWithStats(inputImage, outputImage, inputImageStats, True, False, gdalformat, datatype, imageutils.STRETCH_LINEARSTDDEV, 2)
rsgislib.imageutils.normaliseImagePxlVals(inputimage=string, outputimage=string, gdalformat=string, datatype=rsgislib.TYPE_*, innodataval=float, outnodataval=float, outmin=float, outmax=float, stretchtype=imageutils.STRETCH_*, stretchparam=float)

Normalises the image pixel values to a range of outmin to outmax (default 0-1) where the no data value is specified by the user. This function is largely similar to rsgislib.imageutils.stretchImage but deals with no data values correctly and intended for data processing normalisation rather than visualisation.

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 providing the output gdalformat of the tiles (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the output data type.

  • innodataval – is a float with the input image no data value. (Default = 0)

  • outnodataval – is a float with the no data value used within the output image. (Default = -1)

  • outmin – is a float which specifies the output minimum pixel value (Default = 0)

  • outmax – is a float which specifies the output maximum pixel value (Default = 1)

  • stretchtype – is a STRETCH_* value providing the type of stretch, options are: * imageutils.STRETCH_LINEARMINMAX - Stretches between min and max. * imageutils.STRETCH_LINEARPERCENT - Stretches between percentage of image range. Parameter defines percent. * imageutils.STRETCH_LINEARSTDDEV - Stretches between mean - sd to mean + sd. Parameter defines number of standard deviations. * imageutils.STRETCH_EXPONENTIAL - Exponential stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_LOGARITHMIC - Logarithmic stretch between mean - 2*sd to mean + 2*sd. No parameter. * imageutils.STRETCH_POWERLAW - Power law stretch between mean - 2*sd to mean + 2*sd. Parameter defines power.

  • stretchparam – is a float, providing the input parameter to the stretch (if required; Default=2.0).

Example:

import rsgislib
import rsgislib.imageutils

inImg = './LS5TM_19851990Comp_lat7lon3896_r65p166_stdsref.kea'

outImg = 'LS5TM_19851990Comp_lat7lon3896_r65p166_stdsref_NORM_0-255.kea'
rsgislib.imageutils.normaliseImagePxlVals(inImg, outImg, 'KEA', rsgislib.TYPE_8UINT, innodataval=0, outnodataval=0, outmin=0, outmax=255,
                                          stretchtype=rsgislib.imageutils.STRETCH_LINEARSTDDEV, stretchparam=2)
rsgislib.imageutils.popImageStats(outImg, usenodataval=True, nodataval=0, calcpyramids=True)

outImg = 'LS5TM_19851990Comp_lat7lon3896_r65p166_stdsref_NORM_0-1.kea'
rsgislib.imageutils.normaliseImagePxlVals(inImg, outImg, 'KEA', rsgislib.TYPE_32FLOAT, innodataval=0, outnodataval=0, outmin=0, outmax=1,
                                          stretchtype=rsgislib.imageutils.STRETCH_LINEARSTDDEV, stretchparam=2)
rsgislib.imageutils.popImageStats(outImg, usenodataval=True, nodataval=0, calcpyramids=True)

Subset / Mask

rsgislib.imageutils.maskImage(inputimage, imagemask, outputimage, gdalformat, datatype, outvalue, maskvalue)

This command will mask an input image using a single band mask image - commonly this is a binary image.

Where:

Parameters
  • inputImage – is a string containing the name and path of the input image file.

  • imagemask – is a string containing the name and path of the mask image file.

  • outputimage – is a string containing the name and path for the output image following application of the mask.

  • gdalformat – is a string representing the output image file format (e.g., KEA, ENVI, GTIFF, HFA etc).

  • datatype – is a rsgislib.TYPE_* value for the data type of the output image.

  • outvalue – is a float representing the value written to the output image in place of the regions being masked.

  • maskvalue – is a float or list of floats representing the value(s) within the mask image for the regions which are to be replaced with the outvalue.

Example:

import rsgislib
from rsgislib import imageutils

inImg = './LS5/Outputs/LS5TM_20110926_lat53lon511_r23p205_rad_toa.kea'
imgMask = './LS5/Outputs/LS5TM_20110926_lat53lon511_r23p205_clouds.kea'
outImg = './LS5/Outputs/LS5TM_20110926_lat53lon511_r23p205_rad_toa_mclds.kea'

imageutils.maskImage(inImg, imgMask, outImg, 'KEA', rsgislib.TYPE_16UINT, 0, [1,2])
imageutils.popImageStats(outImg, True, 0.0, True)
rsgislib.imageutils.subset(inputimage, inputvector, outputimage, gdalformat, datatype)

Subset an image to the bounding box of a vector.

Where:

Parameters
  • inputimage – is a string providing the name of the input file.

  • inputvector – is a string providing the vector which the image is to be clipped to.

  • outputimage – is a string providing the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
inputVector = './Vectors/injune_p142_plot_location_utm.shp'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_subset.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.subset(inputImage, inputVector, outputImage, gdalformat, datatype)
rsgislib.imageutils.subset2img(inputimage, inputROIimage, outputimage, gdalformat, type)

Subset an image to the bounding box of an image.

Where:

Parameters
  • inputimage – is a string providing the name of the input file.

  • inputROIimage – is a string providing the image which the ‘inputimage’ is to be clipped to.

  • outputimage – is a string providing the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
inputROIimage = './Vectors/injune_p142_roi.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_subset.kea'
gdalformat = 'KEA'
gdaltype = rsgislib.TYPE_32FLOAT
imageutils.subset2img(inputImage, inputROIimage, outputImage, gdalformat, datatype)
rsgislib.imageutils.subset2polys()

rsgislib.imageutils.subset(inputimage, inputvector, attribute, baseimage, gdalformat, datatype, ext) Subset an image to the bounding box of a each polygon in an input vector. Useful for splitting an image into tiles of unequal sizes.

Where:

Parameters
  • inputimage – is a string providing the name of the input file.

  • inputvector – is a string providing the vector which the image is to be clipped to.

  • attribute – is a string providing the attribute in the vector to use for the ouput name

  • baseimage – is a string providing the base name of the output file. The specified attribute of each polygon and extension will be appended.

  • gdalformat – is a string providing the output gdalformat of the subsets (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the output data type of the subsets.

  • ext – is a string providing the extension for the tiles (as required by the specified data gdalformat).

Returns

A list of strings containing the filenames.

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
inputVector = './Vectors/injune_p142_plot_location_utm.shp'
attribute = 'PLOTNO'
outputImageBase = './TestOutputs/injune_p142_casi_sub_utm_subset_polys_'
gdalformat = 'KEA'
gdaltype = rsgislib.TYPE_32FLOAT
ext = 'kea'
imageutils.subset2polys(inputImage, inputVector, attribute, outputImageBase, gdalformat, gdaltype, ext)
rsgislib.imageutils.subsetImgs2CommonExtent(inImagesDict, outShpEnv, gdalformat)

A command to subset a set of images to the same overlapped extent.

Where:

Parameters
  • inImagesDict – is a list of dictionaries containing values for IN (input image) OUT (output image) and TYPE (data type for output)

  • outShpEnv – is a file path for the output shapefile representing the overlap extent.

  • gdalformat – is the gdal format of the output images.

Example:

from rsgislib import imageutils

inImagesDict = []
inImagesDict.append({'IN': './Images/Lifeformclip.tif', 'OUT':'./Subsets/Lifeformclip_sub.kea', 'TYPE':rsgislib.TYPE_32INT})
inImagesDict.append({'IN': './Images/chmclip.tif', 'OUT':'./Subsets/chmclip_sub.kea', 'TYPE':rsgislib.TYPE_32FLOAT})
inImagesDict.append({'IN': './Images/peakBGclip.tif', 'OUT':'./Subsets/peakBGclip_sub.kea', 'TYPE':rsgislib.TYPE_32FLOAT})

outputVector = 'imgSubExtent.shp'
imageutils.subsetImgs2CommonExtent(inImagesDict, outputVector, 'KEA')
rsgislib.imageutils.subsetbbox(inputimage, outputimage, gdalformat, datatype, xMin, xMax, yMin, yMax)

Subset an image to the bounding box of a vector.

Where:

Parameters
  • inputimage – is a string providing the name of the input file.

  • outputimage – is a string providing the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

  • xMin – double within the minimum X for the bounding box

  • xMax – double within the maximum X for the bounding box

  • yMin – double within the minimum Y for the bounding box

  • yMax – double within the maximum X for the bounding box

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_subset.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
xMin = 295371.5
xMax = 295401.5
yMin = 359470.8
yMax = 359500.8
imageutils.subsetbbox(inputImage, outputImage, gdalformat, datatype, xMin, xMax, yMin, yMax)
rsgislib.imageutils.subsetPxlBBox(inputimage, outputimage, gdalformat, datatype, xMinPxl, xMaxPxl, yMinPxl, yMaxPxl)

Function to subset an input image using a defined pixel bbox.

Parameters
  • inputimage – input image to be subset.

  • outputimage – output image file.

  • gdalformat – output image file format

  • datatype – datatype is a rsgislib.TYPE_* value providing the data type of the output image.

  • xMinPxl – min x in pixels

  • xMaxPxl – max x in pixels

  • yMinPxl – min y in pixels

  • yMaxPxl – max y in pixels

rsgislib.imageutils.buildImgSubDict(globFindImgsStr, outDir, suffix, ext)

Automate building the dictionary of image to be used within the subsetImgs2CommonExtent(inImagesDict, outShpEnv, imgFormat) function.

Where:

Parameters
  • globFindImgsStr – is a string to be passed to the glob module to find the input image files.

  • outDir – is the output directory path for the images.

  • suffix – is a suffix to be appended on to the end of the file name (can be a blank string, i.e., ‘’)

  • ext – is a string with the output file extension

Example:

from rsgislib import imageutils

inImagesDict = imageutils.buildImgSubDict("./Images/*.tif", "./Subsets/", "_sub", ".kea")
print(inImagesDict)

outputVector = 'imgSubExtent.shp'
imageutils.subsetImgs2CommonExtent(inImagesDict, outputVector, 'KEA')
rsgislib.imageutils.genFiniteMask(inimage=string, outimage=string, gdalformat=string)

Generate a binary image mask defining the finite image regions.

Where:

Parameters
  • inimage – is a string containing the name of the input file

  • outimage – is a string containing the name of the output file.

  • gdalformat – is a string with the GDAL output file format.

Example:

from rsgislib import imageutils
inputImage = './injune_p142_casi_sub_utm.kea'
outputImage = './injune_p142_casi_sub_utm.kea'
imageutils.genFiniteMask(inputImage, outputImage, 'KEA')
rsgislib.imageutils.genValidMask(inimages=string|list, outimage=string, gdalformat=string, nodata=float)

Generate a binary image mask defining the regions which are not ‘no data’.

Where:

Parameters
  • inimages – can be either a string or a list containing the input file(s)

  • outimage – is a string containing the name of the output file.

  • gdalformat – is a string with the GDAL output file format.

  • nodata – is a float defining the no data value (Optional and default is 0.0)

Example:

from rsgislib import imageutils
inputImage = './injune_p142_casi_sub_utm.kea'
outputImage = './injune_p142_casi_sub_utm.kea'
imageutils.genValidMask(inputImage, outputImage, 'KEA', 0.0)

Extract

rsgislib.imageutils.ImageBandInfo(fileName=None, name=None, bands=None)

Create a list of these objects to pass to the extractZoneImageBandValues2HDF function

Parameters
  • fileName – is the input image file name and path.

  • name – is a name associated with this layer - doesn’t really matter what you use but needs to be unique; this is used as a dict key in some functions.

  • bands – is a list of image bands within the fileName to be used for processing (band numbers start at 1).

rsgislib.imageutils.extractZoneImageValues2HDF(inputImage, imageMask, outputHDF, maskValue)

Extract the all the pixel values for raster regions to a HDF5 file (1 column for each image band).

Where:

Parameters
  • inputImage – is a string containing the name and path of the input file

  • imageMask – is a string containing the name and path of the input image mask file; the mask file must have only 1 image band.

  • outputHDF – is a string containing the name and path of the output HDF5 file

  • maskValue – is a float containing the value of the pixel within the mask for which values are to be extracted

rsgislib.imageutils.extractZoneImageBandValues2HDF(inputImageInfo, imageMask, outputHDF, maskValue)

Extract the all the pixel values for raster regions to a HDF5 file (1 column for each image band). Multiple input rasters can be provided and the bands extracted selected.

Where:

Parameters
  • inputImageInfo – is a list of rsgislib::imageutils::ImageBandInfo objects with the file names and list of image bands within that file to be extracted.

  • imageMask – is a string containing the name and path of the input image mask file; the mask file must have only 1 image band.

  • outputHDF – is a string containing the name and path of the output HDF5 file

  • maskValue – is a float containing the value of the pixel within the mask for which values are to be extracted

Example:

import rsgislib.imageutils
fileInfo = []
fileInfo.append(rsgislib.imageutils.ImageBandInfo('InputImg1.kea', 'Image1', [1,3,4]))
fileInfo.append(rsgislib.imageutils.ImageBandInfo('InputImg2.kea', 'Image2', [2]))
rsgislib.imageutils.extractZoneImageBandValues2HDF(fileInfo, 'ClassMask.kea', 'ForestRefl.h5', 1.0)
rsgislib.imageutils.mergeExtractedHDF5Data(h5Files, outH5File)

A function to merge a list of HDF files (e.g., from rsgislib.imageutils.extractZoneImageBandValues2HDF) with the same number of variables (i.e., columns) into a single file. For example, if class training regions have been sourced from multiple images.

Parameters
  • h5Files – a list of input files.

  • outH5File – the output file.

Example:

inTrainSamples = ['MSS_CloudTrain1.h5', 'MSS_CloudTrain2.h5', 'MSS_CloudTrain3.h5']
cloudTrainSamples = 'LandsatMSS_CloudTrainingSamples.h5'
rsgislib.imageutils.mergeExtractedHDF5Data(inTrainSamples, cloudTrainSamples)
rsgislib.imageutils.randomSampleHDF5File(inputh5, outputh5, sample, seed)

A function which randomly samples a HDF5 of extracted values.

Where:

Parameters
  • inputh5 – is a string with the path to the input file.

  • outputh5 – is a string with the path to the output file.

  • sample – is an integer with the number values to be sampled from the input file.

  • seed – is an integer which seeds the random number generator

.

rsgislib.imageutils.performRandomPxlSampleInMask(inputImage=string, outputImage=string, gdalformat=string, maskvals=int|list, numSamples=unsigned int)

Randomly sample with a mask (e.g., classification). The same number of samples will be identified within each mask value listed by maskvals.

Where:

Parameters
  • inputImage – is a string for the input image mask - mask is typically whole values within regions (e.g., classifications).

  • outputImage – is a string with the name and path of the output image. Output is the mask pixel values.

  • gdalformat – is a string with the GDAL output file format.

  • maskvals – can either be a single integer value or a list of values. If a list of values is specified then the total number of points identified (numSamples x n-maskVals).

  • numSamples – is the number of samples to be created within each region.

rsgislib.imageutils.performRandomPxlSampleInMaskLowPxlCount(inputImage=string, outputImage=string, gdalformat=string, maskvals=int|list, numSamples=unsigned int, rndSeed=int)

Randomly sample with a mask (e.g., classification). The same number of samples will be identified within each mask value listed by maskvals. This function produces a similar result to rsgislib.imageutils.performRandomPxlSampleInMask but is more efficient for classes where only a small number of pixels have that value. However, this function uses much more memory.

Where:

Parameters
  • inputImage – is a string for the input image mask - mask is typically whole values within regions (e.g., classifications).

  • outputImage – is a string with the name and path of the output image. Output is the mask pixel values.

  • gdalformat – is a string with the GDAL output file format.

  • maskvals – can either be a single integer value or a list of values. If a list of values is specified then the total number of points identified (numSamples x n-maskVals).

  • numSamples – is the number of samples to be created within each region.

  • rndSeed – is a an integer providing a seed for the random number generator. Please not that if this number is the same then the same random set of points will be generated.

rsgislib.imageutils.extractImgPxlSample(inputImg, pxlNSample, noData=None)

A function which extracts a sample of pixels from the input image file to a number array.

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, valid (if noData specified), pixel)

  • noData – provide a no data value which is to be ignored during processing. If None then ignored (Default: None)

Returns

outputs a numpy array (n sampled values, n bands)

rsgislib.imageutils.extractImgPxlValsInMsk(img, img_bands, img_mask, img_mask_val, no_data=None)

A function which extracts the image values within a mask for the specified image bands.

Parameters
  • img – the image from which the random sample will be taken.

  • img_bands – the image bands the values are to be read from.

  • img_mask – the image mask specifying the regions of interest.

  • img_mask_val – the pixel value within the mask defining the region of interest.

Returns

outputs a numpy array (n values, n bands)

rsgislib.imageutils.splitSampleHDF5File(inputh5, outputp1h5, outputp2h5, sample, seed)

A function which splits samples a HDF5 of extracted values.

Where:

Parameters
  • inputh5 – is a string with the path to the input file.

  • outputp1h5 – is a string with the path to the output file.

  • outputp2h5 – is a string with the path to the output file.

  • sample – is an integer with the number values to be sampled from the input file.

  • seed – is an integer which seeds the random number generator

.

Create

rsgislib.imageutils.createBlankImage(outputImage, numBands, width, height, tlX, tlY, res, pxlVal, wktFile, wktString, gdalformat, datatype)

Create a new blank image with the parameters specified.

Where:

Parameters
  • outputImage – is a string containing the name and path for the outputted image.

  • numBands – is an integer specifying the number of image bands in the output image.

  • width – is an integer specifying the width of the output image.

  • height – is an integer specifying the height of the output image.

  • tlX – is a double specifying the Top Left pixel X coordinate (eastings) of the output image.

  • tlY – is a double specifying the Top Left pixel Y coordinate (northings) of the output image.

  • res – is a double specifying the pixel resolution of the output image.

  • pxlVal – is a float specifying the pixel value of the output image.

  • wktFile – is a string specifying the location of a file containing the WKT string representing the coordinate system and projection of the output image (if specified this parameter overrides the wktString parameter).

  • wktString – is a string specifying the WKT string representing the coordinate system and projection of the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

rsgislib.imageutils.createBlankImgFromBBOX(bbox, wktstr, outputImg, outImgRes, outImgPxlVal, outImgNBands, gdalformat, datatype, snap2grid=False)

A function to create a new image file based on a bbox to define the extent.

Parameters
  • bbox – bounding box defining the extent of the output image (xMin, xMax, yMin, yMax)

  • wktstr – the WKT string defining the bbox and output image projection.

  • outputImg – output image file.

  • outImgRes – output image resolution, square pixels so a single value.

  • outImgPxlVal – output image pixel value.

  • outImgNBands – the number of image bands in the output image

  • gdalformat – output image file format.

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

  • snap2grid – optional variable to snap the image to a grid of whole numbers with respect to the image pixel resolution.

rsgislib.imageutils.createBlankImgFromRefVector(inVecFile, inVecLyr, outputImg, outImgRes, outImgNBands, gdalformat, datatype)

A function to create a new image file based on a vector layer to define the extent and projection of the output image.

Parameters
  • inVecFile – input vector file.

  • inVecLyr – name of the vector layer, if None then assume the layer name will be the same as the file name of the input vector file.

  • outputImg – output image file.

  • outImgRes – output image resolution, square pixels so a single value.

  • outImgNBands – the number of image bands in the output image

  • gdalformat – output image file format.

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image

rsgislib.imageutils.createCopyImage(inputImage, outputImage, numBands, pxlVal, gdalformat, datatype)

Create a new blank image with the parameters specified.

Where:

Parameters
  • inputImage – is a string containing the name and path for the input image, which is to be copied.

  • outputImage – is a string containing the name and path for the outputted image.

  • numBands – is an integer specifying the number of image bands in the output image.

  • pxlVal – is a float specifying the pixel value of the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_blank.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.createCopyImage(inputImage, outputImage, 1, 3, gdalformat, datatype)
rsgislib.imageutils.createCopyImageDefExtent(inputImage, outputImage, numBands, xMin, xMax, yMin, yMax, xRes, yRes, pxlVal, gdalformat, datatype)

Create a new blank image with the parameters specified.

Where:

Parameters
  • inputImage – is a string containing the name and path for the input image, which is to be copied.

  • outputImage – is a string containing the name and path for the outputted image.

  • numBands – is an integer specifying the number of image bands in the output image.

  • xMin – is a double specifying the X minimum coordinate of the output image.

  • xMax – is a double specifying the X maximum coordinate of the output image.

  • yMin – is a double specifying the Y minimum coordinate of the output image.

  • yMax – is a double specifying the Y maximum coordinate of the output image.

  • xRes – is a double specifying the X resolution of the output image.

  • yRes – is a double specifying the Y resolution of the output image.

  • pxlVal – is a float specifying the pixel value of the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

rsgislib.imageutils.createCopyImageVecExtent(inputImage, shpFile, outputImage, numBands, pxlVal, gdalformat, datatype)

Create a new blank image with the parameters specified but with the extent of the inputted shapefile.

Where:

Parameters
  • inputImage – is a string containing the name and path for the input image, which is to be copied.

  • shpFile – is a string specifying the name and path of the shapefile to which the image extent will be cut

  • outputImage – is a string containing the name and path for the outputted image.

  • numBands – is an integer specifying the number of image bands in the output image.

  • pxlVal – is a float specifying the pixel value of the output image.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
shpFile = './Rasters/injune_p142_roi.shp'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_blank.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.createCopyImageVecExtent(inputImage, shpFile, outputImage, 3, 1, gdalformat, datatype)
rsgislib.imageutils.createCopyImageVecExtentSnap2Grid(inVecFile, inVecLyr, outputImg, outImgRes, outImgNBands, gdalformat, datatype, bufnpxl=0)

A function to create a new image file based on a vector layer to define the extent and projection of the output image. The image file extent is snapped on to the grid defined by the vector layer.

Parameters
  • inVecFile – input vector file.

  • inVecLyr – name of the vector layer, if None then assume the layer name will be the same as the file name of the input vector file.

  • outputImg – output image file.

  • outImgRes – output image resolution, square pixels so a single value.

  • outImgNBands – the number of image bands in the output image

  • gdalformat – output image file format.

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image

  • bufnpxl – is an integer specifying the number of pixels to buffer the vector file extent by.

rsgislib.imageutils.createImageForEachVecFeat(vectorFile, vectorLyr, fileNameCol, outImgPath, outImgExt, outImgPxlVal, outImgNBands, outImgRes, gdalformat, datatype, snap2grid=False)

A function to create a set of image files representing the extent of each feature in the inputted vector file.

Parameters
  • vectorFile – the input vector file.

  • vectorLyr – the input vector layer

  • fileNameCol – the name of the column in the vector layer which will be used as the file names.

  • outImgPath – output file path (directory) where the images will be saved.

  • outImgExt – the file extension to be added on to the output file names.

  • outImgPxlVal – output image pixel value

  • outImgNBands – the number of image bands in the output image

  • outImgRes – output image resolution, square pixels so a single value

  • gdalformat – output image file format.

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

  • snap2grid – optional variable to snap the image to a grid of whole numbers with respect to the image pixel resolution.

Select / Stack bands

rsgislib.imageutils.selectImageBands(inputImage, outputImage, gdalformat, datatype, bands)

Copy selected image bands from an image to a new image.

Where:

Parameters
  • inputImage – is a string containing the name and path of the input file

  • outputImage – is a string containing the name and path of the output file.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

  • bands – is a list of integers for the bands in the input image to exported to the output image (Note band count starts at 1).

Example:

import rsgislib.imageutils
import rsgislib
bands = [1,2]
rsgislib.imageutils.selectImageBands('N06W053_07_ALL_sl_sub.kea', 'N06W053_07_ALL_sl_sub_HHVV.kea', 'KEA', rsgislib.TYPE_32INT, bands)
rsgislib.imageutils.stackImageBands(inputImages, imageBandNames, outputImage, skipValue, noDataValue, gdalformat, datatype)

Create a single image from list of input images through band stacking.

Where:

Parameters
  • inputImages – is a list of input images.

  • imageBandNames – is a list of band names (one for each input image). If None then ignored.

  • outputImage – is a string containing the name and path for the outputted image.

  • skipVal – is a float providing the value to be skipped (nodata values) in the input images (If None then ignored)

  • noDataValue – is float specifying a no data value.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

import rsgislib
from rsgislib import imageutils
imageList = ['./Rasters/injune_p142_casi_sub_utm_single_band.vrt','./Rasters/injune_p142_casi_sub_utm_single_band.vrt']
bandNamesList = ['Image1','Image2']
outputImage = './TestOutputs/injune_p142_casi_sub_stack.kea'
gdalformat = 'KEA'
gdaltype = rsgislib.TYPE_32FLOAT
imageutils.stackImageBands(imageList, bandNamesList, outputImage, None, 0, gdalformat, gdaltype)

Sharpen Image Bands

rsgislib.imageutils.panSharpenHCS(inimage=string, outimage=string, gdalformat=string, datatype=int, winsize=unsigned int, useNaiveMethod=boolean)

A function which performs a Hyperspherical Colour Space (HSC) Pan Sharpening of an input image. Padwick, C., Deskevich, M., Pacifici, F., Smallwood, S. 2010. WorldView-2 Pan-Sharpening. ASPRS 2010 Annual Conference, San Diego, California (2010) pp. 26-30.

Where:

Parameters
  • inputImage – is a string for the input file, where the single panchromatic band must be the last in the stack.

  • outputImage – is a string with the name and path of the output image.

  • gdalformat – is a string with the GDAL output file format.

  • datatype – is an containing one of the values from rsgislib.TYPE_*

  • winsize – is an optional integer, which must be an odd number, specifying the window size used for the analysis (Default = 7; Only used if useNaiveMethod=False).

  • useNaiveMethod – is an optional boolean option to specify whether the naive or smart method should be used - False=Smart (Default), True=Naive Method.

Example:

import rsgislib
import rsgislib.imageutils

rsgislib.imageutils.resampleImage2Match('./14SEP03025718-P2AS-054000253010_01_P001.TIF', './14SEP03025718-M2AS-054000253010_01_P001.TIF',
                                    './14SEP03025718-M2AS-054000253010_01_P001_resample.kea', 'KEA', 'nearestneighbour', rsgislib.TYPE_16UINT)

rsgislib.imageutils.stackImageBands(['14SEP03025718-M2AS-054000253010_01_P001_resample.kea', '14SEP03025718-P2AS-054000253010_01_P001.TIF'],
                                     None, 'StackPanImg.kea', 0.0, 0.0, 'KEA', rsgislib.TYPE_16UINT)

rsgislib.imageutils.panSharpenHCS(inimage='StackPanImg.kea', outimage='StackPanImgSharp.kea', gdalformat='KEA', datatype=rsgislib.TYPE_16UINT)

rsgislib.imageutils.popImageStats('StackPanImgSharp.kea', usenodataval=True, nodataval=0, calcpyramids=True)
rsgislib.imageutils.SharpBandInfo(band=None, status=None, name=None)

Create a list of these objects to pass to the sharpenLowResBands function.

Parameters
  • band – is the band number (band numbering starts at 1).

  • status – needs to be either rsgislib.SHARP_RES_IGNORE, rsgislib.SHARP_RES_LOW or rsgislib.SHARP_RES_HIGH lowres bands will be sharpened using the highres bands and ignored bands will just be copied into the output image.

  • name – is a name associated with this image band - doesn’t really matter what you put in here.

rsgislib.imageutils.sharpenLowResBands(inimage=string, outimage=string, bandinfo=list, winsize=unsigned int, nodata=int, gdalformat=string, datatype=int)

A function which performs band sharpening using local linear fitting (orignal method proposed by Shepherd and Dymond).

Where:

Parameters
  • inimage – is a string for the input file where the high resolution input image bands have been resampled (recommend nearest neighbour) to the same resolution has the higher resolution bands

  • outimage – is a string with the name and path of the output image.

  • bandinfo – is a list of the input image bands (type: rsgislib.imageutils.SharpBandInfo) specifying the band number, name and status. the status is either rsgislib.SHARP_RES_IGNORE, rsgislib.SHARP_RES_LOW or rsgislib.SHARP_RES_HIGH

  • winsize – is an integer, which must be an odd number, specifying the window size (in pixels) used for the analysis (Default = 7). Recommend that the window size values fits at least 9 low resolution image pixels. For example, if the high resolution image is 10 m and the low 20 m then a 7 x 7 window will include 12.25 low resolution pixels.

  • nodata – is an integer specifying the no data value for the scene

  • gdalformat – is a string with the GDAL output file format.

  • datatype – is an containing one of the values from rsgislib.TYPE_*

Example:

import rsgislib
from rsgislib import imageutils

bandInfo = []
bandInfo.append(imageutils.SharpBandInfo(band=1, status=rsgislib.SHARP_RES_LOW, name='Blue'))
bandInfo.append(imageutils.SharpBandInfo(band=2, status=rsgislib.SHARP_RES_LOW, name='Green'))
bandInfo.append(imageutils.SharpBandInfo(band=3, status=rsgislib.SHARP_RES_LOW, name='Red'))
bandInfo.append(imageutils.SharpBandInfo(band=4, status=rsgislib.SHARP_RES_LOW, name='NIR'))
bandInfo.append(imageutils.SharpBandInfo(band=5, status=rsgislib.SHARP_RES_HIGH, name='PAN'))

imageutils.sharpenLowResBands(inimage='./wv2/wv2_20140903_panstack.kea',
                              outimage='./wv2/wv2_20140903_panstack_sharp.kea',
                              bandinfo=bandInfo, winsize=7, nodata=0,
                              gdalformat='KEA', datatype=rsgislib.TYPE_UINT16)

Band Names

rsgislib.imageutils.setBandNames(inputImage, bandNames, feedback=False)

A utility function to set band names. Where:

Parameters
  • inImage – is the input image

  • bandNames – is a list of band names

  • feedback – is a boolean specifying whether feedback will be printed to the console (True= Printed / False (default) Not Printed)

Example:

from rsgislib import imageutils

inputImage = 'injune_p142_casi_sub_utm.kea'
bandNames = ['446nm','530nm','549nm','569nm','598nm','633nm','680nm','696nm','714nm','732nm','741nm','752nm','800nm','838nm']

imageutils.setBandNames(inputImage, bandNames)
rsgislib.imageutils.getBandNames(inputImage)

A utility function to get band names.

Where:

Parameters

inImage – is the input image

Returns

list of band names

Example:

from rsgislib import imageutils

inputImage = 'injune_p142_casi_sub_utm.kea'
bandNames = imageutils.getBandNames(inputImage)

Image Data Types

rsgislib.imageutils.getGDALDataType(inImg)

Returns the rsgislib datatype ENUM for a raster file

Parameters

inImg – The file to get the datatype for

Returns

The rsgislib datatype enum, e.g., rsgislib.TYPE_8INT

rsgislib.imageutils.getRSGISLibDataType(inImg)

Returns the rsgislib datatype ENUM for a raster file

Parameters

inImg – The file to get the datatype for

Returns

The rsgislib datatype enum, e.g., rsgislib.TYPE_8INT

Other

rsgislib.imageutils.stackStats(inputImage, outputImage, numBands, stat, gdalformat, datatype)

Calculate statistics for every pixel in a stack of image. If all bands are used a single band image is produced with the specified statistics. If a number of bands are specified statistics are taken over every n bands to provide an image with B / n bands (where B is the number of input bands. For example, can be used to produce monthly composite images from a stack with images from every day.

Where:

Parameters
  • inputImage – is a string containing the name and path for the input image.

  • outputImage – is a string containing the name and path for the output image.

  • numBands – is an integer specifying the number of image bands in the output image, pass ‘None’ to use all bands.

  • stat – is a string providing the statistics to calculate, options are ‘mean’, ‘min’, ‘max’, and ‘range’.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image.

Example:

import rsgislib
from rsgislib import imageutils
inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_stackStats.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.stackStats(inputImage, outputImage, None, 'mean', gdalformat, datatype)
rsgislib.imageutils.orderImageUsingValidPxls(inputImages, noDataVal)

Order the list of input images based on the their proportion of valid image pixels. The primary use of this function is expected to be order (rank) images ahead of mosaicing.

Where:

Parameters
  • inputImages – is a list of string containing the name and path for the input images.

  • noDataVal – is a float which specifies the no data value used to defined ‘invalid’ pixels.

Returns

a list of images ordered, from low to high (i.e., the first image will be the image with the smallest number of valid image pixels).

rsgislib.imageutils.genSamplingGrid(onputImage, outputImage, gdalformat, pxlRes, minVal, maxVal, singleLine)

Generate a regular sampling grid.

Where:

Parameters
  • inputImage – is a string specifying an image which defines the area of interest.

  • outputImage – is a string specifying an output image location.

  • gdalformat – is a string providing the gdalformat of the output image (e.g., KEA).

  • pxlRes – is a float specifying the output image resolution.

  • minVal – is a minimum value for the output image pixel values.

  • maxVal – is a maximum value for the output image pixel values.

  • singleLine – is a boolean specifying whether the image is seen as a single line or new line with an offset in the starting value.

rsgislib.imageutils.calcPixelLocations(inputImg, outputImg, gdalformat)

Function which produces a 2 band output image with the X and Y locations of the image pixels.

Where:

Parameters
  • inputImg – the input reference 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.

rsgislib.imageutils.hasGCPs(inImg)

Test whether the input image has GCPs - returns boolean

Parameters

inImg – input image file

Returns

boolean True - has GCPs; False - does not have GCPs

rsgislib.imageutils.copyGCPs(srcImg, destImg)

Copy the GCPs from the srcImg to the destImg

Parameters
  • srcImg – Raster layer with GCPs

  • destImg – Raster layer to which GCPs will be added

rsgislib.imageutils.setImgThematic(imageFile)

Set all image bands to be thematic.

Parameters

imageFile – The file for which the bands are to be set as thematic

rsgislib.imageutils.doImagesOverlap(image1, image2, overThres=0.0)

Function to test whether two images overlap with one another. If the images have a difference projection/coordinate system then corners

Parameters
  • image1 – path to first image

  • image2 – path to second image

  • overThres – the amount of overlap required to return true (e.g., at least 1 pixel)

Returns

Boolean specifying whether they overlap or not.

Example:

import rsgislib.imageutils
img = "/Users/pete/Temp/LandsatStatsImgs/MSS/ClearSkyMsks/LS1MSS_19720823_lat52lon114_r24p218_osgb_clearsky.tif"
tile = "/Users/pete/Temp/LandsatStatsImgs/MSS/RefImages/LandsatWalesRegion_60m_tile8.kea"

overlap = rsgislib.imageutils.doImagesOverlap(tile, img)
print("Images Overlap: " + str(overlap))
rsgislib.imageutils.generateRandomPxlValsImg(inputImg, outputImg, gdalformat, lowVal, upVal)

Function which produces a 1 band image with random values between lowVal and upVal.

Where:

Parameters
  • inputImg – the input reference 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.

  • lowVal – lower value

  • upVal – upper value

rsgislib.imageutils.getUniqueValues(img, img_band=1)

Find the unique image values within an image band. Note, the whole image band gets read into memory.

Parameters
  • img – input image file path

  • img_band – image band to be processed (starts at 1)

Returns

array of unique values.