geetools.ImageCollection#

Toolbox for the ee.ImageCollection class.

Package Contents#

Classes#

ImageCollectionAccessor

Toolbox for the ee.ImageCollection class.

class geetools.ImageCollection.ImageCollectionAccessor(obj)[source]#

Toolbox for the ee.ImageCollection class.

Instantiate the class.

Parameters:

obj (ee.ImageCollection) –

append(image)[source]#

Append an image to the existing image collection.

Parameters:

image (ee.Image) – Image to append to the collection.

Returns:

ImageCollection with the new image appended.

Return type:

ee.ImageCollection

Examples

import ee, geetools

ee.Initialize()

ic = ee.ImageCollection('COPERNICUS/S2_SR');

geom = ee.Geometry.Point(-122.196, 41.411);
ic2018 = ic.filterBounds(geom).filterDate('2019-07-01', '2019-10-01')
ic2021 = ic.filterBounds(geom).filterDate('2021-07-01', '2021-10-01')

ic = ic2018.append(ic2021.first())
ic.getInfo()
closest(date, tolerance=1, unit='month')[source]#

Gets the closest image (or set of images if the collection intersects a region that requires multiple scenes) to the specified date.

Parameters:
  • date (Union[ee.Date, str]) – Date of interest. The method will look for images closest to this date.

  • tolerance (int) – Filter the collection to [date - tolerance, date + tolerance) before searching the closest image. This speeds up the searching process for collections with a high temporal resolution.

  • unit (str) – Units for tolerance. Available units: ‘year’, ‘month’, ‘week’, ‘day’, ‘hour’, ‘minute’ or ‘second’.

Returns:

Closest images to the specified date.

Return type:

ee.ImageCollection

Examples

import ee
import geetools

s2 = ee.ImageCollection('COPERNICUS/S2_SR').closest('2020-10-15')
s2.size().getInfo()
collectionMask()[source]#

A binary ee.Image where only pixels that are masked in all images of the collection get masked.

Returns:

ee.Image of the mask. 1 where at least 1 pixel is valid 0 elswere

Return type:

ee.Image

Examples

import ee, geetools

ee.Initialize()

ic = ee.ImageCollection('COPERNICUS/S2_SR');

geom = ee.Geometry.Point(-122.196, 41.411);
ic2018 = ic.filterBounds(geom).filterDate('2019-07-01', '2019-10-01')
ic = ic2018.geetools.collectionMask()
ic.getInfo()
getCitation()[source]#

Gets the citation of the image, if available.

Returns:

Citation of the ee.Image dataset.

Return type:

str

Examples

import ee
import geetools

ee.Initialize()

ee.ImageCollection('NASA/GPM_L3/IMERG_V06').getCitation()
getDOI()[source]#

Gets the DOI of the collection, if available.

Returns:

DOI of the ee.Image dataset.

Return type:

str

Examples

import ee
import geetools

ee.Initialize()

ee.ImageCollection('NASA/GPM_L3/IMERG_V06').getDOI()
getOffsetParams()[source]#

Gets the offset parameters for each band of the image.

Returns:

Dictionary with the offset parameters for each band.

Return type:

dict

Examples


import ee import geetools

ee.Initialize()

ee.ImageCollection(‘MODIS/006/MOD11A2’).getOffsetParams()

getSTAC()[source]#

Gets the STAC of the image.

Returns:

STAC of the image.

Return type:

dict

Examples


import ee import geetools

ee.Initialize()

ee.ImageCollection(‘COPERNICUS/S2_SR’).getSTAC()

getScaleParams()[source]#

Gets the scale parameters for each band of the image.

Returns:

Dictionary with the scale parameters for each band.

Return type:

dict

Examples

import ee
import geetools

ee.Initialize()

ee.ImageCollection('MODIS/006/MOD11A2').geetools.getScaleParams()
iloc(index)[source]#

Get Image from the ImageCollection by index.

Parameters:

index (int) – Index of the image to get.

