RSGISLib Image Utilities Module

Image Stats and Pyramids

rsgislib.imageutils.pop_img_stats(input_img, use_no_data=True, no_data_val=0, calc_pyramids=True)

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

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

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

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

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

from rsgislib import imageutils
inputImage = './TestOutputs/injune_p142_casi_sub_utm.kea'
imageutils.pop_img_stats(inputImage,True,0.,True)
rsgislib.imageutils.pop_thmt_img_stats(input_img: str, add_clr_tab: bool = True, calc_pyramids: bool = True, ignore_zero: bool = True)

A function which populates a byte thematic input image (e.g., classification) with pyramids and header statistics (e.g., colour table).

Note, for more complex thematic images using formats which support raster attribute tables (e.g., KEA) then use the rsgislib.rastergis.pop_rat_img_stats function.

This function is best used aiding the visualisation of GTIFF’s.

Parameters:
  • input_img – input image path

  • add_clr_tab – boolean specifying whether a colour table should be added (default: True)

  • calc_pyramids – boolean specifying whether a image pyramids should be added (default: True)

  • ignore_zero – boolean specifying whether to ignore pixel with a value of zero i.e., as a no data value (default: True)

Example:

import rsgislib.imageutils
rsgislib.imageutils.pop_thmt_img_stats("land_cover_cls_img.tif")
rsgislib.imageutils.get_img_band_stats(input_img: str, img_band: int, compute: bool = True) Tuple[float, float, float, float]

A function which calls the GDAL function on the band selected to calculate the pixel stats (min, max, mean, standard deviation).

Parameters:
  • input_img – input image file path

  • img_band – specified image band for which stats are to be calculated (starts at 1).

  • compute – whether the stats should be calculated (True; Default) or an approximation or pre-calculated stats are OK (False).

Returns:

stats (min, max, mean, stddev)

Example:

import rsgislib.imageutils
min, max, mean, std = rsgislib.imageutils.get_img_band_stats("img.kea", 1)
rsgislib.imageutils.get_img_no_data_value(input_img: str, img_band: int = 1)

A function to retrieve the no data value for the image (from band; default 1).

Parameters:
  • input_img – input image file.

  • img_band – the band for which the no data value should be returned.

Returns:

number

Example:

import rsgislib.imageutils
no_data_val = rsgislib.imageutils.get_img_no_data_value("img.kea")
rsgislib.imageutils.set_img_no_data_value(input_img: str, no_data_val: float, img_band: int = None)

A function to set the no data value for an image. If band is not specified sets value for all bands.

Parameters:
  • input_img – input image file.

  • no_data_val – No data value to be defined to the image band

  • img_band – the band for which the no data value should be returned.

Example:

import rsgislib.imageutils
rsgislib.imageutils.set_img_no_data_value("img.kea", 0.0, 1)

Image Creation Options

rsgislib.imageutils.get_gdal_img_creation_opts(gdalformat=string)

This function returns a dict from by reading an environment variable to retrieve any creation options for a particular image file format. Variables should have the name RSGISLIB_IMG_CRT_OPTS_<GDAL_FORMAT> where a key value pairs separated by colons (:) is provided. The gdal format string must be upper case. For example: export RSGISLIB_IMG_CRT_OPTS_GTIFF=TILED=YES:COMPRESS=LZW:BIGTIFF=YES export RSGISLIB_IMG_CRT_OPTS_HFA=COMPRESSED=YES:USE_SPILL=YES:AUX=NO:STATISTICS=YES

Parameters:

gdalformat – is a string specifying the GDAL image file format of interest.

Returns:

a dict of the options.

rsgislib.imageutils.get_rios_img_creation_opts(gdalformat: str) List[str]

An internal function used to get the RSGISLib specified GDAL image creation options for input into RIOS applier.

Parameters:

gdalformat – the GDAL format (e.g., GTIFF)

Returns:

list of creation options

rsgislib.imageutils.set_env_vars_lzw_gtiff_outs(bigtiff: bool = False)

Set environmental variables such that outputted GeoTIFF files are outputted as tiled and compressed using the LZW algorithm.

Parameters:

bigtiff – If True GTIFF files will be outputted in big tiff format.

Example:

import rsgislib.imageutils
rsgislib.imageutils.set_env_vars_lzw_gtiff_outs()
rsgislib.imageutils.set_env_vars_deflate_gtiff_outs(bigtiff: bool = False)

Set environmental variables such that outputted GeoTIFF files are outputted as tiled and compressed using the Deflate (zlib) algorithm.

Parameters:

bigtiff – If True GTIFF files will be outputted in big tiff format.

Example:

import rsgislib.imageutils
rsgislib.imageutils.set_env_vars_deflate_gtiff_outs()

Get Image Info

rsgislib.imageutils.get_img_res(input_img: str, abs_vals: bool = False)

A function to retrieve the image resolution.

Parameters:
  • input_img – input image file

  • abs_vals – if True then returned x/y values will be positive (default: False)

Returns:

xRes, yRes

Example:

import rsgislib.imageutils
x_res, y_res = rsgislib.imageutils.get_img_res("img.kea")
rsgislib.imageutils.get_img_size(input_img: str)

A function to retrieve the image size in pixels.

Parameters:

input_img – input image file.

Returns:

xSize, ySize

Example:

import rsgislib.imageutils
x_size, y_size = rsgislib.imageutils.get_img_size("img.kea")
rsgislib.imageutils.get_img_band_count(input_img: str)

A function to retrieve the number of image bands in an image file.

Parameters:

input_img – input image file.

Returns:

nBands

Example:

import rsgislib.imageutils
n_bands = rsgislib.imageutils.get_img_band_count("img.kea")
rsgislib.imageutils.get_img_bbox(input_img: str) Tuple[float, float, float, float]

A function to retrieve the bounding box in the spatial coordinates of the image.

Parameters:

input_img – input image file.

Returns:

(MinX, MaxX, MinY, MaxY)

Example:

import rsgislib.imageutils
bbox = rsgislib.imageutils.get_img_bbox("img.kea")
rsgislib.imageutils.get_img_bbox_in_proj(input_img: str, out_epsg: int) Tuple[float, float, float, float]

A function to retrieve the bounding box in the spatial coordinates of the image.

Parameters:
  • input_img – input image file.

  • out_epsg – an EPSG code for the output BBOX

Returns:

(MinX, MaxX, MinY, MaxY)

Example:

import rsgislib.imageutils
bbox_osgb = rsgislib.imageutils.get_img_bbox("img.kea", out_epsg=27700)
rsgislib.imageutils.get_img_subset_pxl_bbox(input_img: str, sub_bbox: Tuple[float, float, float, float] | List[float]) Tuple[float, float, float, float]

A function which returns a BBOX (xmin, xmax, ymin, ymax) with the pixel coordinates for an intersecting BBOX in the spatial coordinates of the image. Note, the sub_bbox will be subset to be contained by the input image (if outside the bounds of the input image).

Parameters:
  • input_img – The input image file path

  • sub_bbox – The input bbox (xmin, xmax, ymin, ymax) in the same spatial coordinate system as the input image specifying the subset for which the pixel coords are to be calculated.

Returns:

bbox (xmin, xmax, ymin, ymax) in the image pixel coordinates.

rsgislib.imageutils.get_img_pxl_spatial_coords(input_img: str, sub_pxl_bbox: Tuple[float, float, float, float] | List[float]) Tuple[float, float, float, float]

A function which gets the spatial coordinates for a image pixel space BBOX (xmin, xmax, ymin, ymax). The returned BBOX will be within the same coordinate system as the input image.

Parameters:
  • input_img – The input image file path

  • sub_pxl_bbox – The bbox (xmin, xmax, ymin, ymax) in the image pixel coordinates (e.g., [20, 120, 1000, 1230])

Returns:

bbox (xmin, xmax, ymin, ymax) in the image spatial coordinates.

rsgislib.imageutils.get_img_files(input_img: str) List[str]

A function which returns a list of the files associated (e.g., header etc.) with the input image file.

Parameters:

input_img – input image file.

Returns:

lists

rsgislib.imageutils.has_gcps(input_img: str)

Test whether the input image has GCPs - returns boolean

Parameters:

input_img – input image file

Returns:

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

rsgislib.imageutils.get_gdal_format_name(input_img: str)

Gets the shorthand file format for the input image in uppercase.

Parameters:

input_img – The current name of the GDAL layer.

Returns:

string with the file format (e.g., KEA or GTIFF).

Example:

import rsgislib.imageutils
gdal_format = rsgislib.imageutils.get_gdal_format_name("img.kea")
rsgislib.imageutils.is_img_thematic(input_img: str, img_band: int = 1)

Set all image bands to be thematic.

Parameters:
  • input_img – The file for which the bands are to be set as thematic

  • img_band – The image band to be tested.

rsgislib.imageutils.get_img_pxl_coords(input_img: str, x_coords: ~numpy.array, y_coords: ~numpy.array) -> (<built-in function array>, <built-in function array>)

