XArray images

class trollimage.xrimage.XRImage(data)

Image class using an xarray.DataArray as internal storage.

It can be saved to a variety of image formats, but if Rasterio is installed, it can save to geotiff and jpeg2000 with geographical information.

The enhancements functions are recording some parameters in the image’s data attribute called enhancement_history.


Initialize the image with a DataArray.

apply_pil(fun, output_mode, pil_args=None, pil_kwargs=None, fun_args=None, fun_kwargs=None)

Apply a function fun on the pillow image corresponding to the instance of the XRImage.

The function shall take a pil image as first argument, and is then passed fun_args and fun_kwargs. In addition, the current images’s metadata is passed as a keyword argument called image_mda. It is expected to return the modified pil image. This function returns a new XRImage instance with the modified image data.

The pil_args and pil_kwargs are passed to the pil_image method of the XRImage instance.


Alpha blend src on top of the current image.

Perform alpha blending of src on top of the current image. Alpha blending is defined as:

\[\begin{split}\begin{cases} \mathrm{out}_A = \mathrm{src}_A + \mathrm{dst}_A (1 - \mathrm{src}_A) \\ \mathrm{out}_{RGB} = \bigl(\mathrm{src}_{RGB}\mathrm{src}_A + \mathrm{dst}_{RGB} \mathrm{dst}_A \left(1 - \mathrm{src}_A \right) \bigr) \div \mathrm{out}_A \\ \mathrm{out}_A = 0 \Rightarrow \mathrm{out}_{RGB} = 0 \end{cases}\end{split}\]

Both images must have mode "RGBA".


src (XRImage with mode "RGBA") – Image to be blended on top of current image.


XRImage with mode “RGBA”, blended as described above


Colorize the current image using colormap.

Convert a greyscale image (mode “L” or “LA”) to a color image (mode “RGB” or “RGBA”) by applying a colormap. If floating point data being colorized contains NaNs then the result will also contain NaNs instead of a color from the colormap. Integer data that includes a .attrs['_FillValue'] will be converted to a floating point array and values equal to _FillValue replaced with NaN before being colorized.

To create a color image in mode “P” or “PA”, use palettize().


colormap (Colormap) – Colormap to be applied to the image.


Works only on “L” or “LA” images.


Convert image to mode.

crude_stretch(min_stretch=None, max_stretch=None)

Perform simple linear stretching.

This is done without any cutoff on the current image and normalizes to the [0,1] range.


Get the mode of the finalized image when provided this fill_value.

finalize(fill_value=None, dtype=<class 'numpy.uint8'>, keep_palette=False)

Finalize the image to be written to an output file.

This adds an alpha band or fills data with a fill_value (if specified). It also scales float data to the output range of the data type (0-255 for uint8, default). For integer input data this method assumes the data is already scaled to the proper desired range. It will still fill in invalid values and add an alpha band if needed. Integer input data’s fill value is determined by a special _FillValue attribute in the DataArray .attrs dictionary.

  • fill_value (int or float or None) – Output value to use to represent invalid or missing pixels. By default this is None meaning an Alpha channel will be used to represent the invalid values; transparent for invalid, opaque otherwise. Some output formats do not support alpha channels so a fill_value must be provided. This is determined by the underlying library doing the writing (pillow or rasterio). If specified, it should be the minimum or maximum of the dtype (ex. 0 or 255 for uint8). Floating point image data is then scaled to fit the remainder of the data type space. Integer image data will not be scaled. For example, a dtype of numpy.uint8 and a fill_value of 0 will result in floating-point data being scaled linearly from 1 to 255.

  • dtype (numpy.dtype) – Output data type to convert the current image data to. Default is unsigned 8-bit integer (numpy.uint8).

  • keep_palette (bool) – Whether to convert a paletted image to RGB/A or not. If False (default) then P mode images will be converted to RGB and PA will be converted to RGBA. If True, images with mode P or PA are kept as is and will not be scaled in order for their index values into a palette to be maintained. This flag should always be False for non-paletted images.


Apply gamma correction to the channels of the image.

If gamma is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If gamma is a number, the same gamma correction is applied on every channel, if there are several channels in the image. The behaviour of gamma() is undefined outside the normal [0,1] range of the channels.


Merge the scales and offsets from the history.

If history isn’t provided, the history of the current image will be used.


Inverts all the channels of a image according to invert.

If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if invert is true (default).

