trollimage package
Subpackages
- trollimage.tests package
- Submodules
- trollimage.tests.test_colormap module
TestColormap
TestColormap.test_add()
TestColormap.test_bad_color_dims()
TestColormap.test_colorbar()
TestColormap.test_colorize_dask_with_interpolation()
TestColormap.test_colorize_no_interpolation()
TestColormap.test_colorize_with_interpolation()
TestColormap.test_colorize_with_large_hue_jumps()
TestColormap.test_diff_colors_values()
TestColormap.test_invert_set_range()
TestColormap.test_merge_equal_values()
TestColormap.test_merge_monotonic_decreasing()
TestColormap.test_merge_nonmonotonic()
TestColormap.test_merge_rgb_rgba()
TestColormap.test_nonfloat_colors()
TestColormap.test_only_colors_only_values()
TestColormap.test_palettebar()
TestColormap.test_palettize_edge_of_dtype_range()
TestColormap.test_palettize_in_range()
TestColormap.test_palettize_mono_inc_in_range_dask()
TestColormap.test_palettize_mono_inc_nan()
TestColormap.test_palettize_mono_inc_out_range()
TestColormap.test_reverse()
TestColormap.test_set_alpha_range()
TestColormap.test_set_range()
TestColormap.test_to_rgb()
TestColormap.test_to_rgba()
TestColormap.test_to_rio()
TestFromFileCreation
TestFromFileCreation.test_cmap_bad_mode()
TestFromFileCreation.test_cmap_from_csv()
TestFromFileCreation.test_cmap_from_file()
TestFromFileCreation.test_cmap_from_file_bad_shape()
TestFromFileCreation.test_cmap_from_np()
TestFromFileCreation.test_cmap_vrgb_as_rgba()
TestFromFileCreation.test_csv_roundtrip()
closed_named_temp_file()
test_build_colormap_with_float_data()
test_build_colormap_with_int_data_and_with_meanings()
test_build_colormap_with_int_data_and_without_meanings()
test_cmap_from_name()
test_cmap_from_ndarray()
test_cmap_from_sequence_of_colors()
test_cmap_from_string()
- trollimage.tests.test_image module
TestEmptyImage
TestEmptyImage.setUp()
TestEmptyImage.test_clip()
TestEmptyImage.test_convert()
TestEmptyImage.test_gamma()
TestEmptyImage.test_invert()
TestEmptyImage.test_is_empty()
TestEmptyImage.test_merge()
TestEmptyImage.test_pil_image()
TestEmptyImage.test_putalpha()
TestEmptyImage.test_replace_luminance()
TestEmptyImage.test_resize()
TestEmptyImage.test_save()
TestEmptyImage.test_shape()
TestEmptyImage.test_stretch()
TestFlatImage
TestImageColorize
TestImageCreation
TestNoDataImage
TestRegularImage
TestRegularImage.setUp()
TestRegularImage.tearDown()
TestRegularImage.test_clip()
TestRegularImage.test_convert()
TestRegularImage.test_gamma()
TestRegularImage.test_invert()
TestRegularImage.test_is_empty()
TestRegularImage.test_merge()
TestRegularImage.test_pil_image()
TestRegularImage.test_putalpha()
TestRegularImage.test_replace_luminance()
TestRegularImage.test_resize()
TestRegularImage.test_save()
TestRegularImage.test_save_jpeg()
TestRegularImage.test_shape()
TestRegularImage.test_stretch()
TestXRImage
TestXRImage.test_LA_save()
TestXRImage.test_L_save()
TestXRImage.test_PA_save()
TestXRImage.test_P_save()
TestXRImage.test_apply_pil()
TestXRImage.test_blend()
TestXRImage.test_convert_modes()
TestXRImage.test_crude_stretch()
TestXRImage.test_crude_stretch_integer_data()
TestXRImage.test_crude_stretch_with_limits()
TestXRImage.test_delayed_save_geotiff_float_dask_array()
TestXRImage.test_final_mode()
TestXRImage.test_gamma_noop()
TestXRImage.test_gamma_per_channel()
TestXRImage.test_gamma_single_value()
TestXRImage.test_gtiff_save()
TestXRImage.test_histogram_stretch()
TestXRImage.test_init()
TestXRImage.test_init_writability()
TestXRImage.test_invert()
TestXRImage.test_jpeg_save()
TestXRImage.test_linear_stretch()
TestXRImage.test_linear_stretch_does_affect_alpha_with_explicit_cutoffs()
TestXRImage.test_linear_stretch_does_not_affect_alpha()
TestXRImage.test_linear_stretch_does_not_affect_alpha_with_partial_cutoffs()
TestXRImage.test_linear_stretch_integers()
TestXRImage.test_logarithmic_stretch()
TestXRImage.test_merge()
TestXRImage.test_putalpha()
TestXRImage.test_regression_double_format_save()
TestXRImage.test_replace_luminance()
TestXRImage.test_rgb_save()
TestXRImage.test_save_cloud_optimized_geotiff()
TestXRImage.test_save_geotiff_closed_file()
TestXRImage.test_save_geotiff_datetime()
TestXRImage.test_save_geotiff_delayed()
TestXRImage.test_save_geotiff_float_dask_array()
TestXRImage.test_save_geotiff_float_dask_array_to_float()
TestXRImage.test_save_geotiff_float_dask_array_to_float_with_nans_fill_value()
TestXRImage.test_save_geotiff_float_dask_array_to_float_with_numeric_fill_value()
TestXRImage.test_save_geotiff_float_dask_array_to_signed_int()
TestXRImage.test_save_geotiff_float_dask_array_with_alpha()
TestXRImage.test_save_geotiff_float_dask_array_with_nans()
TestXRImage.test_save_geotiff_float_dask_array_with_nans_and_fill_value()
TestXRImage.test_save_geotiff_float_numpy_array()
TestXRImage.test_save_geotiff_int()
TestXRImage.test_save_geotiff_int_gcps()
TestXRImage.test_save_geotiff_int_no_gcp_swath()
TestXRImage.test_save_geotiff_int_rio_colormap()
TestXRImage.test_save_geotiff_int_with_area_def()
TestXRImage.test_save_geotiff_int_with_bad_cmap()
TestXRImage.test_save_geotiff_int_with_cmap()
TestXRImage.test_save_geotiff_int_with_fill()
TestXRImage.test_save_geotiff_int_with_fill_and_alpha()
TestXRImage.test_save_jp2_int()
TestXRImage.test_save_masked()
TestXRImage.test_save_overviews()
TestXRImage.test_save_palettes()
TestXRImage.test_save_single_band_jpeg()
TestXRImage.test_save_single_band_png()
TestXRImage.test_save_tags()
TestXRImage.test_show()
TestXRImage.test_stack()
TestXRImage.test_weber_fechner_stretch()
TestXRImageColorize
TestXRImagePalettize
TestXRImageSaveScaleOffset
TestXRImageSaveScaleOffset.setup_method()
TestXRImageSaveScaleOffset.test_gamma_geotiff_scale_offset()
TestXRImageSaveScaleOffset.test_rgb_geotiff_scale_offset()
TestXRImageSaveScaleOffset.test_save_scale_offset()
TestXRImageSaveScaleOffset.test_save_scale_offset_custom_labels()
TestXRImageSaveScaleOffset.test_save_scale_offset_custom_values()
TestXRImageSaveScaleOffset.test_save_scale_offset_from_lists()
random_string()
- trollimage.tests.utils module
- Module contents
Submodules
trollimage.colormap module
A simple colormap module.
- class trollimage.colormap.Colormap(*tuples, **kwargs)
Bases:
object
The colormap object.
- Parameters:
*args – Series of (value, color) tuples. These positional arguments are only used if the
values
andcolors
keyword arguments aren’t provided.values – One dimensional array-like of control points where each corresponding color is applied. Must be the same number of elements as colors and must be monotonic.
colors – Two dimensional array-like of RGB or RGBA colors where each color is applied to a specific control point. Must be the same number of colors as control points (values). Colors should be floating point numbers between 0 and 1.
Initialize with tuples of (value, (colors)), like this:
Colormap((-75.0, (1.0, 1.0, 0.0)), (-40.0001, (0.0, 1.0, 1.0)), (-40.0, (1, 1, 1)), (30.0, (0, 0, 0)))
You can also concatenate colormaps together, try:
cm = cm1 + cm2
- colorize(data)
Colorize a monochromatic array data, based on the current colormap.
- classmethod from_array_with_metadata(palette, dtype, color_scale=255, valid_range=None, scale_factor=1, add_offset=0, remove_last=True)
Create Colormap from an array with metadata.
Create a colormap from an array with associated metadata, either in attributes or passed on to the function.
For historical reasons, this method exists alongside
from_ndarray()
andfrom_sequence_of_colors()
despite similar functionality.If
palette
is an xarray dataarray with the attributepalette_meanings
, those meanings are interpreted as values associated with the colormap.If no values can be interpreted from the metadata, values will be linearly interpolated between 0 and 255 (if
dtype
isnp.uint8
) or according tovalid_range
.- Parameters:
palette (ndarray or xarray.DataArray) – Array describing colors, possibly with metadata. If it has a
palette_meanings
attribute, this will be used for color interpretation.dtype – dtype for the colormap
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
valid_range – valid range for colors, if colormap is not of dtype uint8
scale_factor – scale factor to apply to the colormap
add_offset – add offset to apply to the colormap
remove_last – Remove the last value if the array has no metadata associated. Defaults to true for historical reasons.
- classmethod from_csv(path, colormap_mode=None, color_scale=255)
Create Colormap from CSV file.
Create a Colormap from a file that contains comma seperated values (CSV).
To read from a string that contains CSV, use
from_string()
.- Parameters:
string (str or pathlib.Path) – Path to file containing CSV. The CSV must have at least three and at most five columns and describe entirely numeric data.
colormap_mode (str or None) – Optional. Can be None, “RGB”, “RGBA”, “VRGB”, or “VRGBA”. If None (default), this is inferred from the dimensions of the data contained in the CSV. Modes starting with V have in the first column the values to which the color relates.
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
- classmethod from_file(filename: str, colormap_mode: str | None = None, color_scale: Number = 255)
Create Colormap from a comma-separated or binary file of colormap data.
- Parameters:
filename – Filename of a binary or CSV file
colormap_mode – Force the scheme of the colormap data (ex. RGBA). See information below on other possible values and how they are interpreted. By default this is determined based on the number of columns in the data.
color_scale – The maximum possible color value in the colormap data provided. For example, if the colors in the provided data were 8-bit unsigned integers this should be 255 (the default). This value will be used to normalize the colors from 0 to 1.
Colormaps can be loaded from
.npy
,.npz
, or comma-separated text files. Numpy (npy/npz) files should be 2D arrays with rows for each color. Comma-separated files should have a row for each color with each column representing a single value/channel. A filename ending with.npy
or.npz
is read as a numpy file withnumpy.load()
. All other extensions are read as a comma-separated file. For.npz
files the data must be stored as a positional list where the first element represents the colormap to use. Seenumpy.savez()
for more information.The colormap is interpreted as 1 of 4 different “colormap modes”:
RGB
,RGBA
,VRGB
, orVRGBA
. The colormap mode can be forced with thecolormap_mode
keyword argument. If it is not provided then a default will be chosen based on the number of columns in the array (3: RGB, 4: VRGB, 5: VRGBA).The “V” in the possible colormap modes represents the control value of where that color should be applied. If “V” is not provided in the colormap data it defaults to the row index in the colormap array (0, 1, 2, …) divided by the total number of colors to produce a number between 0 and 1. See the “Set Range” section below for more information. The remaining elements in the colormap array represent the Red (R), Green (G), and Blue (B) color to be mapped to.
See the “Color Scale” section below for more information on the value range of provided numbers.
To read from a string containing CSV, use
from_csv()
.To get a named colormap, use
from_name()
or load the colormap directly as a module attribute.To get a colormap from an ndarray, use
from_ndarray()
.Color Scale
By default colors are expected to be in a 0-255 range. This can be overridden by specifying
color_scale
keyword argument. A common alternative to 255 is1
to specify floating point numbers between 0 and 1. The resulting Colormap uses the normalized color values (0-1).
- classmethod from_name(name)
Return named colormap.
Return a colormap by name. Supported colormaps are the ones defined in the module namespace.
- Parameters:
name (str) – Name of colormap.
- classmethod from_ndarray(cmap_data, colormap_mode=None, color_scale=255)
Create Colormap from ndarray.
Create a colormap from a numpy data array.
The data should contain at least three and at most five columns.
For historical reasons, this method exists alongside
from_sequence_of_colors()
andfrom_array_with_metadata()
despite similar functionality.- Parameters:
cmap_data (ndarray) – Array describing the colours. Must have at least three and at most five columns and have a numeric dtype.
colormap_mode (str or None) – Optional. Can be None, “RGB”, “RGBA”, “VRGB”, or “VRGBA”. If None (default), this is inferred from the dimensions of the data contained in the CSV. Modes starting with V have in the first column the values to which the color relates.
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
- classmethod from_np(path, *args, **kwargs)
Create Colormap from a numpy-file.
Create a colormap from a numpy data file
.npy
or.npz
.The data should contain at least three and at most five columns.
- Parameters:
path (str or Pathlib.Path) – Path to file containing numpy data.
colormap_mode (str or None) – Optional. Can be None, “RGB”, “RGBA”, “VRGB”, or “VRGBA”. If None (default), this is inferred from the dimensions of the data contained in the CSV. Modes starting with V have in the first column the values to which the color relates.
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
- classmethod from_sequence_of_colors(colors, values=None, color_scale=255)
Create Colormap from sequence of colors.
Create a colormap from a sequence of colors, such as a list of colors. If values is not given, assume values between 0 and 1, linearly spaced according to the total number of colors.
For historical reasons, this method exists alongside
from_ndarray()
andfrom_array_with_metadata()
despite similar functionality.- Parameters:
colors (Sequence) – List of colors, where each element must itself be a sequence of 3 or 4 numbers (RGB or RGBA).
values (array, optional) – Values associated with the colors. If not given, assume linear between 0 and 1.
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
- classmethod from_string(string, *args, **kwargs)
Create colormap from string.
Create a colormap from a string that contains comma seperated values (CSV).
To read from an external file that contains CSV, use
from_csv()
.- Parameters:
string (str) – String containing CSV. Must have no less than three and no more than five columns and describe entirely numeric data.
colormap_mode (str or None) – Optional. Can be None, “RGB”, “RGBA”, “VRGB”, or “VRGBA”. If None (default), this is inferred from the dimensions of the data contained in the CSV. Modes starting with V have in the first column the values to which the color relates.
color_scale (number) – The value that represents white in the numbers describing the colors. Defaults to 255, could also be 1 or something else.
- palettize(data)
Palettize a monochromatic array data based on the current colormap.
- reverse(inplace=True)
Reverse the current colormap in place.
- Parameters:
inplace (bool) – If True (default), modify the colors of this Colormap inplace. If False, return a new instance.
- set_alpha_range(min_alpha, max_alpha, inplace=True)
Set the colormap alpha channel between two values in linear steps.
If the input colormap does not have an alpha channel, it will be added to it. If an alpha channel is already existing, the values will be overwritten.
The min and max values shall be between 0 (completely transparent) and 1 (completely opaque).
- set_range(min_val, max_val, inplace=True)
Set the range of the colormap to [min_val, max_val].
The Colormap’s values will match the range specified even if “min_val” is greater than “max_val”. To flip the order of the colors, use
reversed()
.
- to_csv(filename: str | None = None, color_scale: Number = 255) str | None
Save Colormap to a comma-separated text file or string.
The CSV data will have 4 to 5 columns for each row where each each row will contain the value (V), red (R), green (B), blue (B), and if configured alpha (A).
The values will remain in whatever range is currently set on the colormap. The colors of the colormap (assumed to be between 0 and 1) will be multiplied by 255 to produce a traditional unsigned 8-bit integer value.
- Parameters:
filename – The filename of the CSV file to save to. If not provided or None a string is returned with the contents.
color_scale – Scale colors by this factor before converting to a CSV. Colors are stored in the Colormap in a 0 to 1 range. Defaults to 255. If not equal to 1 values are converted to integers too.
- to_rgb()
Return colormap with RGB colors.
If already RGB then the same instance is returned. If an Alpha channel exists in the colormap, it is dropped.
- to_rgba()
Return colormap with RGBA colors.
If already RGBA then the same instance is returned. If not already RGBA, a completely opaque (1.0) color
- to_rio()
Convert the colormap to a rasterio colormap.
Note that rasterio requires color tables to have round integer value control points. This method assumes that the range of this Colormap is already in the desired output range and to avoid issues with rasterio will round the values and convert them to unsigned integers.
- trollimage.colormap.can_be_block_mapped(data)
Check if the array can be processed in chunks.
- trollimage.colormap.colorbar(height, length, colormap, category=False)
Return the channels of a colorbar.
- trollimage.colormap.colorize(arr, colors, values)
Colorize a monochromatic array arr, based colors given for values.
- Parameters:
arr (numpy array, numpy masked array, dask array) – Data to be mapped to the colors in the colors array using values as control points. Data can be any shape, but must represent a single (luminance) band of data (not RGB or any other colorspace).
colors (numpy array) – Colors to map the data to. Colors can be RGB or RGBA in the 0 to 1 range. The array should be in the shape (N, 3 or 4) where N is the size of the colormap (the number of colors) and the last dimension is the band dimension where each element represents Red (R), Green (G), Blue (B), and optionally Alpha (A).
values (numpy array) – Control points mapping input data values to the colors to be mapped to. Should be one dimension and the same number of elements as the
colors
array has colors (N).
- Returns: Resulting RGB/A array with the shape (3 or 4, …) where the
first dimension is 3 if the colors array was RGB and 4 if the colors array was RGBA. The remaining shape of the result matches the provided
data
input shape. Likecolors
the color values will be between 0 and 1.
- trollimage.colormap.palettebar(height, length, colormap)
Return the channels of a palettebar.
- trollimage.colormap.palettize(arr, colors, values)
Apply colors to data from start values.
- Parameters:
arr (numpy array, numpy masked array, dask array) – data to be palettized.
colors (numpy array) – the colors to use (R, G, B)
values (numpy array) – the values corresponding to the colors in the array
trollimage.colorspaces module
Color spaces using numpy to run on arrays.
trollimage.image module
The main trollimage Image class.
It overlaps largely the PIL library, but has the advantage of using masked arrays as pixel arrays, so that data arrays containing invalid values may be properly handled.
- class trollimage.image.Image(channels=None, mode='L', color_range=None, fill_value=None, palette=None, copy=True)
Bases:
object
Generic masked-array based image.
This class defines images. As such, it contains data of the different channels of the image (red, green, and blue for example). The mode tells if the channels define a black and white image (“L”), an rgb image (“RGB”), an YCbCr image (“YCbCr”), or an indexed image (“P”), in which case a palette is needed. Each mode has also a corresponding alpha mode, which is the mode with an “A” in the end: for example “RGBA” is rgb with an alpha channel. fill_value sets how the image is filled where data is missing, since channels are numpy masked arrays. Setting it to (0,0,0) in RGB mode for example will produce black where data is missing.”None” (default) will produce transparency (thus adding an alpha channel) if the file format allows it, black otherwise.
The channels are considered to contain floating point values in the range [0.0,1.0]. In order to normalize the input data, the color_range parameter defines the original range of the data. The conversion to the classical [0,255] range and byte type is done automagically when saving the image to file.
- blend(other)
Alpha blend other on top of the current image.
- clip(channels=True)
Limit the values of the array to the default [0,1] range.
channels says which channels should be clipped.
- colorize(colormap)
Colorize the current image using colormap.
Works only on”L” or “LA” images.
- convert(mode)
Convert the current image to the given mode.
See
Image
for a list of available modes.
- crude_stretch(ch_nb, min_stretch=None, max_stretch=None)
Perform simple linear stretching (without any cutoff) for a specific channel.
Channel ch_nb is the 0-based index. The image is normalized to the [0,1] range.
- enhance(inverse=False, gamma=1.0, stretch='no', stretch_parameters=None, **kwargs)
Image enhancement function.
It applies in this order inversion, gamma correction, and stretching to the current image, with parameters inverse (see
Image.invert()
), gamma (seeImage.gamma()
), and stretch (seeImage.stretch()
).
- gamma(gamma=1.0)
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.
- invert(invert=True)
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!
- is_empty()
Check for an empty image.
- merge(img)
Use provided image as a background where the current image has missing data.
- modes = ['L', 'LA', 'RGB', 'RGBA', 'YCbCr', 'YCbCrA', 'P', 'PA']
- palettize(colormap)
Palettize the current image using colormap.
Works only on”L” or “LA” images.
- pil_image()
Return a PIL image from the current image.
- pil_save(filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None)
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()
.Supported image formats are listed in https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
- putalpha(alpha)
Add an alpha channel to the current image, or replaces it with alpha if it already exists.
- replace_luminance(luminance)
Replace the Y channel of the image by the array luminance.
If the image is not in YCbCr mode, it is converted automatically to and from that mode.
- resize(shape)
Resize the image to the given shape tuple, in place.
For zooming, nearest neighbour method is used, while for shrinking, decimation is used. Therefore, shape must be a multiple or a divisor of the image shape.
- save(filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None)
Save the image to the given filename.
For some formats like jpg and png, the work is delegated to
pil_save()
, which doesn’t support the compression option.
- show()
Display the image on screen.
- 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_hist_equalize(ch_nb)
Stretch the current image’s colors by performing histogram equalization on channel ch_nb.
- stretch_linear(ch_nb, cutoffs=(0.005, 0.005))
Stretch linearly the contrast of the current image for a specific channel.
Channel ch_nb is the 0-based index. Stretching is based on cutoffs fractions for left and right trimming.
- stretch_logarithmic(ch_nb, factor=100.0)
Move data into range [1:factor] and do a normalized logarithmic enhancement.
- exception trollimage.image.UnknownImageFormat
Bases:
Exception
Exception to be raised when image format is unknown to pytroll-image.
- trollimage.image.check_image_format(fformat)
Check that fformat is valid.
Valid formats are listed in https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
- trollimage.image.ensure_dir(filename)
Check if the dir of f exists, otherwise create it.
- trollimage.image.get_pillow_image_formats()
Get mapping from file extension to PIL format plugin.
- trollimage.image.rgb2ycbcr(r__, g__, b__)
Convert the three RGB channels to YCbCr.
- trollimage.image.ycbcr2rgb(y__, cb_, cr_)
Convert the three YCbCr channels to RGB channels.
trollimage.utilities module
Simple utilities functions to handle colormaps and other use cases.
- trollimage.utilities.cmap_from_text(filename, norm=False, transparency=False, hex=False)
Convert text file colormap to Colormap object.
This takes as input a file that contains a colormap in text format composed by lines with 3 values in the range [0,255] or [00,FF] and returns a tuple of integers. If the parameters cat and tot are given, the function generates a transparency value for this color and returns a tuple of length 4. tot is the total number of colors in the colormap cat is the index of the current colour in the colormap if norm is set to True, the input values are normalized between 0 and 1.
- trollimage.utilities.pilimage2trollimage(pimage)
Convert PIL Image to trollimage Image.
trollimage.version module
- trollimage.version.get_versions()
trollimage.xrimage module
This module defines the XRImage class.
It overlaps largely with the PIL library, but has the advantage of using
DataArray
objects backed by dask arrays
as pixel arrays. This allows for invalid values to
be tracked, metadata to be assigned, and stretching to be lazy
evaluated. With the optional rasterio
library installed dask array
chunks can be saved in parallel.
- class trollimage.xrimage.XRImage(data)
Bases:
object
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.
- 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.
- blend(src)
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.
- Returns
XRImage with mode “RGBA”, blended as described above
- colorize(colormap)
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()
.- Parameters:
colormap (
Colormap
) – Colormap to be applied to the image.
Note
Works only on “L” or “LA” images.
- convert(mode)
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.
- final_mode(fill_value=None)
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 theDataArray
.attrs
dictionary.- Parameters:
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 thedtype
(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, adtype
ofnumpy.uint8
and afill_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) thenP
mode images will be converted toRGB
andPA
will be converted toRGBA
. IfTrue
, images with modeP
orPA
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 beFalse
for non-paletted images.
- gamma(gamma=None)
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.
- get_scaling_from_history(history=None)
Merge the scales and offsets from the history.
If
history
isn’t provided, the history of the current image will be used.
- invert(invert=True)
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 !
- merge(img)
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(colormap)
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”, callsave()
withkeep_palette=True
. To include color information in the output format (if supported), callsave()
withkeep_palette=True
andcmap=colormap
.To (directly) get an image in mode “RGB” or “RGBA”, use
colorize()
.- Parameters:
colormap (
Colormap
) – Colormap to be applied to the image.
Notes
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 imageDataArray
’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 anddtype_max
is 1 in the code above).
- pil_image(fill_value=None, compute=True)
Return a PIL image from the current image.
- Parameters:
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.
- Parameters:
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 Dict[str, number] 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. If set to a dictionary, automatically determined scale/offset values are overruled by the values provided in the keys.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.
- Returns:
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.
- Parameters:
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.
- Returns:
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.
- show()
Display the image on screen.
- stack(img)
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_hist_equalize(approximate=False)
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.
If the cutoffs are just a tuple or list of two scalars, all the channels except the alpha channel will be stretched with the cutoffs. If the cutoffs are a sequence of tuples/lists of two scalars then:
if there are the same number of tuples/lists as channels, each channel will be stretched with the respective cutoff.
if there is one less tuple/list as channels, the same applies, except for the alpha channel which will not be stretched.
- stretch_logarithmic(factor=100.0, base='e', min_stretch=None, max_stretch=None)
Move data into range [1:factor] through normalized logarithm.
- Parameters:
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 unperceived stimulus), and k is the factor.
- xrify_tuples(tup)
Make xarray.DataArray from tuple.
- trollimage.xrimage.combine_scales_offsets(*args)
Combine
(scale, offset)
tuples in one, considering they are applied from left to right.For example, if we have our base data called
`orig_data
and apply to it(scale_1, offset_1)
, then(scale_2, offset_2)
such that:data_1 = orig_data * scale_1 + offset_1 data_2 = data_1 * scale_2 + offset_2
this function will return the tuple
(scale, offset)
such that:data_2 = orig_data * scale + offset
given the arguments
(scale_1, offset_1), (scale_2, offset_2)
.
- trollimage.xrimage.invert_scale_offset(scale, offset)
Invert scale and offset to allow reverse transformation.
Ie, it will return
rscale, roffset
such that:orig_data = rscale * data + roffset
if:
data = scale * orig_data + offset
Module contents
The trollimage package.