| 1 | import warnings |
| 2 | |
| 3 | import numpy as np |
| 4 | |
| 5 | |
| 6 | def normalize(src, min_value=None, max_value=None, return_minmax=False): |
| 7 | """Normalize image. |
| 8 | |
| 9 | Parameters |
| 10 | ---------- |
| 11 | src: numpy.ndarray, (H, W) or (H, W, C), float |
| 12 | Input image. |
| 13 | min_value: float |
| 14 | Minimum value. |
| 15 | max_value: float |
| 16 | Maximum value. |
| 17 | return_minmax: bool |
| 18 | Flag to return min_value and max_value. |
| 19 | |
| 20 | Returns |
| 21 | ------- |
| 22 | dst: numpy.ndarray, float |
| 23 | Normalized image in [0, 1]. |
| 24 | |
| 25 | """ |
| 26 | if src.ndim == 2: |
| 27 | D = 1 |
| 28 | else: |
| 29 | assert src.ndim == 3, "src ndim must be 2 or 3" |
| 30 | D = src.shape[2] |
| 31 | |
| 32 | if min_value is None: |
| 33 | min_value = np.nanmin(src, axis=(0, 1)) |
| 34 | min_value = np.atleast_1d(min_value).astype(float) |
| 35 | assert min_value.shape == (D,) |
| 36 | |
| 37 | if max_value is None: |
| 38 | max_value = np.nanmax(src, axis=(0, 1)) |
| 39 | max_value = np.atleast_1d(max_value).astype(float) |
| 40 | assert max_value.shape == (D,) |
| 41 | |
| 42 | if np.isinf(min_value).any() or np.isinf(max_value).any(): |
| 43 | warnings.warn("some of min or max values are inf.") |
| 44 | |
| 45 | eps = np.finfo(src.dtype).eps |
| 46 | issame = max_value == min_value |
| 47 | min_value[issame] -= eps |
| 48 | max_value[issame] += eps |
| 49 | |
| 50 | dst = np.zeros(src.shape, dtype=float) |
| 51 | |
| 52 | if src.ndim == 2: |
| 53 | isnan = np.isnan(src) |
| 54 | else: |
| 55 | isnan = np.isnan(src).any(axis=2) |
| 56 | dst[~isnan] = 1.0 * (src[~isnan] - min_value) / (max_value - min_value) |
| 57 | dst[isnan] = np.nan |
| 58 | |
| 59 | if return_minmax: |
| 60 | return dst, min_value, max_value |
| 61 | else: |
| 62 | return dst |