Returns:

ee.Image at the specified index.

Return type:

ee.Image

Examples

import ee, geetools

ee.Initialize()

ic = ee.ImageCollection('COPERNICUS/S2_SR');

geom = ee.Geometry.Point(-122.196, 41.411);
ic2018 = ic.filterBounds(geom).filterDate('2019-07-01', '2019-10-01')
ic2018.geetools.iloc(0).getInfo()
integral(band, time='system:time_start', unit='')[source]#

Compute the integral of a band over time or a specified property.

Parameters:
  • band (str) – the name of the band to integrate

  • time (str) – the name of the property to use as time. It must be a date property of the images.

  • unit (str) – the time unit use to compute the integral. It can be one of the following: [“year”, “month”, “day”, “hour”, “minute”, “second”]. If non is set, the time will be normalized on the integral length.

Returns:

An Image object with the integrated band for each pixel

Return type:

ee.Image

Examples

import ee, LDCGEETools

collection = (
    ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
    .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
    .filterDate("2014-01-01", "2014-12-31")
)

integral = collection.ldc.integral("B1")
print(integral.getInfo())
maskClouds(method='cloud_prob', prob=60, maskCirrus=True, maskShadows=True, scaledImage=False, dark=0.15, cloudDist=1000, buffer=250, cdi=None)[source]#

Masks clouds and shadows in each image of an ImageCollection (valid just for Surface Reflectance products).

Parameters:
  • self – ImageCollection to mask.

  • method (str) –

    Method used to mask clouds. This parameter is ignored for Landsat products. Available options:

    • ’cloud_prob’ : Use cloud probability.

    • ’qa’ : Use Quality Assessment band.

  • prob (int) – Cloud probability threshold. Valid just for method = ‘cloud_prob’. This parameter is ignored for Landsat products.

  • maskCirrus (bool) – Whether to mask cirrus clouds. Default to True. Valid just for method = ‘qa’. This parameter is ignored for Landsat products.

  • maskShadows (bool) – Whether to mask cloud shadows. Default to True This parameter is ignored for Landsat products.

  • scaledImage (bool) – Whether the pixel values are scaled to the range [0,1] (reflectance values). This parameter is ignored for Landsat products.

  • dark (float) – NIR threshold. NIR values below this threshold are potential cloud shadows. This parameter is ignored for Landsat products.

  • cloudDist (int) – Maximum distance in meters (m) to look for cloud shadows from cloud edges. This parameter is ignored for Landsat products.

  • buffer (int) – Distance in meters (m) to dilate cloud and cloud shadows objects. This parameter is ignored for Landsat products.

  • cdi (Optional[int]) – Cloud Displacement Index threshold. Values below this threshold are considered potential clouds. A cdi = None means that the index is not used. This parameter is ignored for Landsat products.

Returns:

Cloud-shadow masked image.

Return type:

ee.ImageCollection

Notes

This method may mask water as well as clouds for the Sentinel-3 Radiance product.

Examples

import ee, geetools

ee.Initialize()
S2 = (
    ee.ImageCollection('COPERNICUS/S2_SR')
    .maskClouds(prob = 75,buffer = 300,cdi = -0.5)
    .first()
)
outliers(bands=[], sigma=2, drop=False)[source]#

Compute the outlier for each pixel in the specified bands.

A pixel is considered as an outlier if:

outlier = value > mean+(sigma*stddev)
outlier = value < mean-(sigma*stddev)

In a 1D example it would be: - values = [1, 5, 6, 4, 7, 10] - mean = 5.5 - std dev = 3 - mean + (sigma*stddev) = 8.5 - mean - (sigma*stddev) = 2.5 - outliers = values between 2.5 and 8.5 = [1, 10]

Here in this function an extra band is added to each image for each of the evaluated bands with the outlier status. The band name is the original band name with the suffix “_outlier”. A value of 1 means that the pixel is an outlier, 0 means that it is not.

