hypso.rgb#

RGB images: colour-accurate renderings of hyperspectral cubes (CIE colour matching functions, Magnusson et al. 2020), and HYPSO-2’s RGB camera images.

Submodules#

Classes#

Functions#

HSI2RGB(wY, HSI[, d, threshold])

Calculate a colore accurate RGB image with HSI values. Original function used for the paper

adjust_exposure(image[, ev, percentile, target, ...])

Brighten or darken an RGB image with one gain for all channels.

black_level(rgb[, mode, percentile])

Black level(s) to subtract: the percentile of each channel

camera_filename(ds[, label])

The product's file name, e.g. HYPSO2_RGB.20250404T022723.ariake.L1A.nc

camera_gsd(geo)

Median distance (m) between neighbouring camera pixel centres.

camera_image_time(path)

Acquisition time (UTC) from a camera image's file name.

camera_lonlat(registration, shape)

Latitude and longitude (degrees, float32) of every camera pixel centre,

camera_product(camera[, registration, hsi, sat_id, target])

A camera product from a camera image, georeferenced if registered.

camera_to_hsi_pixels(registration, hsi, shape[, ...])

For every camera pixel, the nearest HSI pixel (line, sample) (-1

decorate_map(ax, extent, crs[, graticule, scale_bar, ...])

Map elements on axes in projected coordinates: latitude/longitude

demosaic_bilinear(mosaic[, pattern])

Bilinear demosaic of a Bayer mosaic.

exposure_gain(rgb[, percentile, target, full_scale])

The gain that maps the percentile of the image's luminance to

find_camera_image(capture_dir)

The RGB camera image of a capture directory, or None if it has none.

georeference_camera(camera, registration[, hsi])

The camera image in its own frame with per-pixel geolocation.

hsi_to_camera_pixels(registration, hsi, shape)

For every HSI pixel, the fractional camera (row, col) it falls on

open_camera(path)

Read a camera product written by write_camera().

plot_rgb_map(source[, ax, graticule, scale_bar, ...])

Plot a gridded RGB image as a map.

read_camera_image(path[, demosaic, rotate])

Read an RGB camera image.

register_camera(camera, hsi[, resolution, downsample, ...])

Register a camera image to an HSI capture.

regrid_camera(geo[, target, resolution, method, max_gb])

A georeferenced camera image on a map grid.

write_camera(ds[, path, out_dir, label])

Write a camera product (default name from camera_filename() in

Package Contents#

class hypso.rgb.CameraRegistration[source]#

Result of register_camera().

attrs()[source]#

The registration as NetCDF attributes (provenance).

Return type:

dict

hypso.rgb.HSI2RGB(wY, HSI, d=65, threshold=0.002)[source]#

Calculate a colore accurate RGB image with HSI values. Original function used for the paper “Creating RGB Images from Hyperspectral Images Using a Color Matching Function” by M. Magnusson, J. Sigurdsson, S. E. Armansson, M. O. Ulfarsson, H. Deborah and J. R. Sveinsson,

If you use this method, please cite the following paper: @INPROCEEDINGS{hsi2rgb, author={M. {Magnusson} and J. {Sigurdsson} and S. E. {Armansson} and M. O. {Ulfarsson} and H. {Deborah} and J. R. {Sveinsson}}, booktitle={IEEE International Geoscience and Remote Sensing Symposium}, title={Creating {RGB} Images from Hyperspectral Images using a Color Matching Function}, year={2020}, volume={}, number={}, pages={}}

Paper is available at https://www.researchgate.net/profile/Jakob_Sigurdsson

Parameters:
  • wY – Wavelengths in nm

  • HSI – Hyperspectral image, a (lines, samples, bands) array

  • d (Literal[50, 55, 65, 75]) – Determines the illuminant used, if in doubt use d65. Values of 50, 55, 65, 75

  • threshold – True if RGB thesholding should be done to increase contrast

Returns:

RGB Image array

Return type:

numpy.ndarray

hypso.rgb.adjust_exposure(image, ev=None, percentile=99.0, target=0.9, gamma=None, full_scale=255.0, normalize=False, black_point=None, black_percentile=1.0)[source]#

Brighten or darken an RGB image with one gain for all channels.

Parameters:
  • image (xarray.DataArray, xarray.Dataset or numpy.ndarray) – (y, x, channel) DataArray, a Dataset with R, G, B variables, or an array whose last axis is R, G, B.

  • ev (float, optional) – Exposure change in stops (gain 2**ev): +1 doubles, -1 halves. Default: automatic, so the percentile of the luminance lands at target of full_scale.

  • percentile (float, default 99 and 0.9) – Automatic exposure only.

  • target (float, default 99 and 0.9) – Automatic exposure only.

  • gamma (float, optional) – Display gamma applied after the gain (e.g. 2.2 lifts dark water); None keeps the result linear.

  • full_scale (float, default 255) – The value of white: 255 for the camera’s 8-bit counts, 1 for 0-1 images such as HSI2RGB output.

  • normalize (bool, default False) – Return 0-1 values instead of 0-full_scale.

  • black_point ({None, "common", "channel"} or float or 3 floats, optional) – Subtract a black level before the gain: "channel" the black_percentile of each channel (removes haze and the camera’s dark offset; usually the most natural look over water), "common" one level for all channels (keeps the colour balance), or given value(s) in the image’s units. None (default): gain only. A channel that is saturated (e.g. blue in a bright summer capture) cannot be restored, and per-channel levels then shift the colour.

  • black_percentile (float, default 1) – For "common"/"channel".

Returns:

Float32, clipped at full scale (saturated pixels stay white). Xarray results carry exposure_gain, exposure_ev, exposure_gamma and exposure_black attributes.

Return type:

Same type as image

hypso.rgb.black_level(rgb, mode='channel', percentile=1.0)[source]#

Black level(s) to subtract: the percentile of each channel ("channel": removes a colour cast such as atmospheric haze, like dark object subtraction) or its smallest value over the channels ("common": keeps the colour balance).

Parameters:
Return type:

numpy.ndarray

hypso.rgb.camera_filename(ds, label=None)[source]#

The product’s file name, e.g. HYPSO2_RGB.20250404T022723.ariake.L1A.nc (with the grid token for a hypso.rgb.regrid_camera() result).

Parameters:
Return type:

str

hypso.rgb.camera_gsd(geo)[source]#

Median distance (m) between neighbouring camera pixel centres.

Parameters:

geo (xarray.Dataset)

Return type:

float

hypso.rgb.camera_image_time(path)[source]#

Acquisition time (UTC) from a camera image’s file name.

Return type:

datetime.datetime

hypso.rgb.camera_lonlat(registration, shape)[source]#

Latitude and longitude (degrees, float32) of every camera pixel centre, (rows, cols) arrays for an image of shape.

Parameters:

registration (CameraRegistration)

Return type:

tuple

hypso.rgb.camera_product(camera, registration=None, hsi=None, sat_id='HYPSO-2', target=None)[source]#

A camera product from a camera image, georeferenced if registered.

Parameters:
Return type:

xarray.Dataset

hypso.rgb.camera_to_hsi_pixels(registration, hsi, shape, max_distance_m=None)[source]#

For every camera pixel, the nearest HSI pixel (line, sample) (-1 where it is farther than max_distance_m, default the HSI’s resolution, i.e. outside the swath). Arrays of the camera’s shape.

Parameters:
Return type:

tuple

hypso.rgb.decorate_map(ax, extent, crs, graticule=True, scale_bar=True, north_arrow=True, coastlines=False, graticule_step=None, ink='white', coast_color='yellow', water=False, water_color='#c6dbef')[source]#

Map elements on axes in projected coordinates: latitude/longitude graticule, scale bar, north arrow and Natural Earth coastlines.

Parameters:
  • ax (matplotlib.axes.Axes)

  • extent (sequence of float) – [xmin, xmax, ymin, ymax] in the CRS’s units; the axes are set to it.

  • crs (pyproj.CRS) – The axes’ projection.

  • graticule (bool) – As in plot_rgb_map().

  • scale_bar (bool) – As in plot_rgb_map().

  • north_arrow (bool) – As in plot_rgb_map().

  • coastlines (bool) – As in plot_rgb_map().

  • graticule_step (float) – As in plot_rgb_map().

  • ink (str, default "white") – Colour of lines and labels (“white” on images, “black” on a light background).

  • coast_color (str, default "yellow")

  • water (bool, default False) – Fill the sea and lakes (Natural Earth 10 m ocean and lakes) in water_color, below anything drawn at zorder >= 0 (images, data).

  • water_color (str, default "#c6dbef" (light blue))

hypso.rgb.demosaic_bilinear(mosaic, pattern=BAYER_PATTERN)[source]#

Bilinear demosaic of a Bayer mosaic.

Parameters:
  • mosaic (numpy.ndarray) – 2D raw values.

  • pattern ({"RGGB", "BGGR", "GRBG", "GBRG"}) – Colour filters of the top-left 2x2 cell, row by row.

Returns:

(rows, cols, 3) float32 R, G, B.

Return type:

numpy.ndarray

hypso.rgb.exposure_gain(rgb, percentile=99.0, target=0.9, full_scale=255.0)[source]#

The gain that maps the percentile of the image’s luminance to target of full_scale (NaN pixels ignored).

Parameters:
Return type:

float

hypso.rgb.find_camera_image(capture_dir)[source]#

The RGB camera image of a capture directory, or None if it has none.

Parameters:

capture_dir (str or pathlib.Path)

Return type:

pathlib.Path or None

hypso.rgb.georeference_camera(camera, registration, hsi=None)[source]#

The camera image in its own frame with per-pixel geolocation.

Parameters:
Returns:

R, G, B (y, x), latitude, longitude, optionally in_hsi_swath, and the registration in the attributes; writable with to_netcdf.

Return type:

xarray.Dataset

hypso.rgb.hsi_to_camera_pixels(registration, hsi, shape)[source]#

For every HSI pixel, the fractional camera (row, col) it falls on (via the inverse homography; exact for the model), NaN outside the camera image of shape. Arrays of the HSI’s spatial shape.

Parameters:

registration (CameraRegistration)

Return type:

tuple

hypso.rgb.open_camera(path)[source]#

Read a camera product written by write_camera().

Return type:

xarray.Dataset

hypso.rgb.plot_rgb_map(source, ax=None, graticule=True, scale_bar=True, north_arrow=True, coastlines=False, title=None, stretch=(2, 98), graticule_step=None, exposure=None)[source]#

Plot a gridded RGB image as a map.

Parameters:
  • source (xarray.Dataset or hypso.Product) – A gridded camera image (regrid_camera()) or a regridded product (its bands nearest 640, 550 and 460 nm).

  • ax (matplotlib.axes.Axes, optional) – Axes to draw on; default a new figure.

  • graticule (bool, default True) – Latitude/longitude lines with labels.

  • scale_bar (bool, default True) – A scale bar (km) in the lower left.

  • north_arrow (bool, default True) – An arrow to true north (in a UTM grid, true north is not straight up).

  • coastlines (bool, default False) – Natural Earth 10 m coastlines (needs cartopy and its data; skipped with a warning otherwise).

  • title (str, optional)

  • stretch (tuple of float, default (2, 98)) – Percentiles mapped to black and white per channel.

  • graticule_step (float, optional) – Degrees between graticule lines; default chosen from the extent.

  • exposure (dict, optional) – Use hypso.rgb.adjust_exposure() (one gain for all channels, colours kept) instead of the per-channel stretch, with these arguments, e.g. {} (automatic), {"ev": 1} or {"gamma": 2.2}.

Return type:

matplotlib.axes.Axes

hypso.rgb.read_camera_image(path, demosaic=True, rotate=True)[source]#

Read an RGB camera image.

Parameters:
  • path (str or pathlib.Path) – The .bmp (see find_camera_image()).

  • demosaic (bool, default True) – Bilinear RGGB demosaic to R, G, B; False returns the raw mosaic.

  • rotate (bool, default True) – Rotate 180 degrees, the orientation of the ground processing’s demosaiced image.

Returns:

(y, x, channel) float32 R, G, B in raw counts (0-255), or the (y, x) uint8 mosaic; attributes instrument (“RGB”), acquisition_time (ISO 8601, UTC), bayer_pattern, source.

Return type:

xarray.DataArray

hypso.rgb.register_camera(camera, hsi, resolution=150.0, downsample=0.25, min_inliers=30, min_coverage=0.25, max_rms_m=500.0, ratio=0.8, ransac_threshold_px=3.0, seed=0)[source]#

Register a camera image to an HSI capture.

Parameters:
  • camera (xarray.DataArray) – (y, x, channel) image from hypso.rgb.read_camera_image() (demosaiced, rotated as the ground processing does).

  • hsi (hypso.Product) – The capture’s georeferenced L1B or L1C product (needs geolocation).

  • resolution (float, default 150) – Pixel size (m) of the UTM map the camera is matched against.

  • downsample (float, default 0.25) – Scale of the camera image used for matching.

  • min_inliers (int) – Quality check: at least this many RANSAC inliers, covering at least this fraction of the camera image (convex hull), with at most this residual RMS (m).

  • min_coverage (float) – Quality check: at least this many RANSAC inliers, covering at least this fraction of the camera image (convex hull), with at most this residual RMS (m).

  • max_rms_m (float) – Quality check: at least this many RANSAC inliers, covering at least this fraction of the camera image (convex hull), with at most this residual RMS (m).

  • ratio (float, default 0.8) – Lowe’s ratio test for descriptor matching.

  • ransac_threshold_px (float, default 3) – RANSAC inlier threshold, in map pixels.

  • seed (int, default 0) – RANSAC random seed (reproducible results).

Return type:

CameraRegistration

hypso.rgb.regrid_camera(geo, target='utm', resolution=None, method='auto', max_gb=2.0)[source]#

A georeferenced camera image on a map grid.

Parameters:
  • geo (xarray.Dataset) – From hypso.rgb.georeference_camera() (R, G, B, latitude, longitude).

  • target (str, int, pyproj.CRS or pyresample.geometry.AreaDefinition, default "utm") – "utm" (zone of the image centre), any CRS, or a grid - e.g. the HSI product’s after regridding, l1c.regrid(...).area_definition(), to put both on the same grid.

  • resolution (float, optional) – Pixel size in the CRS’s units; default the camera’s own (~30 m). Not with an AreaDefinition.

  • method ({"auto", "average", "nearest"}, default "auto") – Cell means of the camera pixels in each cell, or the nearest pixel; “auto” averages when cells are at least twice the camera’s pixel size and takes the nearest pixel otherwise (averaging onto cells as small as the pixels leaves empty cells).

  • max_gb (float, default 2) – Refuse grids larger than this.

Returns:

R, G, B on (y, x) with CF projection coordinates and a crs grid mapping (NaN where the camera has no data), and the camera’s attributes plus grid.

Return type:

xarray.Dataset

hypso.rgb.write_camera(ds, path=None, out_dir=None, label=None)[source]#

Write a camera product (default name from camera_filename() in out_dir). Channels uint8, geolocation float32, zlib level 4.

Parameters:
Return type:

pathlib.Path