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

Parameters: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.


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.


Mode of the image.


Palettize the current image using colormap.


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

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

The delayed or computed result of the saving.

save(filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=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.
  • 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.
  • 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.

Parameters: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.


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

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.