zea.metrics

Metrics for ultrasound images.

Functions

cnr(x, y)

Calculate contrast to noise ratio

contrast(x, y)

Contrast ratio

fwhm(img)

Resolution full width half maxima

gcnr(x, y[, bins])

Generalized contrast-to-noise-ratio

get_lpips(image_range[, clip])

Get the Learned Perceptual Image Patch Similarity (LPIPS) metric.

get_metric(name, **kwargs)

Get metric function given name.

mae(y_true, y_pred)

Gives the MAE for two input tensors.

mse(y_true, y_pred)

Gives the MSE for two input tensors.

ncc(x, y)

Normalized cross correlation

psnr(y_true, y_pred, *[, max_val])

Peak Signal to Noise Ratio (PSNR) for two input tensors.

snr(img)

Signal to noise ratio

ssim(a, b, *[, max_val, filter_size, ...])

Computes the structural similarity index (SSIM) between image pairs.

wopt_mae(ref, img)

Find the optimal weight that minimizes the mean absolute error

wopt_mse(ref, img)

Find the optimal weight that minimizes the mean squared error

Classes

Metrics(metrics, image_range[, quantize, ...])

Class for calculating multiple paired metrics.

class zea.metrics.Metrics(metrics, image_range, quantize=False, clip=False, jit_compile=True, **kwargs)[source]

Bases: object

Class for calculating multiple paired metrics. Also useful for batch processing.

Will preprocess images by translating to [0, 255], clipping, and quantizing to uint8 if specified.

Example

>>> from zea import metrics
>>> import numpy as np

>>> metrics = metrics.Metrics(["psnr", "lpips"], image_range=[0, 255])
>>> y_true = np.random.rand(4, 128, 128, 1)
>>> y_pred = np.random.rand(4, 128, 128, 1)
>>> result = metrics(y_true, y_pred)
>>> result = {k: float(v) for k, v in result.items()}
>>> print(result)
{'psnr': ..., 'lpips': ...}

Initialize the Metrics class.

Parameters:
  • metrics (List[str]) – List of metric names to calculate.

  • image_range (tuple) – The range of the images. Used for metrics like PSNR and LPIPS.

  • quantize (bool) – Whether to quantize the images to uint8 before calculating metrics.

  • clip (bool) – Whether to clip the images to image_range before calculating metrics.

  • kwargs – Additional keyword arguments to pass to the metric functions.

__call__(y_true, y_pred, average_batches=True, mapped_batch_size=None, return_numpy=True, device=None)[source]

Calculate all metrics and return as a dictionary. Assumes input shape (…, h, w, c), i.e. images of shape (h, w, c) with any number of leading batch dimensions. The metrics will be calculated on these 2d images and mapped across all leading batch dimensions.

Parameters:
  • y_true (tensor) – Ground truth images with shape (…, h, w, c)

  • y_pred (tensor) – Predicted images with shape (…, h, w, c)

  • average_batches (bool) – Whether to average the metrics over the batch dimensions.

  • mapped_batch_size (optional int) – The batch size to use for computing metric values in parallel. You may want to decrease this if you run into memory issues, e.g. with LPIPS.

  • return_numpy (bool) – Whether to return the metrics as numpy arrays. If False, will return as tensors.

  • device (str) – The device to run the metric calculations on. If None, will use the default device.

zea.metrics.cnr(x, y)[source]

Calculate contrast to noise ratio

zea.metrics.contrast(x, y)[source]

Contrast ratio

zea.metrics.fwhm(img)[source]

Resolution full width half maxima

zea.metrics.gcnr(x, y, bins=256)[source]

Generalized contrast-to-noise-ratio

zea.metrics.get_lpips(image_range, clip=False)[source]

Get the Learned Perceptual Image Patch Similarity (LPIPS) metric.

Parameters:
  • image_range (list) – The range of the images. Will be translated to [-1, 1] for LPIPS.

  • clip (bool) – Whether to clip the images to image_range.

Returns:

The LPIPS metric function.

zea.metrics.get_metric(name, **kwargs)[source]

Get metric function given name.

zea.metrics.mae(y_true, y_pred)[source]

Gives the MAE for two input tensors.

Parameters:
  • y_true (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

  • y_pred (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

Returns:

mean absolute error between y_true and y_pred. L1 loss.

Return type:

(float)

zea.metrics.mse(y_true, y_pred)[source]

Gives the MSE for two input tensors.

Parameters:
  • y_true (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

  • y_pred (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

Returns:

mean squared error between y_true and y_pred. L2 loss.

Return type:

(float)

zea.metrics.ncc(x, y)[source]

Normalized cross correlation

zea.metrics.psnr(y_true, y_pred, *, max_val=255)[source]

Peak Signal to Noise Ratio (PSNR) for two input tensors.

PSNR = 20 * log10(max_val) - 10 * log10(mean(square(y_true - y_pred)))

Parameters:
  • y_true (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

  • y_pred (tensor) – input tensor of shape (height, width, channels) with optional batch dimension.

  • max_val – The dynamic range of the images

Returns:

PSNR score for each image in the batch.

Return type:

Tensor (float)

zea.metrics.snr(img)[source]

Signal to noise ratio

zea.metrics.ssim(a, b, *, max_val=255.0, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, return_map=False, filter_fn=None)[source]

Computes the structural similarity index (SSIM) between image pairs.

This function is based on the standard SSIM implementation from: Z. Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli, “Image quality assessment: from error visibility to structural similarity”, in IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, 2004.

This function copied from [dm_pix.ssim](https://dm-pix.readthedocs.io/en/latest/api.html#dm_pix.ssim), which is part of the DeepMind’s dm_pix library. They modeled their implementation after the tf.image.ssim function.

Note: the true SSIM is only defined on grayscale. This function does not perform any colorspace transform. If the input is in a color space, then it will compute the average SSIM.

Parameters:
  • a – First image (or set of images).

  • b – Second image (or set of images).

  • max_val (float) – The maximum magnitude that a or b can have.

  • filter_size (int) – Window size (>= 1). Image dims must be at least this small.

  • filter_sigma (float) – The bandwidth of the Gaussian used for filtering (> 0.).

  • k1 (float) – One of the SSIM dampening parameters (> 0.).

  • k2 (float) – One of the SSIM dampening parameters (> 0.).

  • return_map (bool) – If True, will cause the per-pixel SSIM “map” to be returned.

  • filter_fn – An optional argument for overriding the filter function used by SSIM, which would otherwise be a 2D Gaussian blur specified by filter_size and filter_sigma.

Returns:

Each image’s mean SSIM, or a tensor of individual values if return_map.

zea.metrics.wopt_mae(ref, img)[source]

Find the optimal weight that minimizes the mean absolute error

zea.metrics.wopt_mse(ref, img)[source]

Find the optimal weight that minimizes the mean squared error