A function which calculates the image pixel coordinates for a set of spatial coordinates for the input_img. Note, the input coordinates must be within the input image extent.

Parameters:
  • input_img – Input image file path. This image defines the spatial coordinate system and extent for the conversion of the input coordinates.

  • x_coords – Numpy array of x coordinates

  • y_coords – Numpy array of y coordinates

Returns:

x_pxl_coords, y_pxl_coords. A pair of numpy arrays with the image pixel coordinates for the input spatial coordinates.

Spatial Header info

rsgislib.imageutils.assign_wkt_proj(input_img, wkt_str, wkt_file)

Assign a projection to the input GDAL image file.

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

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

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

from rsgislib import imageutils
wkt_str = '''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"]]'''
input_img = './TestOutputs/injune_p142_casi_sub_utm.kea'
imageutils.assign_wkt_proj(input_img, wkt_str)
rsgislib.imageutils.assign_spatial_info(input_img, tl_x, tl_y, res_x, res_y, rot_x, rot_y)

Assign the spatial information to an input GDAL image file.

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

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

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

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

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

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

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

rsgislib.imageutils.copy_proj_from_img(input_img, ref_img)

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

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

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

rsgislib.imageutils.copy_spatial_and_proj_from_img(input_img, ref_img)

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

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

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

rsgislib.imageutils.get_wkt_proj_from_img(input_img: str)

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

Parameters:

input_img – input image file.

Returns:

WTK string

rsgislib.imageutils.get_epsg_proj_from_img(input_img: str) int

Using GDAL to return the EPSG code for the input layer.

Parameters:

input_img – input image file.

Returns:

EPSG code

rsgislib.imageutils.get_utm_zone(input_img: str)

A function which returns a string with the UTM (XXN | XXS) zone of the input image but only if it is projected within the UTM projection/coordinate system.

Parameters:

input_img – input image file.

Returns:

string

rsgislib.imageutils.copy_gcps(input_img: str, output_img: str)

Copy the GCPs from the input_img to the output_img

Parameters:
  • input_img – Raster layer with GCPs

  • output_img – Raster layer to which GCPs will be added

Image Reprojection / Warp

rsgislib.imageutils.resample_img_to_match(in_ref_img: str, in_process_img: str, output_img: str, gdalformat: str, interp_method: int = 0, datatype: int = None, no_data_val: float = None, multicore: bool = False)

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

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

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

  • output_img – is the output image file.

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

  • interp_method – is the interpolation method used to resample the image rsgislib.INTERP_XXXX (Default: rsgislib.INTERP_NEAREST_NEIGHBOUR)

  • 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.reproject_image(input_img: str, output_img: str, out_wkt: str, gdalformat: str = 'KEA', interp_method: int = 0, in_wkt: str = None, no_data_val: float = 0.0, out_pxl_res: float = 'image', snap_to_grid: bool = True, multicore: bool = False, gdal_options: List[str] = [])

This function provides a tool which uses the gdalwarp function to reproject an input image. When you want an simpler interface use the rsgislib.imageutils.gdal_warp function. This handles more automatically.

Parameters:
  • input_img – the input image name and path

  • output_img – the output image name and path

  • out_wkt – a WKT file representing the output projection

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

  • interp_method – is the interpolation method used to resample the image rsgislib.INTERP_XXXX (Default: rsgislib.INTERP_NEAREST_NEIGHBOUR)

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

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

  • out_pxl_res – 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. You may consider using rsgislib.imageutils.gdal_warp instead of this option. 3) provide a floating point value for the image resolution (note. pixels will be sqaure)

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

  • multicore – use multiple cores for warpping (Default=False)

  • gdal_options – GDAL file creation options e.g., [“TILED=YES”, “COMPRESS=LZW”, “BIGTIFF=YES”]

rsgislib.imageutils.gdal_warp(input_img: str, output_img: str, out_epsg: int, interp_method: int = 0, gdalformat: str = 'KEA', use_multi_threaded: bool = True, options: List[str] = [])

A function which runs GDAL Warp function to tranform an image from one projection to another. Use this function when you want GDAL to do processing of pixel size and image size automatically. rsgislib.imageutils.reproject_image should be used when you want to put the output image on a particular grid etc.

Parameters:
  • input_img – input image file

  • output_img – output image file

  • out_epsg – the EPSG for the output image file.

  • interp_method – is the interpolation method used to resample the image rsgislib.INTERP_XXXX (Default: rsgislib.INTERP_NEAREST_NEIGHBOUR)

  • gdalformat – output image file format

  • use_multi_threaded – Use multiple cores for processing (Default: True).

  • options – GDAL file creation options e.g., [“TILED=YES”, “COMPRESS=LZW”, “BIGTIFF=YES”]

Mosaic

rsgislib.imageutils.create_img_mosaic(input_imgs, output_img, background_val, skip_val, skip_band, overlap_behaviour, gdalformat, datatype)

Create mosaic from list of input images.

Where

Parameters:
  • input_imgs – is a list of input images.

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

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

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

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

  • overlap_behaviour – 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.

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.create_img_mosaic(inputList, outImage, backgroundVal, skipVal, skipBand, overlapBehaviour, gdalformat, datatype)
rsgislib.imageutils.include_imgs(input_img, include_imgs, input_bands=None, skip_val=None)

Create mosaic from list of input images.

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

  • include_imgs – is a list of input images

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

  • skip_val – 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.

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.include_imgs(baseImage, inputList)
rsgislib.imageutils.include_imgs_with_overlap(input_img, include_imgs, overlap)

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

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

  • include_imgs – is a list of input images

  • overlap – the size, in pixels, of the each on the images which should be ignored as an overlapping region.

     import rsgislib
     from rsgislib import imageutils
     import glob
inputImg = 'LandsatImg.kea'
tilesImgBase = './tiles/LandsatTile'
outputImg = 'LandsatImgProcessed.kea'
imageutils.create_tiles(inputImg, tilesImgBase, 1000, 1000, 10, False, 'KEA', rsgislib.TYPE_32FLOAT, 'kea')
# Do some processing on the tiles... 
imageutils.create_copy_img(inputImg, outputImg, 6, 0, 'KEA', rsgislib.TYPE_32FLOAT)
     inputList = glob.glob('./tiles/LandsatTile*.kea')
     imageutils.include_imgs_with_overlap(outputImg, inputList, 10)
rsgislib.imageutils.include_imgs_ind_img_intersect(input_img, include_imgs)

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

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

  • include_imgs – is a list of input images

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.include_imgs_ind_img_intersect(baseImage, inputList)
rsgislib.imageutils.combine_imgs_to_band(input_imgs=list, output_img=string, gdalformat=string, datatype=int, no_data_val=float)

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

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

  • output_img – 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_*

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

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

Composite