Optionally users can discard this band by setting drop to True and the outlier will simply be masked from each ilmage. This is useful when the outlier band is not needed and the user wants to save space.

idea from: https://www.kdnuggets.com/2017/02/removing-outliers-standard-deviation-python.html

Parameters:
  • bands (geetools.types.ee_list) – the bands to evaluate for outliers. If empty, all bands are evaluated

  • sigma (geetools.types.ee_number) – the number of standard deviations to use to compute the outlier

  • drop (bool) – whether to drop the outlier band from the images

Returns:

an ImageCollection with the outlier band added to each image or masked if drop is True

Return type:

ee.ImageCollection

Examples

import ee, LDCGEETools

collection = (
    ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
    .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
    .filterDate("2014-01-01", "2014-12-31")
)

outliers = collection.ldc.outliers(["B1", "B2"], 2)
print(outliers.getInfo())
panSharpen(method='SFIM', qa='', **kwargs)[source]#

Apply panchromatic sharpening to the ImageCollection images.

Optionally, run quality assessments between the original and sharpened Image to measure spectral distortion and set results as properties of the sharpened Image.

Parameters:
  • method (str) – The sharpening algorithm to apply. Current options are “SFIM” (Smoothing Filter-based Intensity Modulation), “HPFA” (High Pass Filter Addition), “PCS” (Principal Component Substitution), and “SM” (simple mean). Different sharpening methods will produce different quality sharpening results in different scenarios.

  • qa (str) – One or more optional quality assessment names to apply after sharpening. Results will be stored as image properties with the pattern geetools:metric, e.g. geetools:RMSE.

  • **kwargs – Keyword arguments passed to ee.Image.reduceRegion() such as “geometry”, “maxPixels”, “bestEffort”, etc. These arguments are only used for PCS sharpening and quality assessments.

Returns:

The ImageCollections with all sharpenable bands sharpened to the panchromatic resolution and quality assessments run and set as properties.

Return type:

ee.ImageCollection

Examples

import ee
import geetools

ee.Initialize()

source = ee.Image("LANDSAT/LC08/C01/T1_TOA/LC08_047027_20160819")
sharp = source.panSharpen(method="HPFA", qa=["MSE", "RMSE"], maxPixels=1e13)
preprocess(**kwargs)[source]#

Pre-processes the image: masks clouds and shadows, and scales and offsets the image.

Parameters:

**kwargs – Keywords arguments for maskClouds method.

Returns:

Pre-processed image.

Return type:

ee.ImageCollection

Examples


import ee import geetools

ee.Initialize() S2 = ee.ImageCollection(‘COPERNICUS/S2_SR’).preprocess()

scaleAndOffset()[source]#

Scales bands on an image according to their scale and offset parameters.

Returns:

Scaled image.

Return type:

ee.ImageCollection

Examples

import ee, geetools

ee.Initialize()

S2 = ee.ImageCollection('COPERNICUS/S2_SR').scaleAndOffset()
spectralIndices(index='NDVI', G=2.5, C1=6.0, C2=7.5, L=1.0, cexp=1.16, nexp=2.0, alpha=0.1, slope=1.0, intercept=0.0, gamma=1.0, omega=2.0, beta=0.05, k=0.0, fdelta=0.581, kernel='RBF', sigma='0.5 * (a + b)', p=2.0, c=1.0, lambdaN=858.5, lambdaR=645.0, lambdaG=555.0, online=False)[source]#

Computes one or more spectral indices (indices are added as bands) for an image from the Awesome List of Spectral Indices.

