micro_sam.v2.normalization
Common normalization for SAM2 raw microscopy inputs.
1"""Common normalization for SAM2 raw microscopy inputs.""" 2 3from typing import Optional, Tuple, Union 4 5import numpy as np 6 7# Persist the preprocessing (normalization + resize) policy in embedding caches so incompatible 8# features are not silently reused. Both image and video paths use the per-channel percentile 9# normalization used in training. Images are quantized to uint8 for the image predictor; videos 10# stay float32 and use whole-volume percentile bounds. 11IMAGE_PREPROCESSING = "percentile_2_98_per_channel_uint8_v2" 12# v2 stores one shared positional encoding per volume / tile instead of one per slice. v3 computes 13# the percentiles once over the whole volume instead of once per slice or tile crop. 14VIDEO_PREPROCESSING = "percentile_2_98_per_channel_torch_resize_v3" 15 16 17def compute_percentile_bounds( 18 raw: np.ndarray, 19 lower_percentile: float = 2.0, 20 upper_percentile: float = 98.0, 21 axis: Optional[Union[int, Tuple[int, ...]]] = None, 22) -> Tuple[np.ndarray, np.ndarray]: 23 """The (lower, upper) percentile values that `normalize_raw` maps to 0 and 1. 24 25 Compute this once over a whole volume and pass it to every slice or tile the volume is later 26 split into (via `normalize_raw`'s `bounds` argument), so they all share one normalization 27 instead of each one estimating its own percentiles from a smaller, biased sample. 28 29 Args: 30 raw: The input data. 31 lower_percentile: The percentile that is mapped to 0. 32 upper_percentile: The percentile that is mapped to 1. 33 axis: The axis or axes to compute the percentiles over. By default they are computed over the 34 full data. Pass the spatial axes to normalize each channel independently. 35 36 Returns: 37 The (lower, upper) percentile values, each with `axis` reduced to size 1. 38 """ 39 # float32 throughout, matching 'normalize_raw's contract - a boolean 'raw' otherwise crashes 40 # inside numpy's percentile interpolation, which subtracts two boolean values. 41 raw = np.asarray(raw, dtype="float32") 42 v_lower = np.percentile(raw, lower_percentile, axis=axis, keepdims=True) 43 v_upper = np.percentile(raw, upper_percentile, axis=axis, keepdims=True) 44 return v_lower, v_upper 45 46 47def normalize_raw( 48 raw: np.ndarray, 49 axis: Optional[Union[int, Tuple[int, ...]]] = None, 50 output_dtype: Union[str, np.dtype] = "float32", 51 lower_percentile: float = 2.0, 52 upper_percentile: float = 98.0, 53 bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 54 eps: float = 1e-7, 55) -> np.ndarray: 56 """Percentile-normalize raw image data to the value range of the output dtype. 57 58 The lower and upper percentiles are mapped to the bounds of the output range and values outside of 59 them are clipped. The output range is derived from the output dtype: [0, 1] for floating dtypes and 60 the full representable range for integer dtypes. The data is normalized in float32 regardless of its 61 input dtype and is only cast to the output dtype afterwards. 62 63 Args: 64 raw: The raw image data. May be of any floating or integer dtype. 65 axis: The axis or axes to compute the percentiles over. Ignored if `bounds` is given. By 66 default they are computed over the full data. Pass the spatial axes to normalize each 67 channel independently. 68 output_dtype: The dtype of the returned data. Must be a floating or an 8- or 16-bit integer dtype. 69 Floating dtypes are normalized to [0, 1], integer dtypes to their full representable range. 70 lower_percentile: The percentile that is mapped to the lower bound of the output range. 71 upper_percentile: The percentile that is mapped to the upper bound of the output range. 72 bounds: Precomputed (lower, upper) percentile values, e.g. from `compute_percentile_bounds` 73 run on a whole volume. Skips computing percentiles from `raw` itself when given. 74 eps: Added to the percentile range to keep constant input from dividing by zero. 75 76 Returns: 77 The normalized image data in the output dtype. 78 79 Raises: 80 ValueError: If the output dtype is neither a floating nor an 8- or 16-bit integer dtype. 81 """ 82 output_dtype = np.dtype(output_dtype) 83 is_small_int = np.issubdtype(output_dtype, np.integer) and output_dtype.itemsize <= 2 # 8- or 16-bit integers 84 if not (np.issubdtype(output_dtype, np.floating) or is_small_int): 85 raise ValueError( 86 f"Invalid output dtype '{output_dtype}'. Expect a floating dtype or an 8- or 16-bit integer dtype." 87 ) 88 89 raw = np.asarray(raw) 90 if raw.size == 0: 91 return raw.astype(output_dtype, copy=False) 92 93 v_lower, v_upper = bounds if bounds is not None else compute_percentile_bounds( 94 raw, lower_percentile, upper_percentile, axis=axis, 95 ) 96 normalized = (raw.astype("float32") - v_lower) / (v_upper - v_lower + eps) 97 normalized = np.clip(normalized, 0.0, 1.0) 98 99 # Integer dtypes are mapped to their full range. Round so that the cast does not bias values downwards. 100 if is_small_int: 101 info = np.iinfo(output_dtype) 102 normalized = np.round(normalized * (float(info.max) - float(info.min)) + float(info.min)) 103 104 return normalized.astype(output_dtype, copy=False) 105 106 107def to_image(image: np.ndarray) -> np.ndarray: 108 """Map a 2D or channel-last image to percentile-normalized, channel-last uint8 RGB. 109 110 Match the training normalization: map each channel's 2nd and 98th percentiles to 0 and 255, 111 clipping intensities outside that range. This applies to both whole images and image tiles. 112 113 Args: 114 image: The input image. Either 2D or channel-last with up to three channels. 115 116 Returns: 117 The channel-last uint8 RGB image, with each channel normalized independently. 118 """ 119 from micro_sam.util import _ensure_rgb 120 return normalize_raw(_ensure_rgb(image), axis=(0, 1), output_dtype="uint8")
18def compute_percentile_bounds( 19 raw: np.ndarray, 20 lower_percentile: float = 2.0, 21 upper_percentile: float = 98.0, 22 axis: Optional[Union[int, Tuple[int, ...]]] = None, 23) -> Tuple[np.ndarray, np.ndarray]: 24 """The (lower, upper) percentile values that `normalize_raw` maps to 0 and 1. 25 26 Compute this once over a whole volume and pass it to every slice or tile the volume is later 27 split into (via `normalize_raw`'s `bounds` argument), so they all share one normalization 28 instead of each one estimating its own percentiles from a smaller, biased sample. 29 30 Args: 31 raw: The input data. 32 lower_percentile: The percentile that is mapped to 0. 33 upper_percentile: The percentile that is mapped to 1. 34 axis: The axis or axes to compute the percentiles over. By default they are computed over the 35 full data. Pass the spatial axes to normalize each channel independently. 36 37 Returns: 38 The (lower, upper) percentile values, each with `axis` reduced to size 1. 39 """ 40 # float32 throughout, matching 'normalize_raw's contract - a boolean 'raw' otherwise crashes 41 # inside numpy's percentile interpolation, which subtracts two boolean values. 42 raw = np.asarray(raw, dtype="float32") 43 v_lower = np.percentile(raw, lower_percentile, axis=axis, keepdims=True) 44 v_upper = np.percentile(raw, upper_percentile, axis=axis, keepdims=True) 45 return v_lower, v_upper
The (lower, upper) percentile values that normalize_raw maps to 0 and 1.
Compute this once over a whole volume and pass it to every slice or tile the volume is later
split into (via normalize_raw's bounds argument), so they all share one normalization
instead of each one estimating its own percentiles from a smaller, biased sample.
Arguments:
- raw: The input data.
- lower_percentile: The percentile that is mapped to 0.
- upper_percentile: The percentile that is mapped to 1.
- axis: The axis or axes to compute the percentiles over. By default they are computed over the full data. Pass the spatial axes to normalize each channel independently.
Returns:
The (lower, upper) percentile values, each with
axisreduced to size 1.
48def normalize_raw( 49 raw: np.ndarray, 50 axis: Optional[Union[int, Tuple[int, ...]]] = None, 51 output_dtype: Union[str, np.dtype] = "float32", 52 lower_percentile: float = 2.0, 53 upper_percentile: float = 98.0, 54 bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 55 eps: float = 1e-7, 56) -> np.ndarray: 57 """Percentile-normalize raw image data to the value range of the output dtype. 58 59 The lower and upper percentiles are mapped to the bounds of the output range and values outside of 60 them are clipped. The output range is derived from the output dtype: [0, 1] for floating dtypes and 61 the full representable range for integer dtypes. The data is normalized in float32 regardless of its 62 input dtype and is only cast to the output dtype afterwards. 63 64 Args: 65 raw: The raw image data. May be of any floating or integer dtype. 66 axis: The axis or axes to compute the percentiles over. Ignored if `bounds` is given. By 67 default they are computed over the full data. Pass the spatial axes to normalize each 68 channel independently. 69 output_dtype: The dtype of the returned data. Must be a floating or an 8- or 16-bit integer dtype. 70 Floating dtypes are normalized to [0, 1], integer dtypes to their full representable range. 71 lower_percentile: The percentile that is mapped to the lower bound of the output range. 72 upper_percentile: The percentile that is mapped to the upper bound of the output range. 73 bounds: Precomputed (lower, upper) percentile values, e.g. from `compute_percentile_bounds` 74 run on a whole volume. Skips computing percentiles from `raw` itself when given. 75 eps: Added to the percentile range to keep constant input from dividing by zero. 76 77 Returns: 78 The normalized image data in the output dtype. 79 80 Raises: 81 ValueError: If the output dtype is neither a floating nor an 8- or 16-bit integer dtype. 82 """ 83 output_dtype = np.dtype(output_dtype) 84 is_small_int = np.issubdtype(output_dtype, np.integer) and output_dtype.itemsize <= 2 # 8- or 16-bit integers 85 if not (np.issubdtype(output_dtype, np.floating) or is_small_int): 86 raise ValueError( 87 f"Invalid output dtype '{output_dtype}'. Expect a floating dtype or an 8- or 16-bit integer dtype." 88 ) 89 90 raw = np.asarray(raw) 91 if raw.size == 0: 92 return raw.astype(output_dtype, copy=False) 93 94 v_lower, v_upper = bounds if bounds is not None else compute_percentile_bounds( 95 raw, lower_percentile, upper_percentile, axis=axis, 96 ) 97 normalized = (raw.astype("float32") - v_lower) / (v_upper - v_lower + eps) 98 normalized = np.clip(normalized, 0.0, 1.0) 99 100 # Integer dtypes are mapped to their full range. Round so that the cast does not bias values downwards. 101 if is_small_int: 102 info = np.iinfo(output_dtype) 103 normalized = np.round(normalized * (float(info.max) - float(info.min)) + float(info.min)) 104 105 return normalized.astype(output_dtype, copy=False)
Percentile-normalize raw image data to the value range of the output dtype.
The lower and upper percentiles are mapped to the bounds of the output range and values outside of them are clipped. The output range is derived from the output dtype: [0, 1] for floating dtypes and the full representable range for integer dtypes. The data is normalized in float32 regardless of its input dtype and is only cast to the output dtype afterwards.
Arguments:
- raw: The raw image data. May be of any floating or integer dtype.
- axis: The axis or axes to compute the percentiles over. Ignored if
boundsis given. By default they are computed over the full data. Pass the spatial axes to normalize each channel independently. - output_dtype: The dtype of the returned data. Must be a floating or an 8- or 16-bit integer dtype. Floating dtypes are normalized to [0, 1], integer dtypes to their full representable range.
- lower_percentile: The percentile that is mapped to the lower bound of the output range.
- upper_percentile: The percentile that is mapped to the upper bound of the output range.
- bounds: Precomputed (lower, upper) percentile values, e.g. from
compute_percentile_boundsrun on a whole volume. Skips computing percentiles fromrawitself when given. - eps: Added to the percentile range to keep constant input from dividing by zero.
Returns:
The normalized image data in the output dtype.
Raises:
- ValueError: If the output dtype is neither a floating nor an 8- or 16-bit integer dtype.
108def to_image(image: np.ndarray) -> np.ndarray: 109 """Map a 2D or channel-last image to percentile-normalized, channel-last uint8 RGB. 110 111 Match the training normalization: map each channel's 2nd and 98th percentiles to 0 and 255, 112 clipping intensities outside that range. This applies to both whole images and image tiles. 113 114 Args: 115 image: The input image. Either 2D or channel-last with up to three channels. 116 117 Returns: 118 The channel-last uint8 RGB image, with each channel normalized independently. 119 """ 120 from micro_sam.util import _ensure_rgb 121 return normalize_raw(_ensure_rgb(image), axis=(0, 1), output_dtype="uint8")
Map a 2D or channel-last image to percentile-normalized, channel-last uint8 RGB.
Match the training normalization: map each channel's 2nd and 98th percentiles to 0 and 255, clipping intensities outside that range. This applies to both whole images and image tiles.
Arguments:
- image: The input image. Either 2D or channel-last with up to three channels.
Returns:
The channel-last uint8 RGB image, with each channel normalized independently.