Note: ‘Inverting’ means that black becomes white, and vice-versa, not that the values are negated !


Use the provided image as background for the current img image.

That is if the current image has missing data.

property mode

Mode of the image.


Palettize the current image using colormap.

Convert a mode “L” (or “LA”) grayscale image to a mode “P” (or “PA”) palette image and store the palette in the palette attribute. To store this image in mode “P”, call save() with keep_palette=True. To include color information in the output format (if supported), call save() with keep_palette=True and cmap=colormap.

To (directly) get an image in mode “RGB” or “RGBA”, use colorize().


colormap (Colormap) – Colormap to be applied to the image.


Works only on “L” or “LA” images.

Similar to other enhancement methods (colorize, stretch, etc) this method adds an enhancement_history list to the metadata stored in the image DataArray’s metadata (.attrs). In other methods, however, the metadata directly translates to the linear operations performed in that enhancement. The palettize operation converts data values to indices into a colormap. This result is based on the range of values defined in the Colormap (cmap.values). To be most useful, the enhancement history scale and offset values represent the range of the colormap as if scaling the data to a 0-1 range. This means that once the data is saved to a format as an RGB (the palette colors are applied) the scale and offset can be used to determine the original range of the data based on the min/max of the data type of the format (ex. uint8). For example:

dtype_min = 0
dtype_max = 255
scale = ...  # scale from geotiff
offset = ...  # offset from geotiff
data_min = offset
data_max = (dtype_max - dtype_min) * scale + offset

If a geotiff is saved with keep_palette=True then the data saved to the geotiff are the palette indices and will not be scaled to the data type of the format. There will also be a standard geotiff color table in the geotiff to identify that these are indices rather than some other type of image data. This means in this case the scale and offset can be used to determine the original range of the data starting from a 0-1 range (dtype_min is 0 and dtype_max is 1 in the code above).

pil_image(fill_value=None, compute=True)

Return a PIL image from the current image.

  • fill_value (int or float) – Value to use for NaN null values. See finalize() for more info.

  • compute (bool) – Whether to return a fully computed PIL.Image object (True) or return a dask Delayed object representing the Image (False). This is True by default.

pil_save(filename, fformat=None, fill_value=None, compute=True, **format_kwargs)

Save the image to the given filename using PIL.

For now, the compression level [0-9] is ignored, due to PIL’s lack of support. See also save().

rio_save(filename, fformat=None, fill_value=None, dtype=<class 'numpy.uint8'>, compute=True, tags=None, keep_palette=False, cmap=None, overviews=None, overviews_minsize=256, overviews_resampling=None, include_scale_offset_tags=False, scale_offset_tags=None, colormap_tag=None, driver=None, **format_kwargs)

Save the image using rasterio.

  • filename (string) – The filename to save to.

  • fformat (string) – The format to save to. If not specified (default), it will be infered from the file extension.

  • driver (string) – The gdal driver to use. If not specified (default), it will be inferred from the fformat, but you can override the default GeoTIFF driver (“GTiff”) with “COG” if you want to create a Cloud_Optimized GeoTIFF (and set tiled=True,overviews=[]).

  • fill_value (number) – The value to fill the missing data with. Default is None, translating to trying to keep the data transparent.

  • dtype (np.dtype) – The type to save the data to. Defaults to np.uint8.

  • compute (bool) – Whether (default) or not to compute the lazy data.

  • tags (dict) – Tags to include in the file.

  • keep_palette (bool) – Whether or not (default) to keep the image in P mode.

  • cmap (colormap) – The colormap to use for the data.

  • overviews (list) –

    The reduction factors of the overviews to include in the image, eg:

    img.rio_save('myfile.tif', overviews=[2, 4, 8, 16])

    If provided as an empty list, then levels will be computed as powers of two until the last level has less pixels than overviews_minsize. If driver=’COG’ then use overviews=[] to get a Cloud-Optimized GeoTIFF with a correct set of overviews created automatically. Default is to not add overviews.

  • overviews_minsize (int) – Minimum number of pixels for the smallest overview size generated when overviews is auto-generated. Defaults to 256.

  • overviews_resampling (str) – Resampling method to use when generating overviews. This must be the name of an enum value from rasterio.enums.Resampling and only takes effect if the overviews keyword argument is provided. Common values include nearest (default), bilinear, average, and many others. See the rasterio documentation for more information.

  • scale_offset_tags (Tuple[str, str] or None) – If set to a (str, str) tuple, scale and offset will be stored in GDALMetaData tags. Those can then be used to retrieve the original data values from pixel values. Scale and offset will be set to (NaN, NaN) for images that had non-linear enhancements applied (ex. gamma) as they can’t be represented by a simple scale and offset. Scale and offset are also saved as (NaN, NaN) for multi-band images (ex. RGB) as storing multiple values in a single GDALMetaData tag is not currently supported.

  • colormap_tag (str or None) – If set and the image was colorized or palettized, a tag will be added with this name with the value of a comma-separated version of the Colormap that was used. See trollimage.colormap.Colormap.to_csv() for more information.