Parameters:
  • self – Image to compute indices on. Must be scaled to [0,1].

  • index (str) –

    Index or list of indices to compute, default = ‘NDVI’ Available options:

    • ’vegetation’ : Compute all vegetation indices.

    • ’burn’ : Compute all burn indices.

    • ’water’ : Compute all water indices.

    • ’snow’ : Compute all snow indices.

    • ’urban’ : Compute all urban (built-up) indices.

    • ’kernel’ : Compute all kernel indices.

    • ’all’ : Compute all indices listed below.

    • Awesome Spectral Indices for GEE: Check the complete list of indices here.

  • G (geetools.types.number) – Gain factor. Used just for index = ‘EVI’, default = 2.5

  • C1 (geetools.types.number) – Coefficient 1 for the aerosol resistance term. Used just for index = ‘EVI’, default = 6.0

  • C2 (geetools.types.number) – Coefficient 2 for the aerosol resistance term. Used just for index = ‘EVI’, default = 7.5

  • L (geetools.types.number) – Canopy background adjustment. Used just for index = [‘EVI’,’SAVI’], default = 1.0

  • cexp (geetools.types.number) – Exponent used for OCVI, default = 1.16

  • nexp (geetools.types.number) – Exponent used for GDVI, default = 2.0

  • alpha (geetools.types.number) – Weighting coefficient used for WDRVI, default = 0.1

  • slope (geetools.types.number) – Soil line slope, default = 1.0

  • intercept (geetools.types.number) – Soil line intercept, default = 0.0

  • gamma (geetools.types.number) – Weighting coefficient used for ARVI, default = 1.0

  • omega (geetools.types.number) – Weighting coefficient used for MBWI, default = 2.0

  • beta (geetools.types.number) – Calibration parameter used for NDSIns, default = 0.05

  • k (geetools.types.number) – Slope parameter by soil used for NIRvH2, default = 0.0

  • fdelta (geetools.types.number) – Adjustment factor used for SEVI, default = 0.581

  • kernel (str) –

    Kernel used for kernel indices, default = ‘RBF’ Available options:

    • ’linear’ : Linear Kernel.

    • ’RBF’ : Radial Basis Function (RBF) Kernel.

    • ’poly’ : Polynomial Kernel.

  • sigma (str) – Length-scale parameter. Used for kernel = ‘RBF’, default = ‘0.5 * (a + b)’. If str, this must be an expression including ‘a’ and ‘b’. If numeric, this must be positive.

  • p (geetools.types.number) – Kernel degree. Used for kernel = ‘poly’, default = 2.0

  • c (geetools.types.number) – Free parameter that trades off the influence of higher-order versus lower-order terms in the polynomial kernel. Used for kernel = ‘poly’, default = 1.0. This must be greater than or equal to 0.

  • lambdaN (geetools.types.number) – NIR wavelength used for NIRvH2 and NDGI, default = 858.5

  • lambdaR (geetools.types.number) – Red wavelength used for NIRvH2 and NDGI, default = 645.0

  • lambdaG (geetools.types.number) – Green wavelength used for NDGI, default = 555.0

  • drop – Whether to drop all bands except the new spectral indices, default = False

  • online (geetools.types.number) –

Returns:

Image with the computed spectral index, or indices, as new bands.

Return type:

ee.ImageCollection

Examples

import ee, geetools

ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR/20190828T151811_20190828T151809_T18GYT')
image = image.geetools.specralIndices(["NDVI", "NDFI"])
tasseledCap()[source]#

Calculates tasseled cap brightness, wetness, and greenness components.

Tasseled cap transformations are applied using coefficients published for these supported platforms:

  • Sentinel-2 MSI Level 1C

  • Landsat 9 OLI-2 SR

  • Landsat 9 OLI-2 TOA

  • Landsat 8 OLI SR

  • Landsat 8 OLI TOA

  • Landsat 7 ETM+ TOA

  • Landsat 5 TM Raw DN

  • Landsat 4 TM Raw DN

  • Landsat 4 TM Surface Reflectance

  • MODIS NBAR

Parameters:

self – ee.ImageCollection to calculate tasseled cap components for. Must belong to a supported platform.

Returns:

ImageCollections with the tasseled cap components as new bands.

Return type:

ee.ImageCollection

Examples

import ee, geetools

ee.Initialize()