rsgislib.imageutils.create_ref_img_composite_img(input_imgs=list, output_img=string, in_ref_img=string, gdalformat=string, datatype=int, out_no_data=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.get_img_idx_for_stat function.

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

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

  • in_ref_img – 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_*

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

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.calc_ndvi(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.get_img_idx_for_stat(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.create_ref_img_composite_img(inImages, outCompImg, pxlRefImg, 'KEA', rsgislib.TYPE_16UINT, 0.0)

# Calc Stats
rsgislib.imageutils.pop_img_stats(outCompImg, usenodataval=True, nodataval=0, calcpyramids=True)
rsgislib.imageutils.combine_binary_masks(msk_imgs_dict: dict, output_img: str, out_lut_file: str, gdalformat: str = '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.

  • output_img – output image file.

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

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

rsgislib.imageutils.export_single_merged_img_band(input_img=string, int_band_ref_img=string, output_img=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.

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

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

  • output_img – 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

rsgislib.imageutils.imagecomp.check_build_ls8_ls9_vrts(input_imgs, output_dir)

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

Parameters:
  • input_imgs – input list of image file paths.

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

rsgislib.imageutils.imagecomp.create_max_ndvi_composite(input_imgs, r_band, n_band, out_ref_img, out_comp_img, tmp_dir='tmp', gdalformat='KEA', datatype=None, calc_stats=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:
  • input_imgs – list of input images for the analysis.

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

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

  • out_ref_img – 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).

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

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

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

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

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

rsgislib.imageutils.imagecomp.create_max_ndvi_ndwi_composite(ref_sp_img, input_imgs, r_band, n_band, s_band, out_ref_img, out_comp_img, out_msk_img, tmp_path='tmp', gdalformat='KEA', datatype=None, calc_stats=True, reproj_method=2, 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:
  • ref_sp_img – is a reference image with any number of bands and data type which is used to define the output image extent and projection.

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

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

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

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

  • out_ref_img – 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).

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

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

  • tmp_path – is a temp path for intermediate 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).

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

  • reproj_method – specifies the interpolation method (rsgislib.INTERP*) used to reproject the input images which are in a different projection and/or pixel size as the reference image (default: rsgislib.INTERP_CUBIC).

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

rsgislib.imageutils.order_img_using_prop_valid_pxls(input_imgs, no_data_val)

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.

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

  • no_data_val – 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.gen_timeseries_fill_composite_img(comp_info=list, in_vld_img=string, out_ref_fill_img=string, out_comp_img=string, out_comp_ref_img=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.

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

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

  • out_ref_fill_img

  • out_comp_img

  • out_comp_ref_img

  • 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

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 create_max_ndvi_composite or create_max_ndvi_ndwi_composite_landsat) 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 create_max_ndvi_composite or create_max_ndvi_ndwi_composite_landsat) with zero for no data regions

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

Tile

rsgislib.imageutils.create_tiles(input_img, out_img_base, tile_width, tile_height, tile_overlap, offset_tiles, gdalformat, datatype, out_img_ext)

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

Where

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

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

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

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

  • tile_overlap – is the overlap between tiles, in pixels

  • offset_tiles – 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.

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

Returns:

list of tile file names

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.create_tiles(inputImage, outBase, width, height, overlap, offsettiling, gdalformat, datatype, ext)
rsgislib.imageutils.create_tiles_multi_core(input_img: str, out_img_base: str, width: int, height: int, gdalformat: str, datatype: int, out_img_ext: str, n_cores: int = 1)

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

Parameters:
  • input_img – input image to be subset.

  • out_img_base – 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.

  • out_img_ext – output file extension to be added to the base image path (e.g., kea)

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

rsgislib.imageutils.create_raster_tiles_bbox(bbox: List[float], tile_x_size: float, tile_y_size: float, out_img_res: float, out_epsg: int, out_tile_dir: str, out_tile_name: str = 'base_tile_{}', out_img_ext: str = 'kea', gdalformat: str = 'KEA', datatype: int = 5, out_img_pxl_val: float = 0, out_img_n_bands: int = 1)

A function which creates a set of raster tiles for a region defined by a bbox.

Parameters:
  • bbox – the bounding box (xMin, xMax, yMin, yMax) for the whole region for which the tiles are generated.

  • tile_x_size – the size of the tiles in x axis in the units of the projection (e.g., metres or degrees)

  • tile_y_size – the size of the tiles in y axis in the units of the projection (e.g., metres or degrees)

  • out_img_res – the output image tile pixel resolution

  • out_epsg – the output projection (which needs to match the bbox).

  • out_tile_dir – the output directory path.

  • out_tile_name – the base name for the output image tiles - note must include {} which will be replace with the tile x and y numbering. (Default: “base_tile_{}”)

  • out_img_ext – the output image file extension (Default: kea)

  • gdalformat – the output gdal image format (Default: KEA)

  • datatype – the output image data type (Default: rsgislib.TYPE_8UINT)

  • out_img_pxl_val – the output image pixel values (Default: 0)

  • out_img_n_bands – the number of output image bands (Default: 1)

rsgislib.imageutils.tilingutils.create_min_data_tiles(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.

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.create_tiles_from_masks(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.

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.

rsgislib.imageutils.tilingutils.create_tile_mask_images_from_shp(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.

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.create_tile_mask_images_from_clumps(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.

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

Visualisation / Normalisation

rsgislib.imageutils.stretch_img(input_img, output_img, save_stats, out_stats_file, no_data_val, one_pass_std, gdalformat, datatype, stretch_type, stretch_param)

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

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

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

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

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

  • no_data_val – is a float specifying the no data value of the input image.

  • one_pass_std – 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.

  • stretch_type – 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.

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

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.stretch_img(inputImage, outputImage, False, '', 0.0, False, gdalformat, datatype, imageutils.STRETCH_LINEARSTDDEV, 2)
rsgislib.imageutils.stretch_img_with_stats(input_img, output_img, in_stats_file, gdalformat, datatype, no_data_val, stretch_type, stretch_param)

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.stretch_img.

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

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

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

  • 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.

  • no_data_val – is a float with the no data value of the input image.

  • stretch_type – 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.

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

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
nodataval = 0.0
imageutils.stretch_img_with_stats(inputImage, outputImage, inputImageStats, True, False, gdalformat, datatype, nodataval, imageutils.STRETCH_LINEARSTDDEV, 2)
rsgislib.imageutils.normalise_img_pxl_vals(input_img=string, output_img=string, gdalformat=string, datatype=rsgislib.TYPE_*, in_no_data_val=float, out_no_data_val=float, out_min=float, out_max=float, stretch_type=imageutils.STRETCH_*, stretch_param=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.stretch_img but deals with no data values correctly and intended for data processing normalisation rather than visualisation.

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

  • output_img – 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.

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

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

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

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

  • stretch_type – 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.

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

import rsgislib
import rsgislib.imageutils

inImg = './LS5TM_19851990Comp_lat7lon3896_r65p166_stdsref.kea'

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

outImg = 'LS5TM_19851990Comp_lat7lon3896_r65p166_stdsref_NORM_0-1.kea'
rsgislib.imageutils.normalise_img_pxl_vals(inImg, outImg, 'KEA', rsgislib.TYPE_32FLOAT, innodataval=0, outnodataval=0, outmin=0, outmax=1,
                                          stretchtype=rsgislib.imageutils.STRETCH_LINEARSTDDEV, stretchparam=2)
rsgislib.imageutils.pop_img_stats(outImg, usenodataval=True, nodataval=0, calcpyramids=True)
rsgislib.imageutils.get_img_band_colour_interp(input_img: str, img_band: int)

A function to get the colour interpretation for a specific band.

  • GCI_Undefined=0,

  • GCI_GrayIndex=1,

  • GCI_PaletteIndex=2,

  • GCI_RedBand=3,

  • GCI_GreenBand=4,

  • GCI_BlueBand=5,

  • GCI_AlphaBand=6,

  • GCI_HueBand=7,

  • GCI_SaturationBand=8,

  • GCI_LightnessBand=9,

  • GCI_CyanBand=10,

  • GCI_MagentaBand=11,

  • GCI_YellowBand=12,

  • GCI_BlackBand=13,

  • GCI_YCbCr_YBand=14,

  • GCI_YCbCr_CbBand=15,

  • GCI_YCbCr_CrBand=16,

  • GCI_Max=16

Parameters:
  • input_img – input image file.

  • img_band – the band for which the no data value should be returned.

Returns:

is a GDALColorInterp value

rsgislib.imageutils.set_img_band_colour_interp(input_img: str, img_band: int, clr_itrp_val: int)

A function to set the colour interpretation for a specific band. input is a GDALColorInterp value:

  • GCI_Undefined=0,

  • GCI_GrayIndex=1,

  • GCI_PaletteIndex=2,

  • GCI_RedBand=3,

  • GCI_GreenBand=4,

  • GCI_BlueBand=5,

  • GCI_AlphaBand=6,

  • GCI_HueBand=7,

  • GCI_SaturationBand=8,

  • GCI_LightnessBand=9,

  • GCI_CyanBand=10,

  • GCI_MagentaBand=11,

  • GCI_YellowBand=12,

  • GCI_BlackBand=13,

  • GCI_YCbCr_YBand=14,

  • GCI_YCbCr_CbBand=15,

  • GCI_YCbCr_CrBand=16,

  • GCI_Max=16

Parameters:
  • input_img – input image file.

  • img_band – the band for which the no data value should be returned.

  • clr_itrp_val – the clr_itrp_val value to be set.

rsgislib.imageutils.set_img_thematic(input_img: str)

Set all image bands to be thematic.

Parameters:

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

rsgislib.imageutils.set_img_not_thematic(input_img: str)

Set all image bands to be not thematic (athematic).

Parameters:

input_img – The file for which the bands are to be set as not thematic (athematic)

rsgislib.imageutils.get_colour_tab_info(input_img: str, img_band: int = 1) Dict[str, Dict]

A function which returns the colour table info from an input image. The output dict has the following structure:

clr_info[1] = {‘red’:0, ‘green’:255, ‘blue’:0, ‘alpha’: 255} clr_info[2] = {‘red’:0, ‘green’:0, ‘blue’:255, ‘alpha’: 255}

Parameters:
  • input_img – the file path to the input image.

  • img_band – optional image band to be read - default is 1.

Returns:

dict of dicts with the colour table info.

rsgislib.imageutils.define_colour_table(input_img: str, clr_lut: dict, img_band: int = 1)

A function which defines specific colours for image values for a colour table. Note, this function must be used to thematic images which use int pixel values and replaces the existing colour table.

Parameters:
  • input_img – input image path

  • clr_lut – a dict with the pixel value as the key with a single value or list of 3 or 4 values. If 3 values are provided they are interpreted as RGB (values between 0 and 255) while if 4 are provided they are interpreted as RGBA (values between 0 and 255). If a single value is provided then it is interpreted as a hexadecimal value for RGB (e.g., #b432be).

  • img_band – int specifying the band for the colour table (default = 1)

Example:

import rsgislib.imageutils

clr_lut = dict()
clr_lut[1] = '#009600'
clr_lut[2] = '#FFE5CC'
clr_lut[3] = '#CCFFE5'
rsgislib.imageutils.define_colour_table("cls_img.tif", clr_lut)

Masking

rsgislib.imageutils.mask_img(input_img, in_msk_img, output_img, gdalformat, datatype, out_value, mask_value)

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

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

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

  • output_img – 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.

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

  • mask_value – 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.

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.mask_img(inImg, imgMask, outImg, 'KEA', rsgislib.TYPE_16UINT, 0, [1,2])
imageutils.pop_img_stats(outImg, True, 0.0, True)
rsgislib.imageutils.gen_finite_mask(input_img=string, output_img=string, gdalformat=string)

Generate a binary image mask defining the finite image regions.

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

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

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

from rsgislib import imageutils
inputImage = './injune_p142_casi_sub_utm.kea'
outputImage = './injune_p142_casi_sub_utm.kea'
imageutils.gen_finite_mask(inputImage, outputImage, 'KEA')
rsgislib.imageutils.gen_valid_mask(input_imgs=string | list, output_img=string, gdalformat=string, no_data_val=float)

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

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

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

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

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

from rsgislib import imageutils
inputImage = './injune_p142_casi_sub_utm.kea'
outputImage = './injune_p142_casi_sub_utm.kea'
imageutils.gen_valid_mask(inputImage, outputImage, 'KEA', 0.0)
rsgislib.imageutils.gen_img_edge_mask(input_img=string, output_img=string, gdalformat=string, n_edge_pxls=int)
Generate a binary image mask defining the edges of the pixel. The n_edge_pxls parameter specifies the

number of pixels from the edge of the input image which will be provided as the output mask.

Parameters:
  • input_img – the input image

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

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

  • n_edge_pxls – is int specifying the number of pixels from the edge to create the mask for.

rsgislib.imageutils.mask_img_with_vec(input_img: str, output_img: str, gdalformat: str, roi_vec_file: str, roi_vec_lyr: str, tmp_dir: str, outvalue: float = 0, datatype: int = None, vec_epsg: int = None)

This function masks the input image using a polygon vector file.

Parameters:
  • input_img – Input Image file.

  • output_img – Output Image file.

  • gdalformat – Output image file format.

  • roi_vec_file – The input vector file.

  • roi_vec_lyr – The name of the input layer.

  • tmp_dir – a temporary directory for files generated during processing.

  • outvalue – The output value in the regions masked.

  • datatype – Output image data type. If None then the datatype of the input image will be used.

  • vec_epsg – If projection is poorly defined by the vector layer then it can be specified.

rsgislib.imageutils.mask_all_band_zero_vals(input_img: str, output_img: str, gdalformat: str, out_val: int = 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.imageutils.create_valid_mask(img_band_info: List, out_msk_file: str, gdalformat: str, tmp_dir: str)

A function to create a single valid mask from the intersection of the valid masks for all the input images.

Parameters:
  • img_band_info – A list of rsgislib.imageutils.ImageBandInfo objects to define the images and bands of interest.

  • out_msk_file – A output image file and path

  • gdalformat – The output file format.

  • tmp_dir – A directory for temporary outputs created during the processing.

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

Create a list of these objects to pass to functions to specifying individual images and image bands. Functions where this class is used include:

  • rsgislib.imageutils.create_valid_mask

  • rsgislib.zonalstats.extractZoneImageBandValues2HDF

Parameters:
  • file_name – 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 file_name to be used for processing (band numbers start at 1).

  • file_name – 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 file_name to be used for processing (band numbers start at 1).

Subsetting

rsgislib.imageutils.subset(input_img, vec_file, vec_lyr, output_img, gdalformat, datatype)

Subset an image to the bounding box of a vector.

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

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

  • vec_lyr – is a string specifying the layer within the vector file to be used

  • output_img – 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.

import rsgislib
from rsgislib import imageutils
input_img = './Rasters/injune_p142_casi_sub_utm.kea'
vec_file = './Vectors/injune_p142_plot_location_utm.shp'
vec_lyr = 'injune_p142_plot_location_utm'
output_img = './TestOutputs/injune_p142_casi_sub_utm_subset.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.subset(input_img, vec_file, vec_lyr, output_img, gdalformat, datatype)
rsgislib.imageutils.subset_to_img(input_img: str, in_roi_img: str, output_img: str, gdalformat: str, datatype: int)

Subset an image to the bounding box of an image.

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

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

  • output_img – 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.

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.subset_to_img(inputImage, inputROIimage, outputImage, gdalformat, datatype)
rsgislib.imageutils.subset_to_geoms_bbox(input_img: str, vec_file: str, vec_lyr: str, att_unq_val_col: str, out_img_base: str, gdalformat: str = 'KEA', datatype: int = None, out_img_ext: str = 'kea')

Subset an image to the bounding box of a each geometry in the input vector producing multiple output files. Useful for splitting an image into tiles of unequal sizes or extracting sampling plots from a larger image.

Note, if a vector feature does not intersect with the input image then it will silently ignore the feature (i.e., not output image will be produced).

Parameters:
  • input_img – The input image from which the subsets will be extracted.

  • vec_file – input vector file/path

  • vec_lyr – input vector layer name

  • att_unq_val_col – column within the attribute table which has a value to be included within the output file name so the output files can be identified and have unique file names.

  • out_img_base – the output images base path and file name

  • gdalformat – output image file format (default: KEA)

  • datatype – output image data type. If None (default) then taken from the input image.

  • out_img_ext – output image file extension (e.g., kea)

rsgislib.imageutils.subset_bbox(input_img, output_img, gdalformat, datatype, min_x, max_x, min_y, max_y)

Subset an image to the bounding box of a vector.

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

  • output_img – 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.

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

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

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

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

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.subset_bbox(inputImage, outputImage, gdalformat, datatype, xMin, xMax, yMin, yMax)
rsgislib.imageutils.subset_pxl_bbox(input_img: str, output_img: str, gdalformat: str, datatype: int, x_min_pxl: int, x_max_pxl: int, y_min_pxl: int, y_max_pxl: int)

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

Parameters:
  • input_img – input image to be subset.

  • output_img – output image file.

  • gdalformat – output image file format

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

  • x_min_pxl – min x in pixels

  • x_max_pxl – max x in pixels

  • y_min_pxl – min y in pixels

  • y_max_pxl – max y in pixels

rsgislib.imageutils.subset_to_vec(input_img: str, output_img: str, gdalformat: str, roi_vec_file: str, roi_vec_lyr: str, datatype: int = None, vec_epsg: int = None, img_epsg: int = None)

A function which subsets an input image using the extent of a vector layer where the input vector can be a different projection to the input image. Reprojection will be handled.

Parameters:
  • input_img – Input Image file.

  • output_img – Output Image file.

  • gdalformat – Output image file format.

  • roi_vec_file – The input vector file.

  • roi_vec_lyr – The name of the input layer.

  • datatype – Output image data type. If None then the datatype of the input image will be used.

  • vec_epsg – If projection is poorly defined by the vector layer then it can be specified.

  • img_epsg – If projection is poorly defined by the image layer then it can be specified.

rsgislib.imageutils.create_inmem_gdal_ds_subset(input_img: str, bbox_sub: List[float], no_data_val: float = None) Dataset

A function which creates an in-memory (MEM) GDAL dataset for a subset defined by a BBOX (MinX, MaxX, MinY, MaxY)

Parameters:
  • input_img – the input image

  • bbox_sub – the bbox (MinX, MaxX, MinY, MaxY) defining the subset.

  • no_data_val – the image no data value. If None then read from input_img

Returns:

Returns a GDAL Dataset with a subset.

Extract / Sample

rsgislib.imageutils.perform_random_pxl_sample_in_mask(input_img=string, output_img=string, gdalformat=string, mask_vals=int|list, n_samples=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.

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

  • output_img – 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.

  • mask_vals – 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).

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

rsgislib.imageutils.perform_random_pxl_sample_in_mask_low_pxl_count(input_img=string, output_img=string, gdalformat=string, mask_vals=int|list, n_samples=unsigned int, rnd_seed=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.perform_random_pxl_sample_in_mask but is more efficient for classes where only a small number of pixels have that value. However, this function uses much more memory.

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

  • output_img – 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.

  • mask_vals – 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).

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

  • rnd_seed – 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.extract_img_pxl_sample(input_img: str, pxl_n_sample: int, no_data_val: float = None)

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

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

  • pxl_n_sample – the sample to be taken (e.g., a value of 100 will sample every 100th, valid (if noData specified), pixel)

  • no_data_val – 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.extract_img_pxl_vals_in_msk(input_img: str, img_bands: List[int], in_msk_img: str, img_mask_val: int, no_data_val: float = None)

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

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

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

  • in_msk_img – 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)

Create

rsgislib.imageutils.create_blank_img(output_img, n_bands, width, height, tl_x, tl_y, res_x, res_y, pxl_val, wkt_file, wkt_str, gdalformat, datatype)

Create a new blank image with the parameters specified.

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

  • n_bands – 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.

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

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

  • res_x – is a double specifying the pixel resolution in the x-axis for the output image.

  • res_y – is a double specifying the pixel resolution in the y-axis for the output image.

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

  • wkt_file – 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).

  • wkt_str – 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.create_blank_img_py(output_img: str, n_bands: int, width: int, height: int, tl_x: float, tl_y: float, out_img_res_x: float, out_img_res_y: float, wkt_string: str, gdalformat: str, datatype: int, options: List[str] = [], no_data_val: float = 0)

Create a blank output image file - this is a pure python implementation of rsgislib.imageutils.create_blank_img

Parameters:
  • output_img – the output file and path.

  • n_bands – the number of output image bands.

  • width – the number of x pixels.

  • height – the number of Y pixels.

  • tl_x – the top-left corner x coordinate

  • tl_y – the top-left corner y coordinate

  • out_img_res_x – the output image resolution in the x axis

  • out_img_res_y – the output image resolution in the y axis

  • wkt_string – a WKT string with the output image projection

  • gdalformat – the output image file format.

  • datatype – the output image data type - needs to be a rsgislib datatype (e.g., rsgislib.TYPE_32FLOAT)

  • options – image creation options e.g., [“TILED=YES”, “INTERLEAVE=PIXEL”, “COMPRESS=LZW”, “BIGTIFF=YES”]

  • no_data_val – the output image no data value.

rsgislib.imageutils.create_copy_img(input_img, output_img, n_bands, pxl_val, gdalformat, datatype)

Create a new blank image with the parameters specified.

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

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

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

  • pxl_val – 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.

inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_blank.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.create_copy_img(inputImage, outputImage, 1, 3, gdalformat, datatype)
rsgislib.imageutils.create_copy_img_def_extent(input_img, output_img, n_bands, pxl_val, min_x, max_x, min_y, max_y, res_x, res_y, gdalformat, datatype)

Create a new blank image with the parameters specified.

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

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

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

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

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

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

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

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

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

  • res_y – is a double specifying the Y resolution 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.create_blank_buf_img_from_ref_img(input_img: str, output_img: str, gdalformat: str, datatype: int, buf_pxl_ext: int = None, buf_spt_ext: float = None, no_data_val: float = None)

A function to create a new image file based on the input image but buffered by the specified amount (e.g., 100 pixels bigger on all sides). The buffer amount can be specified in pixels or spatial units. If non-None value is given for both inputs then an error will be produced. By default the no data value will be taken from the input image header but if not available or specified within the function call then that value will be used.

Parameters:
  • input_img – input reference image

  • output_img – output image file.

  • gdalformat – output image file format.

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

  • buf_pxl_ext – the amount the input image will be buffered in pixels.

  • buf_spt_ext – the amount the input image will be buffered in spatial distance, units are defined from the projection of the input image.

  • no_data_val – Optional no data value. If None then the no data value will be taken from the input image.

rsgislib.imageutils.create_blank_buf_img_from_4326_ref_img(input_img: str, output_img: str, gdalformat: str, datatype: int, buf_pxl_ext: int, no_data_val: float = None)

A function to create a new image file based on the input image but buffered by the specified amount (e.g., 100 pixels bigger on all sides). By default the no data value will be taken from the input image header but if not available or specified within the function call then that value will be used. Note, this function only works with images projected in WGS84 (EPSG:4326) and deals with edge cases, reducing the image size so coordinates are within -180-180, -90-90 valid range.

Parameters:
  • input_img – input reference image

  • output_img – output image file.

  • gdalformat – output image file format.

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

  • buf_pxl_ext – the amount the input image will be buffered in pixels.

  • no_data_val – Optional no data value. If None then the no data value will be taken from the input image.

rsgislib.imageutils.create_blank_img_from_ref_vector(vec_file: str, vec_lyr: str, output_img: str, out_img_res: float, out_img_n_bands: int, gdalformat: str, datatype: int)

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

Parameters:
  • vec_file – input vector file.

  • vec_lyr – 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.

  • output_img – output image file.

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

  • out_img_n_bands – 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.create_copy_img_vec_extent_snap_to_grid(vec_file: str, vec_lyr: str, output_img: str, out_img_res: float, out_img_n_bands: int, gdalformat: str, datatype: int, buf_n_pxl: int = 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:
  • vec_file – input vector file.

  • vec_lyr – 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.

  • output_img – output image file.

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

  • out_img_n_bands – 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

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

rsgislib.imageutils.create_blank_img_from_bbox(bbox: Tuple[float, float, float, float] | List[float], wkt_str: str, output_img: str, out_img_res: float, out_img_pxl_val: float, out_img_n_bands: int, gdalformat: str, datatype: int, snap_to_grid: bool = 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)

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

  • output_img – output image file.

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

  • out_img_pxl_val – output image pixel value.

  • out_img_n_bands – 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.

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

rsgislib.imageutils.create_img_for_each_vec_feat(vec_file: str, vec_lyr: str, file_name_col: str, out_img_path: str, out_img_ext: str, out_img_pxl_val: float, out_img_n_bands: int, out_img_res: float, gdalformat: str, datatype: int, snap_to_grid: bool = False, ignore_exist: bool = True)

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

Parameters:
  • vec_file – the input vector file.

  • vec_lyr – the input vector layer

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

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

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

  • out_img_pxl_val – output image pixel value

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

  • out_img_res – 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.

  • snap_to_grid – snap the output image to a grid of whole numbers with respect to the image pixel resolution.

  • ignore_exist – ignore outputs which already exist and therefore only create those which don’t exist.

rsgislib.imageutils.create_img_from_array(data_arr: array, output_img: str, tl_x: float, tl_y: float, out_img_res_x: float, out_img_res_y: float, wkt_string: str, gdalformat: str, datatype: int, options: List[str] = [], no_data_val: float = None)

A function which creates a new image from a numpy array with the spatial header information provided.

Parameters:
  • data_arr – a numpy array with dimensions (bands, height, width) or if just a single band then can be (height, width).

  • output_img – the output file and path.

  • tl_x – the top-left corner x coordinate

  • tl_y – the top-left corner y coordinate

  • out_img_res_x – the output image resolution in the x axis

  • out_img_res_y – the output image resolution in the y axis

  • wkt_string – a WKT string with the output image projection

  • gdalformat – the output image file format.

  • datatype – the output image data type - needs to be a rsgislib datatype (e.g., rsgislib.TYPE_32FLOAT)

  • options – image creation options e.g., [“TILED=YES”, “INTERLEAVE=PIXEL”, “COMPRESS=LZW”, “BIGTIFF=YES”]

  • no_data_val – the output image no data value. If None then ignored.

rsgislib.imageutils.create_img_from_array_ref_img(data_arr: array, output_img: str, ref_img: str, gdalformat: str, datatype: int, options: List[str] = [], no_data_val: float = None)

A function which creates a new image from a numpy array with the spatial header information provided from a reference image. Note, the reference image must match the image size (height and width) of the data_arr.

Parameters:
  • data_arr – a numpy array with dimensions (bands, height, width) or if just a single band then can be (height, width).

  • output_img – the output file path.

  • ref_img – the reference image file path

  • gdalformat – the output image file format.

  • datatype – the output image data type - needs to be a rsgislib datatype (e.g., rsgislib.TYPE_32FLOAT)

  • options – image creation options e.g., [“TILED=YES”, “INTERLEAVE=PIXEL”, “COMPRESS=LZW”, “BIGTIFF=YES”]

  • no_data_val – the output image no data value. If None then ignored.

rsgislib.imageutils.gdal_translate(input_img: str, output_img: str, gdalformat: str = 'KEA', datatype: int = None, options: str = '')

Using GDAL translate to convert input image to a different format, if GTIFF selected and no options are provided then a cloud optimised GeoTIFF will be outputted.

Parameters:
  • input_img – Input image which is GDAL readable.

  • output_img – The output image file.

  • gdalformat – The output image file format

  • datatype – is a rsgislib.TYPE_* value providing the data type of the output image. If None (Default) then input data type will be used.

  • options – options for the output driver (e.g., “-co TILED=YES -co COMPRESS=LZW -co BIGTIFF=YES”)

rsgislib.imageutils.create_copy_img_vec_extent(input_img, vec_file, vec_lyr, output_img, n_bands, pxl_val, gdalformat, datatype)

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

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

  • vec_file – is a string specifying the name and path of the vector file to which the image extent will be defined

  • vec_lyr – is a string specifying the vector layer within the vector file.

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

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

  • pxl_val – 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.

inputImage = './Rasters/injune_p142_casi_sub_utm.kea'
vec_file = './Rasters/injune_p142_roi.shp'
vec_lyr = 'injune_p142_roi'
outputImage = './TestOutputs/injune_p142_casi_sub_utm_blank.kea'
gdalformat = 'KEA'
datatype = rsgislib.TYPE_32FLOAT
imageutils.create_copy_img_vec_extent(inputImage, vec_file, vec_lyr, outputImage, 3, 1, gdalformat, datatype)
rsgislib.imageutils.grid_scattered_pts(vec_file: str, vec_lyr: str, vec_col: str, input_img: str, output_img: str, gdal_grid_alg: str = None, no_data_val: float = 0.0, gdalformat: str = 'KEA', datatype: int = 9)

A function which uses the GDAL grid function to create a regular grid (i.e., raster) from an irregular grid of points within a raster layer.

See gdal_grid documentation for the algorithm options:

Available algorithms and parameters with their defaults: Inverse distance to a power (default)

invdist:power=2.0:smoothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata=0.0

Inverse distance to a power with nearest neighbor search

invdistnn:power=2.0:radius=1.0:max_points=12:min_points=0:nodata=0

Moving average

average:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0

Nearest neighbor

nearest:radius1=0.0:radius2=0.0:angle=0.0:nodata=0.0

Various data metrics

<metric name>:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 possible metrics are:

minimum maximum range count average_distance average_distance_pts

Linear

linear:radius=-1.0:nodata=0.0

Parameters:
  • vec_file – input vector file path.

  • vec_lyr – input vector layer name.

  • vec_col – column within the input vector layer with the values to be interpolated across the region of interest.

  • input_img – an input image which defines the region of interest, pixel resolution and projection of the output image.

  • output_img – The output image file path.

  • gdal_grid_alg – the gdal formatted string with the algorithm options.

  • no_data_val – the output no data value (Default: 0.0)

  • gdalformat – the output image format (Default: KEA)

  • datatype – the output image data type (Default: Float 32)

Create VRT

rsgislib.imageutils.create_stack_images_vrt(input_imgs: List[str], out_vrt_file: str)

A function which creates a GDAL VRT file from a set of input images by stacking the input images in a multi-band output file.

Parameters:
  • input_imgs – A list of input images

  • out_vrt_file – The output file location for the VRT.

rsgislib.imageutils.create_mosaic_images_vrt(input_imgs: List[str], out_vrt_file: str, vrt_extent: Tuple[float, float, float, float] | List[float] = None, vrt_out_res_x: float = None, vrt_out_res_y: float = None, interp_method: int = 0, align_out_pxls: bool = False)

A function which creates a GDAL VRT file from a set of input images by mosaicking the input images.

Parameters:
  • input_imgs – A list of input images

  • out_vrt_file – The output file location for the VRT.

  • vrt_extent – An optional (If None then ignored) extent (minX, minY, maxX, maxY) for the VRT image.

  • vrt_out_res_x – An optional (If None then ignored) set defining the x resolution of the output VRT.

  • vrt_out_res_y – An optional (If None then ignored) set defining the y resolution of the output VRT.

  • interp_method – define the interpolation algorithm used when resampling is required.

  • align_out_pxls – align the output pixels to force output bounds to be multiple of output resolution.

rsgislib.imageutils.create_vrt_band_subset(input_img: str, img_bands: List[int], out_vrt_img: str)

A function which creates a GDAL VRT for the input image with the bands selected in the input list.

Parameters:
  • input_img – the input GDAL image

  • img_bands – a list of bands (in the order they will be in the VRT). Note, band numbering starts at 1.

  • out_vrt_img – the output VRT file.

Select / Stack bands

rsgislib.imageutils.select_img_bands(input_img, output_img, gdalformat, datatype, bands)

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

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

  • output_img – 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).

import rsgislib.imageutils
import rsgislib
bands = [1,2]
rsgislib.imageutils.select_img_bands('N06W053_07_ALL_sl_sub.kea', 'N06W053_07_ALL_sl_sub_HHVV.kea', 'KEA', rsgislib.TYPE_32INT, bands)
rsgislib.imageutils.stack_img_bands(input_imgs, band_names, output_img, skip_value, no_data_val, gdalformat, datatype)

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

Parameters:
  • input_imgs – is a list of input images.

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

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

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

  • no_data_val – 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.

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.stack_img_bands(imageList, bandNamesList, outputImage, None, 0, gdalformat, gdaltype)

Sharpen Image Bands

rsgislib.imageutils.pan_sharpen_hcs(input_img=string, output_img=string, gdalformat=string, datatype=int, win_size=unsigned int, use_naive_method=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.

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

  • output_img – 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_*

  • win_size – 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).

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

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.stack_img_bands(['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.pan_sharpen_hcs(inimage='StackPanImg.kea', outimage='StackPanImgSharp.kea', gdalformat='KEA', datatype=rsgislib.TYPE_16UINT)

rsgislib.imageutils.pop_img_stats('StackPanImgSharp.kea', usenodataval=True, nodataval=0, calcpyramids=True)
rsgislib.imageutils.sharpen_low_res_bands(input_img=string, output_img=string, band_info=list, win_size=unsigned int, no_data_val=int, gdalformat=string, datatype=int)

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

Parameters:
  • input_img – 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

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

  • band_info – 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

  • win_size – 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.

  • no_data_val – 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_*

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.sharpen_low_res_bands(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)
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.

Band Names

rsgislib.imageutils.set_band_names(input_img: str, band_names: List[str], feedback: bool = False)

A utility function to set band names.

Parameters:
  • input_img – input image file.

  • band_names – 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)

from rsgislib import imageutils

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

imageutils.set_band_names(input_img, band_names)
rsgislib.imageutils.get_band_names(input_img: str) List[str]

A utility function to get band names.

Parameters:

input_img – input image file.

Returns:

list of band names

from rsgislib import imageutils

input_img = 'injune_p142_casi_sub_utm.kea'
band_names = imageutils.get_band_names(input_img)

Image Data Types

rsgislib.imageutils.get_gdal_datatype_from_img(input_img: str) int

Returns the GDAL datatype ENUM (e.g., GDT_Float32) for the inputted raster file.

Parameters:

input_img – input image file.

Returns:

int

Example:

import rsgislib.imageutils
datatype = rsgislib.imageutils.get_gdal_datatype_from_img("img.kea")
rsgislib.imageutils.get_rsgislib_datatype_from_img(input_img: str) int

Returns the rsgislib datatype ENUM (e.g., rsgislib.TYPE_8UINT) for the inputted raster file

Parameters:

input_img – input image file.

Returns:

int

Example:

import rsgislib.imageutils
datatype = rsgislib.imageutils.get_rsgislib_datatype_from_img("img.kea")
rsgislib.imageutils.get_gdal_datatype_name_from_img(input_img: str) str

Returns the GDAL datatype ENUM (e.g., GDT_Float32) for the inputted raster file.

Parameters:

input_img – input image file.

Returns:

str

Example:

import rsgislib.imageutils
datatype = rsgislib.imageutils.get_gdal_datatype_name_from_img("img.kea")

Look Up Tables

rsgislib.imageutils.imagelut.query_img_lut(scn_bbox: Tuple[float, float, float, float] | List[float], lut_db_file: str, lyr_name: str) List[str]

A function for querying the LUT DB spatially filtering using a BBOX

Parameters:
  • scn_bbox – A bbox (MinX, MaxX, MinY, MaxY) in the same projection as the LUT for the area of interest.

  • lut_db_file – The file path to the LUT database file (e.g., lut.gpkg).

  • lyr_name – The layer name within the database file.

Returns:

a list of files from the LUT

rsgislib.imageutils.imagelut.get_all_lut_imgs(lut_db_file: str, lyr_name: str) List[str]

Get a list of all the images within the LUT.

Parameters:
  • lut_db_file – The file path to the LUT database file (e.g., lut.gpkg).

  • lyr_name – The layer name within the database file.

Returns:

a list of files from the LUT

rsgislib.imageutils.imagelut.create_img_extent_lut(input_imgs: List[str], vec_file: str, vec_lyr: str, out_format: str, ignore_none_imgs: bool = False, out_proj_wgs84: bool = False, overwrite_lut_file: bool = False)

Create a vector layer look up table (LUT) for a directory of images.

Parameters:
  • input_imgs – list of input images for the LUT. All input images should be the same projection/coordinate system.

  • vec_file – output vector file/path

  • vec_lyr – output vector layer

  • out_format – the output vector layer type (e.g., GPKG).

  • ignore_none_imgs – if a NULL epsg is returned from an image then ignore and don’t include in LUT else throw exception.

  • out_proj_wgs84 – if True then the image bounding boxes will be re-projected to EPSG:4326.

  • overwrite_lut_file – if True then output file will be overwritten. If false then not, e.g., can add extra layer to GPKG

import glob
import rsgislib.imageutils.imagelut
imgList = glob.glob('/Users/pete/Temp/GabonLandsat/Hansen*.kea')
rsgislib.imageutils.imagelut.create_img_extent_lut(imgList,
                                                  'ImgExtents.gpkg',
                                                  'HansenImgExtents', 'GPKG')
rsgislib.imageutils.imagelut.query_file_lut(lut_db_file: str, lyr_name: str, roi_file: str, roi_lyr: str, out_dest: str, targz_out: bool = False, cp_cmds: bool = False) List[str]

A function which allows the file LUT to be queried (intersection) and commands generated for completing operations. Must select (pass true) for either targz_out or cp_cmds not both. If both are False then the list of intersecting files will be returned.

Parameters:
  • lut_db_file – OGR vector file with the LUT.

  • lyr_name – name of the layer within the LUT file.

  • roi_file – region of interest OGR vector file.

  • roi_lyr – layer name within the ROI file.

  • out_dest – the destination for outputs from command (e.g., where are the files to be copied to or output file name for tar.gz file.

  • targz_out – boolean which specifies that the command for generating a tar.gz file should be generated.

  • cp_cmds – boolean which specifies that the command for copying the LUT files to a out_dest should be generated.

Returns:

returns a list of commands to be executed.

rsgislib.imageutils.imagelut.get_raster_lyr(scn_bbox: Tuple[float, float, float, float] | List[float], lut_db_file: str, lyr_name: str, tmp_dir: str) str | None

This function provides a single raster layer using the LUT file provided. If a single image file intersecting with the BBOX is not within the LUT then a VRT generated from a number of images will be returned. The VRT will be within the tmp_path directory which will need to be cleaned up afterwards. If no image(s) is available then None is returned.

Parameters:
  • scn_bbox – A bbox (MinX, MaxX, MinY, MaxY) in the same projection as the LUT for the area of interest.

  • lut_db_file – The file path to the LUT datbase file (e.g., lut.gpkg).

  • lyr_name – The layer name within the database file.

  • tmp_dir – A directory where temporary files can be saved to.

Returns:

a string with the file path to the raster layer. If no image intersects then None is returned.

Check Images

rsgislib.imageutils.do_img_res_match(in_a_img: str, in_b_img: str)

A function to test whether two images have the same image pixel resolution.

Parameters:
  • in_a_img – input image file.

  • in_b_img – input image file.

Returns:

boolean

Example:

import rsgislib.imageutils
if rsgislib.imageutils.do_img_res_match("img1.kea", "img2.kea"):
    print("Images match in terms of resolutions")
rsgislib.imageutils.check_img_lst(input_imgs: List[str], exp_x_res: float, exp_y_res: float, bbox: Tuple[float, float, float, float] | List[float] = None, print_errors: bool = True, abs_res: bool = True)

A function which checks a list of images to ensure they resolution and optionally the bounding box is as expected.

Parameters:
  • input_imgs – a list of input images

  • exp_x_res – the expected image resolution in the x-axis

  • exp_y_res – the expected image resolution in the y-axis

  • bbox – a bbox (MinX, MaxX, MinY, MaxY) where intersection will be tested. Default None and ignored.

  • print_errors – if True then images with errors will be printed to the console. Default: True

Returns:

a list of images which have passed resolution and optional bbox intersection test.

rsgislib.imageutils.check_img_file_comparison(in_base_img: str, in_comp_img: str, test_n_bands: bool = False, test_eql_bbox: bool = False, print_errors: bool = True)
A function which tests whether an image is comparable:
  • Image resolution

  • Intersecting bounding box

  • Optionally the number of bands

  • Optionally whether the BBOXs match rather than intersect

Parameters:
  • in_base_img – base input image which will be compared to

  • in_comp_img – the input image which will be compared to the base.

  • test_n_bands – if true the number of image bands will be checked (i.e., the same)

  • print_errors – if True then images with errors will be printed to the console. Default: True

Parma test_eql_bbox:

if true then the bboxes will need to be identical between the images.

Returns:

Boolean (True; images are compariable)

rsgislib.imageutils.do_images_overlap(in_a_img: str, in_b_img: str, over_thres: int = 0.0)

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

Parameters:
  • in_a_img – path to first image

  • in_b_img – path to second image

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

Returns:

Boolean specifying whether they overlap or not.

import rsgislib.imageutils
overlap = rsgislib.imageutils.do_images_overlap("tile_8.kea", "input.tif")
print("Images Overlap: {}".format(overlap))
rsgislib.imageutils.do_gdal_layers_have_same_proj(in_a_img: str, in_b_img: str)

A function which tests whether two gdal compatible layers are in the same projection/coordinate system. This is done using the GDAL SpatialReference function AutoIdentifyEPSG. If the identified EPSG codes are different then False is returned otherwise True.

Parameters:
  • in_a_img – input image file.

  • in_b_img – input image file.

Returns:

boolean

rsgislib.imageutils.test_img_lst_intersects(input_imgs: List[str], stop_err: bool = False)

A function which will test a list of image to check if they intersect, have matching image resolution and projection. The first image in the list is used as the reference to which all others are compared to.

Parameters:
  • input_imgs – list of images file paths

  • stop_err – boolean. Default: False. If True then an exception will be thrown if error found. If False then errors will just be printed to screen.

Pixel Size / Area

rsgislib.imageutils.calc_wgs84_pixel_area(input_img: str, output_img: str, scale: float = 10000, gdalformat: str = 'KEA')

A function which calculates the area (in metres) of the pixel projected in WGS84.

Parameters:
  • input_img – input image, for which the per-pixel area will be calculated.

  • output_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.imageutils.calc_wsg84_pixel_size(input_img: str, output_img: str, gdalformat: str = 'KEA')

A function which calculates the x and y pixel resolution (in metres) of each pixel projected in WGS84.

Parameters:
  • input_img – input image, for which the per-pixel area will be calculated.

  • output_img – output image file where band 1 is X and band 2 is the Y pixel resolution.

  • gdalformat – the output image file format (default: KEA).

rsgislib.imageutils.calc_pixel_locations(input_img: str, output_img: str, gdalformat: str)

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

Parameters:
  • input_img – the input reference image

  • output_img – 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.calc_wgs84_pixel_locations(input_img: str, output_img: str, gdalformat: str)

Function which produces a 2 band output image with the latitude and longitude locations of the image pixels in WGS84 (EPSG:4326). This function works with data in any projection and is assumed to be used with images which are not projected in EPSG:4326 as you would then use calc_pixel_locations. Note, the outputted pixel locations are an approximation.

Parameters:
  • input_img – the input reference image

  • output_img – 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.

Image File Operations:

rsgislib.imageutils.get_gdal_format_from_ext(input_img: str)

Get GDAL format, based on input_file

Parameters:

input_img – input image file.

Returns:

string

Example:

import rsgislib.imageutils
img_ext = rsgislib.imageutils.get_gdal_format_from_ext("img.kea")
rsgislib.imageutils.get_file_img_extension(gdalformat: str)

A function to get the extension for a given file format (NOTE, currently only KEA, GTIFF, HFA, PCI and ENVI are supported).

Parameters:

gdalformat – GDAL string for the format.

Returns:

string

Example:

import rsgislib.imageutils
img_ext = rsgislib.imageutils.get_file_img_extension("KEA")
rsgislib.imageutils.rename_gdal_layer(input_img: str, output_img: str)

Rename all the files associated with a GDAL layer.

Parameters:
  • input_img – The current name of the GDAL layer.

  • output_img – The output name of the GDAL layer.

Example:

import rsgislib.imageutils
rsgislib.imageutils.rename_gdal_layer("img.kea", "output_img.kea")
rsgislib.imageutils.delete_gdal_layer(input_img: str)

Deletes all the files associated with a GDAL layer.

Parameters:

input_img – The file name and path of the GDAL layer to be deleted.

Example:

import rsgislib.imageutils
rsgislib.imageutils.delete_gdal_layer("img.kea")

Image I/O

rsgislib.imageutils.get_img_pxl_values(input_img: str, img_band: int, x_coords: array, y_coords: array) array

Function which gets pixel values from a image for specified image pixels. The coordinate space is image pixels, i.e., (0 - xSize) and (0 - ySize).

Parameters:
  • input_img – The input image name and path

  • img_band – The band within the input image.

  • x_coords – A numpy array of image X coordinates (in the image pixel coordinates)

  • y_coords – A numpy array of image Y coordinates (in the image pixel coordinates)

Returns:

An array of image pixel values.

rsgislib.imageutils.set_img_pxl_values(input_img: str, img_band: int, x_coords: array, y_coords: array, pxl_value: float = 1)

A function which sets defined image pixels to a value. The coordinate space is image pixels, i.e., (0 - xSize) and (0 - ySize).

Parameters:
  • input_img – The input image name and path

  • img_band – The band within the input image.

  • x_coords – A numpy array of image X coordinates (in the image pixel coordinates)

  • y_coords – A numpy array of image Y coordinates (in the image pixel coordinates)

  • pxl_value – The value to set the image pixel to (specified by the x/y coordinates)

rsgislib.imageutils.get_img_pxl_column(input_img: str, x_pxl_coord: int, y_pxl_coord: int) array

Function which gets pixel band values for a single pixel within an image. The coordinate space is image pixels, i.e., (0 - xSize) and (0 - ySize).

Parameters:
  • input_img – The input image name and path

  • x_pxl_coord – An image X coordinate (in the image pixel coordinates)

  • y_pxl_coord – An image Y coordinate (in the image pixel coordinates)

Returns:

An array of image pixel values (length = the number of image bands).

rsgislib.imageutils.assign_random_pxls(input_img: str, output_img: str, n_pts: int, img_band: int = 1, gdalformat: str = 'KEA', edge_pxl: int = 0, use_no_data: bool = True, rnd_seed: int = None)

A function which can generate a set of random pixels. Can honor the image no data value and use an edge buffer so pixels are not identified near the image edge.

Parameters:
  • input_img – The input image providing the reference area and no data value.

  • output_img – The output image with the random pixels.

  • n_pts – The number of pixels to be sampled.

  • img_band – The image band from the input image used for the no data value.

  • gdalformat – The file format of the output image.

  • edge_pxl – The edge pixel buffer, in pixels. This is a buffer around the edge of the image within which pixels will not be identified. (Default: 0)

  • use_no_data – A boolean specifying whether the image no data value should be used. (Default: True)

  • rnd_seed – A random seed for generating the pixel locations. If None then a different seed is used each time the system is executed (Default None).

input_img = 'LS5TM_20000108_latn531lonw37_r23p204_osgb_clouds_up.kea'
output_img = 'LS5TM_20000108_latn531lonw37_r23p204_osgb_samples.kea'
n_pts = 5000

assign_random_pxls(input_img, output_img, n_pts, img_band=1, gdalformat='KEA')
# Calculate the image stats and pyramids for display
import rsgislib.rastergis
rsgislib.rastergis.pop_rat_img_stats(output_img, True, True, True)
rsgislib.imageutils.generate_random_pxl_vals_img(input_img: str, output_img: str, gdalformat: str, low_val: int, up_val: int)

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

Parameters:
  • input_img – the input reference image

  • output_img – 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.

  • low_val – lower value

  • up_val – upper value

rsgislib.imageutils.get_img_band_pxl_data(input_img: str, img_band: int, bbox_sub: List[float]) array

A function which reads the image pixels values from an image to a numpy array for a spatial subset of the input image.

Parameters:
  • input_img – the path to input image

  • img_band – the band within the input image (note band numbering starts at 1)

  • bbox_sub – the BBOX (MinX, MaxX, MinY, MaxY) defining the spatial subset to be read in.

Returns:

a n x m numpy array with the pixel values.

rsgislib.imageutils.get_img_data_as_arr(input_img: str, img_bands: List[int] = None) ndarray

A function which gets the image data as a numpy array for the whole image extent. If a list of bands is not provided then all the bands will be read and returned in order. If a list is provided the bands will be returned in the order listed in img_bands. Note. GDAL band indexing starts from 1.

Parameters:
  • input_img – the image file path

  • img_bands – optional list of bands to be read.

Returns:

numpy array of the image data (band, height, width)

Pixel Smoothing / Filling

rsgislib.imageutils.spectral_smoothing(input_img: str, valid_msk_img: str, valid_msk_val: int, output_img: str, win_len: int = 5, polyorder: int = 3, gdalformat: str = 'KEA', datatype: int = 9, calc_stats: bool = True)

This function performs spectral smoothing using a Savitzky-Golay filter. Typically applied to hyperspectral data to remove noise.

Parameters:
  • input_img – input image file.

  • valid_msk_img – an image file representing the valid data region

  • valid_msk_val – image pixel value in the mask for the valid data region

  • output_img – the output image file

  • win_len – the window length for the Savitzky-Golay filter (Default: 5)

  • polyorder – the order of the polynomial for the Savitzky-Golay filter (Default: 3)

  • gdalformat – the output file format. (Default: KEA)

  • datatype – the output image datatype (Default: Float 32)

  • calc_stats – Boolean specifying whether to calculate pyramids and metadata stats (Default: True)

rsgislib.imageutils.mask_outliners_data_values(input_img: str, valid_msk_img: str, valid_msk_val: int, output_img: str, lower: int = 5, upper: int = 95, gdalformat: str = 'KEA', calc_stats: bool = True)

This function masks outliners (assigning them to nan; output pixel type must therefore be Float32). Outliners are defined using an upper and lower percentile.

Parameters:
  • input_img – input image file.

  • valid_msk_img – an image file representing the valid data region

  • valid_msk_val – image pixel value in the mask for the valid data region

  • output_img – the output image file

  • lower – the lower percentile threshold (value: 0-100)

  • upper – the upper percentile threshold (value: 0-100)

  • gdalformat – the output file format. (Default: KEA)

  • calc_stats – Boolean specifying whether to calculate pyramids and metadata stats (Default: True)

rsgislib.imageutils.polyfill_nan_data_values(input_img: str, band_vals: List[float], valid_msk_img: str, valid_msk_val: int, output_img: str, polyorder: int = 3, mean_abs_diff: float = None, gdalformat: str = 'KEA', calc_stats: bool = True)

This function fills missing data along (defined as nan values) the y-axis (i.e., along the bands).

Parameters:
  • input_img – input image file.

  • valid_msk_img – an image file representing the valid data region

  • valid_msk_val – image pixel value in the mask for the valid data region

  • output_img – the output image file

  • polyorder – the order of the polynomial (Default: 3)

  • mean_abs_diff – Optional parameter to calculate the absolute mean difference between the predict values have the mean of the original pixel values. This threshold can be used to replace any predicted values which are > than the thresholds specified with the mean.

  • gdalformat – the output file format. (Default: KEA)

  • calc_stats – Boolean specifying whether to calculate pyramids and metadata stats (Default: True)

Other

rsgislib.imageutils.gen_sampling_grid(input_img, output_img, gdalformat, pxl_res, min_val, max_val, single_line)

Generate a regular sampling grid.

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

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

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

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

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

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

  • single_line – 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.whiten_image(input_img: str, valid_msk_img: str, valid_msk_val: int, output_img: str, gdalformat: str)

A function which whitens the input image where the noise covariance matrix is used to decorrelate and rescale the noise in the data (noise whitening). This results in a transformed datset in which the noise has unit variance and no band-to-band correlations. The valid mask is used to identify the areas of valid data. This function is used to an MNF transformation.

WARNING: This function loads the whole image into memory and therefore

can use a lot of memory for the analysis.

Parameters:
  • input_img – the input image

  • valid_msk_img – a valid input image mask

  • valid_msk_val – the pixel value in the mask image specifying valid image pixels.

  • output_img – 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.

Get Image Metadata

rsgislib.imageutils.set_img_band_metadata(input_img: str, img_band: int, meta_field_name: str, meta_field_value: str)

Function to set image band metadata value.

Parameters:
  • input_img – the input image data

  • img_band – the image band for the meta-data to be written to

  • meta_field_name – the field name of the meta-data

  • meta_field_value – the value of the meta-data to be written.

rsgislib.imageutils.get_img_band_metadata(input_img: str, img_band: int, meta_field_name: str)

Function to get image band metadata value.

Parameters:
  • input_img – the input image data

  • img_band – the image band for the meta-data to be read

  • meta_field_name – the field name of the meta-data

rsgislib.imageutils.get_img_band_metadata_fields(input_img: str, img_band: int)

Function to get a list of the image band metadata names.

Parameters:
  • input_img – the input image data

  • img_band – the image band for the meta-data to be read

rsgislib.imageutils.get_img_band_metadata_fields_dict(input_img: str, img_band: int)

Function to get image band metadata names and values as a dict.

Parameters:
  • input_img – the input image data

  • img_band – the image band for the meta-data to be read

rsgislib.imageutils.set_img_metadata(input_img: str, meta_field_name: str, meta_field_value: str)

Function to set image metadata value.

Parameters:
  • input_img – the input image data

  • meta_field_name – the field name of the meta-data

  • meta_field_value – the value of the meta-data to be written.

rsgislib.imageutils.get_img_metadata(input_img: str, meta_field_name: str)

Function to get image metadata value.

Parameters:
  • input_img – the input image data

  • meta_field_name – the field name of the meta-data

rsgislib.imageutils.get_img_metadata_fields(input_img: str)

Function to get a list of the image metadata names.

Parameters:
  • input_img – the input image data

  • band – the image band for the meta-data to be read

rsgislib.imageutils.get_img_metadata_fields_dict(input_img: str)

Function to get image metadata names and values as a dict.

Parameters:

input_img – the input image data