The delayed or computed result of the saving.

save(filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=None, driver=None, **format_kwargs)

Save the image to the given filename.

  • filename (str) – Output filename

  • fformat (str) – File format of output file (optional). Can be one of many image formats supported by the rasterio or PIL libraries (‘jpg’, ‘png’, ‘tif’). By default this is determined by the extension of the provided filename. If the format allows, geographical information will be saved to the ouput file, in the form of grid mapping or ground control points.

  • driver (str) – can override the choice of rasterio/gdal driver which is normally selected from the filename or fformat. This is an implementation detail normally avoided but can be necessary if you wish to distinguish between GeoTIFF drivers (“GTiff” is the default, but you can specify “COG” to write a Cloud-Optimized GeoTIFF).

  • fill_value (float) – Replace invalid data values with this value and do not produce an Alpha band. Default behavior is to create an alpha band.

  • compute (bool) – If True (default) write the data to the file immediately. If False the return value is either a dask.Delayed object or a tuple of (source, target) to be passed to dask.array.store.

  • keep_palette (bool) – Saves the palettized version of the image if set to True. False by default. Warning: this does not automatically write the colormap (palette) to the file. To write the colormap to the file, one should additionally pass the colormap with the cmap keyword argument.

  • cmap (Colormap or dict) – Colormap to be applied to the image when saving with rasterio, used with keep_palette=True. Should be uint8.

  • format_kwargs – Additional format options to pass to rasterio or PIL saving methods. Any format argument passed at this stage would be superseeded by fformat.


Either None if compute is True or a dask.Delayed object or (source, target) pair to be passed to dask.array.store. If compute is False the return value depends on format and how the image backend is used. If (source, target) is provided then target is an open file-like object that must be closed by the caller.


Display the image on screen.


Stack the provided image on top of the current image.

stretch(stretch='crude', **kwargs)

Apply stretching to the current image.

The value of stretch sets the type of stretching applied. The values “histogram”, “linear”, “crude” (or “crude-stretch”) perform respectively histogram equalization, contrast stretching (with 5% cutoff on both sides), and contrast stretching without cutoff. The value “logarithmic” or “log” will do a logarithmic enhancement towards white. If a tuple or a list of two values is given as input, then a contrast stretching is performed with the values as cutoff. These values should be normalized in the range [0.0,1.0].


Stretch the current image’s colors through histogram equalization.


approximate (bool) – Use a faster less-accurate percentile calculation. At the time of writing the dask version of percentile is not as accurate as the numpy version. This will likely change in the future. Current dask version 0.17.

stretch_linear(cutoffs=(0.005, 0.005))

Stretch linearly the contrast of the current image.

Use cutoffs for left and right trimming.

stretch_logarithmic(factor=100.0, base='e', min_stretch=None, max_stretch=None)

Move data into range [1:factor] through normalized logarithm.

  • factor (float) – Maximum of the range data will be scaled to before applying the log function. Image data will be scaled to a 1 to factor range.

  • base (str) – Type of log to use. Defaults to natural log (“e”), but can also be “10” for base 10 log or “2” for base 2 log.

  • min_stretch (float or list) – Minimum input value to scale from. Data will be clipped to this value before being scaled to the 1:factor range. By default (None), the limits are computed on the fly but with a performance penalty. May also be a list for multi-band images.

  • max_stretch (float or list) – Maximum input value to scale from. Data will be clipped to this value before being scaled to the 1:factor range. By default (None), the limits are computed on the fly but with a performance penalty. May also be a list for multi-band images.

stretch_weber_fechner(k, s0)

Stretch according to the Weber-Fechner law.

p = k.ln(S/S0) p is perception, S is the stimulus, S0 is the stimulus threshold (the highest unpercieved stimulus), and k is the factor.


Make xarray.DataArray from tuple.