image = ee.Image('COPERNICUS/S2_SR')
img = img.tasseledCap()
to_xarray(drop_variables=None, io_chunks=None, n_images=-1, mask_and_scale=True, decode_times=True, decode_timedelta=None, use_cftime=None, concat_characters=True, decode_coords=True, crs=None, scale=None, projection=None, geometry=None, primary_dim_name=None, primary_dim_property=None, ee_mask_value=None, request_byte_limit=REQUEST_BYTE_LIMIT)[source]#

Open an Earth Engine ImageCollection as an xarray.Dataset.

Parameters:
  • drop_variables (Optional[Tuple[str, Ellipsis]]) – Variables or bands to drop before opening.

  • io_chunks (Optional[Any]) – Specifies the chunking strategy for loading data from EE. By default, this automatically calculates optional chunks based on the request_byte_limit.

  • n_images (int) – The max number of EE images in the collection to open. Useful when there are a large number of images in the collection since calculating collection size can be slow. -1 indicates that all images should be included.

  • mask_and_scale (bool) – Lazily scale (using scale_factor and add_offset) and mask (using _FillValue).

  • decode_times (bool) – Decode cf times (e.g., integers since “hours since 2000-01-01”) to np.datetime64.

  • decode_timedelta (Optional[bool]) – If True, decode variables and coordinates with time units in {“days”, “hours”, “minutes”, “seconds”, “milliseconds”, “microseconds”} into timedelta objects. If False, leave them encoded as numbers. If None (default), assume the same value of decode_time.

  • use_cftime (Optional[bool]) – Only relevant if encoded dates come from a standard calendar (e.g. “gregorian”, “proleptic_gregorian”, “standard”, or not specified). If None (default), attempt to decode times to np.datetime64[ns] objects; if this is not possible, decode times to cftime.datetime objects. If True, always decode times to cftime.datetime objects, regardless of whether or not they can be represented using np.datetime64[ns] objects. If False, always decode times to np.datetime64[ns] objects; if this is not possible raise an error.

  • concat_characters (bool) – Should character arrays be concatenated to strings, for example: [“h”, “e”, “l”, “l”, “o”] -> “hello”

  • decode_coords (bool) – bool or {“coordinates”, “all”}, Controls which variables are set as coordinate variables: - “coordinates” or True: Set variables referred to in the 'coordinates' attribute of the datasets or individual variables as coordinate variables. - “all”: Set variables referred to in 'grid_mapping', 'bounds' and other attributes as coordinate variables.

  • crs (Optional[str]) – The coordinate reference system (a CRS code or WKT string). This defines the frame of reference to coalesce all variables upon opening. By default, data is opened with ‘EPSG:4326’.

  • scale (Union[float, int, None]) – The scale in the crs or projection’s units of measure – either meters or degrees. This defines the scale that all data is represented in upon opening. By default, the scale is 1° when the CRS is in degrees or 10,000 when in meters.

  • projection (Optional[ee.Projection]) – Specify an ee.Projection object to define the scale and crs (or other coordinate reference system) with which to coalesce all variables upon opening. By default, the scale and reference system is set by the the crs and scale arguments.

  • geometry (Optional[ee.Geometry]) – Specify an ee.Geometry to define the regional bounds when opening the data. When not set, the bounds are defined by the CRS’s area_of_use boundaries. If those aren’t present, the bounds are derived from the geometry of the first image of the collection.

  • primary_dim_name (Optional[str]) – Override the name of the primary dimension of the output Dataset. By default, the name is ‘time’.

  • primary_dim_property (Optional[str]) – Override the ee.Image property for which to derive the values of the primary dimension. By default, this is ‘system:time_start’.

  • ee_mask_value (Optional[float]) – Value to mask to EE nodata values. By default, this is ‘np.iinfo(np.int32).max’ i.e. 2147483647.

  • request_byte_limit (int) – the max allowed bytes to request at a time from Earth Engine. By default, it is 48MBs.

Returns:

An xarray.Dataset that streams in remote data from Earth Engine.

Return type:

xarray.Dataset