diff --git a/src/machinevisiontoolbox/ImageColor.py b/src/machinevisiontoolbox/ImageColor.py index 1b1804ea..d3494669 100644 --- a/src/machinevisiontoolbox/ImageColor.py +++ b/src/machinevisiontoolbox/ImageColor.py @@ -293,7 +293,9 @@ def kmeans_color( else: raise ValueError("must specify either k or centroids") - def colorspace(self, dst: str, src: str | None = None) -> Self: + def colorspace( + self, dst: str, src: str | None = None, dtype: Any = None + ) -> Self: """ Transform a color image between color representations @@ -301,6 +303,9 @@ def colorspace(self, dst: str, src: str | None = None) -> Self: :type dst: str :param src: source color space (see below), defaults to colororder of image :type src: str, optional + :param dtype: data type of the result, defaults to the type of this image + :type dtype: str or NumPy dtype, optional + :raises ValueError: integer data in, or asked for in, a color space with natural units :return: color image in new colorspace :rtype: :class:`Image` @@ -330,6 +335,20 @@ def colorspace(self, dst: str, src: str | None = None) -> Self: .. note:: RGB images are assumed to be linear, or gamma decoded. + .. note:: + - Integer images span 0 to the maximum value of their type, and float + images span 0 to 1. This holds for the RGB, BGR, grey and YCrCb + color spaces. + - HSV, HLS, CIE XYZ, L*a*b* and L*u*v* are always floating point and have + their natural units: hue is in degrees, L* is 0 to 100, and a* and b* + can be negative. An integer image converted to one of these has type + float32. An integer type cannot be the source or destination. + + .. versionchanged:: 2.5.0 + Added the ``dtype`` argument. The result has the type of the image, as + before, except as noted above. Previously an 8-bit image converted to + HSV, L*a*b* or XYZ had OpenCV's 8-bit encoding of those spaces. + :references: - |RVC3|, Section 10.2.7, 10.4.1. @@ -354,15 +373,19 @@ def colorspace(self, dst: str, src: str | None = None) -> Self: # print('converting from', src, 'to', dst) - out = color.colorspace_convert(self._A, src, dst) + out = color.colorspace_convert(self._A, src, dst, dtype=dtype) # print('conversion done') if out.ndim > 2: - colororder = dst - colororder = colororder.replace("*", "*:", 2) + # the multi-character plane names need colons to separate them + colororder = {"ycrcb": "Y:Cr:Cb", "xyz_709": "X:Y:Z"}.get( + dst.lower(), dst.replace("*", "*:", 2) + ) else: colororder = None - return self.__class__(out, dtype=self.dtype, colororder=colororder) + # dtype=True keeps the type that colorspace_convert gave, which is not + # always the type that the Image constructor would choose + return self.__class__(out, colororder=colororder, dtype=True) @classmethod def Overlay(cls, im1: Image, im2: Image, colors: str = "rc") -> Self: diff --git a/src/machinevisiontoolbox/base/color.py b/src/machinevisiontoolbox/base/color.py index 39d206c3..fb4d8f4b 100755 --- a/src/machinevisiontoolbox/base/color.py +++ b/src/machinevisiontoolbox/base/color.py @@ -21,7 +21,7 @@ # import io as io from machinevisiontoolbox.base.data import mvtb_path_to_datafile -from machinevisiontoolbox.base.types import float_image, int_image +from machinevisiontoolbox.base.types import DTYPE_ALIASES, float_image, int_image # TODO # need to remove references to image class here @@ -1293,7 +1293,58 @@ def cie_primaries() -> np.ndarray: # ------------------------------------------------------------------------- # -def colorspace_convert(image: ArrayLike, src: str, dst: str) -> np.ndarray: +# ------------------------------------------------------------------------- # +# dtype handling shared by colorspace_convert, gamma_encode and gamma_decode +# +# Image-like data is either an integer type (uint8 or uint16), spanning 0 to the +# maximum value of the type, or a float type, spanning 0 to 1. + +_INTEGER_IMAGE_TYPES = (np.uint8, np.uint16) + + +def _resolve_dtype(dtype: Any) -> np.dtype: + """Resolve a dtype argument, including the Toolbox aliases such as "float".""" + if isinstance(dtype, str): + dtype = DTYPE_ALIASES.get(dtype, dtype) + dtype = np.dtype(dtype) + if np.issubdtype(dtype, np.integer) and dtype.type not in _INTEGER_IMAGE_TYPES: + raise ValueError(f"integer image data must be uint8 or uint16, not {dtype}") + if not (np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.floating)): + raise ValueError(f"unsupported data type {dtype}") + return dtype + + +def _to_float(image: np.ndarray) -> np.ndarray: + """Float version of image data: 0 to 1 for integers, float32 or float64. + + Floating point data keeps its precision, except float16 which is widened. + """ + if image.dtype == np.float64: + return image + if np.issubdtype(image.dtype, np.integer) and image.dtype.type not in _INTEGER_IMAGE_TYPES: + raise ValueError(f"integer image data must be uint8 or uint16, not {image.dtype}") + return float_image(image, "float32") + + +def _from_float(x: np.ndarray, dtype: np.dtype) -> np.ndarray: + """Convert float image data to ``dtype``, scaling and clipping if it is an integer.""" + if np.issubdtype(dtype, np.floating): + return x.astype(dtype) + return int_image(np.clip(x, 0, 1), dtype) + + +# colorspaces whose values have natural units, not a 0 to 1 range: hue in degrees, L* from +# 0 to 100, a* and b* that can be negative, and so on. They are floating point only. +_NATURAL_UNIT_SPACES = ("hsv", "hls", "lab", "l*a*b*", "luv", "l*u*v*", "xyz", "xyz_709") + + +def _space_name(name: str) -> str: + return name.replace(":", "").lower() + + +def colorspace_convert( + image: ArrayLike, src: str, dst: str, dtype: Any = None +) -> np.ndarray: """ Convert images between colorspaces @@ -1303,8 +1354,11 @@ def colorspace_convert(image: ArrayLike, src: str, dst: str) -> np.ndarray: :type src: str :param dst: output colorspace name :type dst: str + :param dtype: output data type, defaults to the type of ``image`` + :type dtype: str or NumPy dtype, optional + :raises ValueError: integer data in, or asked for in, a colorspace with natural units :return: output image - :rtype: ndarray(N,M,3), (N,3) + :rtype: ndarray(N,M,3), (N,3), (3,) Convert images or rowwise color coordinates from one color space to another. The work is done by OpenCV and assumes that the input image is linear, not @@ -1334,27 +1388,83 @@ def colorspace_convert(image: ArrayLike, src: str, dst: str) -> np.ndarray: >>> colorspace_convert([0, 0, 1], 'rgb', 'hls') .. note:: + * Integer data (``uint8`` or ``uint16``) in the RGB, BGR, grey and YCrCb color + spaces spans 0 to the maximum value of its type, and float data spans 0 to 1. + The result has the type of ``image`` unless ``dtype`` is given, which converts + and scales it. + * HSV, HLS, XYZ, L*a*b* and L*u*v* are always floating point, in their natural + units: hue is in degrees, L* is 0 to 100, and a* and b* can be negative. An + integer image converted to one of these gives float32, and an integer type + cannot be the source or destination (``ValueError``). + * A list or tuple of numbers is floating point. * Color space names 'grey' and 'gray' are synonyms, as are 'xyz' and 'xyz_709', 'lab' and 'l*a*b*', and 'luv' and 'l*u*v*'. * Colons within the color space names, as returned by :meth:`~machinevisiontoolbox.Image.colororder_str`, are ignored, so 'rgb' and 'r:g:b' are treated as the same color space. * Case is ignored in color space names, so 'RGB' and 'rgb' are treated as the same color space. + .. versionchanged:: 2.5.0 + Added the ``dtype`` argument. Integer values in a 3-vector or Nx3 array are now + scaled to 0 to 1, where before they were treated as floats. An 8-bit image + converted to HSV, XYZ or L*a*b* used to have OpenCV's 8-bit encoding of those + spaces, and now gives float32 in natural units. ``float64`` and ``uint16`` + images are accepted for every conversion. + :seealso: :func:`gamma_decode` `cv2.cvtColor `_ """ operation = _convertflag(src, dst) + src_natural = _space_name(src) in _NATURAL_UNIT_SPACES + dst_natural = _space_name(dst) in _NATURAL_UNIT_SPACES - if isinstance(image, np.ndarray) and image.ndim == 3: - # its a color image - return cv2.cvtColor(image, code=operation) + if isinstance(image, np.ndarray): + arr = image else: - # not an image, see if it's Nx3 - image = smb.getmatrix(image, (None, 3), dtype=np.float32) - image = image.reshape((-1, 1, 3)) # type: ignore[union-attr] - converted = cv2.cvtColor(image, code=operation) - if converted.shape[0] == 1: - return converted.flatten().astype(np.float64) - else: - return converted.reshape((-1, 3)).astype(np.float64) + # a list or tuple of numbers is floating point + arr = np.asarray(image, dtype=np.float64) + is_int = np.issubdtype(arr.dtype, np.integer) + if src_natural and is_int: + raise ValueError( + f"{src} data has natural units (for example hue in degrees) so it must be " + "floating point, not an integer type" + ) + + # the output type: that of the input, but an integer input gives float32 in a + # colorspace with natural units since it cannot be represented as an integer + if dtype is not None: + out_dtype = _resolve_dtype(dtype) + elif dst_natural and is_int: + out_dtype = np.dtype(np.float32) + elif arr.dtype == np.float16 or arr.dtype == np.bool_: + out_dtype = np.dtype(np.float32) + else: + out_dtype = _resolve_dtype(arr.dtype) + if dst_natural and np.issubdtype(out_dtype, np.integer): + raise ValueError( + f"{dst} data has natural units (for example hue in degrees) so it must be " + "floating point, not an integer type" + ) + + # OpenCV works here on float32 data, which handles every conversion and type + if arr.ndim == 3: + shaped = arr + elif arr.ndim == 1 and arr.shape[0] == 3: + shaped = arr.reshape(1, 1, 3) + elif arr.ndim == 2 and arr.shape[1] == 3: + shaped = arr.reshape(-1, 1, 3) + else: + raise ValueError("expecting an image or an Nx3 array of color coordinates") + f32 = np.ascontiguousarray(_to_float(shaped), dtype=np.float32) + converted = cv2.cvtColor(f32, code=operation) + + # restore the shape of the input + nplanes = converted.shape[2] if converted.ndim == 3 else 1 + if arr.ndim == 1: + converted = converted.reshape(nplanes) + elif arr.ndim == 2: + converted = converted.reshape(-1, nplanes) if nplanes > 1 else converted.reshape(-1) + + if dst_natural: + return converted.astype(out_dtype) + return _from_float(converted, out_dtype) def _convertflag(src: str, dst: str) -> int: @@ -1362,7 +1472,9 @@ def _convertflag(src: str, dst: str) -> int: dst = dst.replace(":", "").lower() if src == "rgb": - if dst in ("grey", "gray"): + if dst == "bgr": + return cv2.COLOR_RGB2BGR + elif dst in ("grey", "gray"): return cv2.COLOR_RGB2GRAY elif dst in ("xyz", "xyz_709"): return cv2.COLOR_RGB2XYZ @@ -1379,7 +1491,9 @@ def _convertflag(src: str, dst: str) -> int: else: raise ValueError(f"destination colorspace {dst} not known") elif src == "bgr": - if dst in ("grey", "gray"): + if dst == "rgb": + return cv2.COLOR_BGR2RGB + elif dst in ("grey", "gray"): return cv2.COLOR_BGR2GRAY elif dst in ("xyz", "xyz_709"): return cv2.COLOR_BGR2XYZ @@ -1436,7 +1550,9 @@ def _convertflag(src: str, dst: str) -> int: # ------------------------------------------------------------------------- # -def gamma_encode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: +def gamma_encode( + image: np.ndarray, gamma: float | str = "sRGB", dtype: Any = None +) -> np.ndarray: r""" Gamma encoding @@ -1444,8 +1560,10 @@ def gamma_encode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: :type image: ndarray(H,W), ndarray(H,W,N) :param gamma: gamma exponent or "srgb" :type gamma: float, str + :param dtype: data type of the result, defaults to the type of ``image`` + :type dtype: str or NumPy dtype, optional :return: gamma encoded version of image - :rtype: ndarray(H,W), ndarray(H,W,N) + :rtype: ndarray(N), ndarray(H,W), ndarray(H,W,N) Maps linear tristimulus values to a gamma encoded values using either: @@ -1461,56 +1579,41 @@ def gamma_encode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: :math:`\gamma=0.45`. - For images with multiple planes, the gamma encoding is applied to each plane. - - For images of type double, the pixels are assumed to be in the - range 0 to 1. - - For images of type int, the pixels are assumed in the range 0 to - the maximum value of their class. Pixels are converted first to - double, encoded, then converted back to the integer class. + - The array can have any number of dimensions, including a 1D array of + values. + - Integer data (``uint8`` or ``uint16``) is assumed to span 0 to the maximum + value of its type, and float data to span 0 to 1. The result has the same + type as the input unless ``dtype`` is given, which converts and scales it. + Integer results are rounded and clipped to their range. :references: - |RVC3|, Section 10.1. + .. versionchanged:: 2.5.0 + Added the ``dtype`` argument. The result now has the type of the input, + where an integer image gave float32 or ``uint8``. A 1D array is now + accepted with the sRGB mapping. + :seealso: :func:`gamma_decode` :func:`colorspace_convert` """ if not isinstance(gamma, (int, float, str)): raise ValueError("gamma must be string or scalar") - - if isinstance(gamma, str) and gamma.lower() == "srgb": - imagef = float_image(image) - - if imagef.ndim == 2: - # greyscale - return _srgb(imagef) - elif imagef.ndim == 3: - # multi-dimensional - out = np.empty(imagef.shape, dtype=imagef.dtype) - for p in range(imagef.ndim): - out[:, :, p] = _srgb(imagef[:, :, p]) - else: - raise ValueError("expecting 2d or 3d image") - - if np.issubdtype(image.dtype, np.integer): - # original image was float, convert back - return int_image(out) - else: - return out - - elif isinstance(gamma, (int, float)): - # normal power law: - # import code - # code.interact(local=dict(globals(), **locals())) - if np.issubdtype(image.dtype, np.floating): - return image**gamma - else: - # int image - maxg = np.float32((np.iinfo(image.dtype).max)) - return ((image.astype(np.float32) / maxg) ** gamma) * maxg + image = np.asarray(image) + out_dtype = _resolve_dtype(dtype if dtype is not None else image.dtype) + imagef = _to_float(image) + if isinstance(gamma, str): + if gamma.lower() != "srgb": + raise ValueError("gamma must be string or scalar") + out = _srgb(imagef) else: - raise ValueError("gamma must be string or scalar") + out = imagef**gamma + return _from_float(out, out_dtype) -def gamma_decode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: +def gamma_decode( + image: np.ndarray, gamma: float | str = "sRGB", dtype: Any = None +) -> np.ndarray: r""" Gamma decoding @@ -1518,8 +1621,10 @@ def gamma_decode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: :type image: ndarray(H,W), ndarray(H,W,N) :param gamma: gamma exponent or "srgb" :type gamma: float, str + :param dtype: data type of the result, defaults to the type of ``image`` + :type dtype: str or NumPy dtype, optional :return: gamma decoded version of image - :rtype: ndarray(H,W), ndarray(H,W,N) + :rtype: ndarray(N), ndarray(H,W), ndarray(H,W,N) Maps linear tristimulus values to a gamma encoded values using either: @@ -1534,48 +1639,36 @@ def gamma_decode(image: np.ndarray, gamma: float | str = "sRGB") -> np.ndarray: :math:`\gamma=2.2`. - For images with multiple planes, the gamma correction is applied to each plane. - - For images of type double, the pixels are assumed to be in the - range 0 to 1. - - For images of type int, the pixels are assumed in the range 0 to - the maximum value of their class. Pixels are converted first to - double, encoded, then converted back to the integer class. + - The array can have any number of dimensions, including a 1D array of + values. + - Integer data (``uint8`` or ``uint16``) is assumed to span 0 to the maximum + value of its type, and float data to span 0 to 1. The result has the same + type as the input unless ``dtype`` is given, which converts and scales it. + Integer results are rounded and clipped to their range. :references: - |RVC3|, Section 10.1. + .. versionchanged:: 2.5.0 + Added the ``dtype`` argument. The result now has the type of the input, + where ``uint16`` data gave ``uint8`` and ``float64`` data gave float32. A 1D + array is now accepted with the sRGB mapping. + :seealso: :func:`gamma_encode` """ if not isinstance(gamma, (int, float, str)): raise ValueError("gamma must be string or scalar") - - imagef = float_image(image) # convert to float image - - if isinstance(gamma, str) and gamma.lower() == "srgb": - # sRGB gamma decode - - if imagef.ndim == 2: - # greyscale - out = _srgb_inverse(imagef) - - elif imagef.ndim == 3: - # multi-dimensional - out = np.empty(imagef.shape, dtype=imagef.dtype) - for p in range(imagef.shape[2]): - out[:, :, p] = _srgb_inverse(imagef[:, :, p]) - else: - raise ValueError("expecting 2d or 3d image") - + image = np.asarray(image) + out_dtype = _resolve_dtype(dtype if dtype is not None else image.dtype) + imagef = _to_float(image) + if isinstance(gamma, str): + if gamma.lower() != "srgb": + raise ValueError("gamma must be string or scalar") + out = _srgb_inverse(imagef) else: - # normal power law decoding - out = imagef**gamma - - if np.issubdtype(image.dtype, np.integer): - # original image was integer, convert back to int - return int_image(out) - else: - return out + return _from_float(out, out_dtype) def _srgb_inverse(Rg: np.ndarray) -> np.ndarray: @@ -1600,14 +1693,11 @@ def _srgb_inverse(Rg: np.ndarray) -> np.ndarray: - And colorspace.m from Peter Corke's Machine Vision Toolbox """ - R = np.empty(Rg.shape, dtype=np.float32) Rg = np.clip(Rg, 0, 1) a = 0.0404482362771076 - i = np.where(Rg <= a) - noti = np.where(Rg > a) - R[i] = Rg[i] / 12.92 - R[noti] = ((Rg[noti] + 0.055) / 1.055) ** 2.4 - return R + return np.where(Rg <= a, Rg / 12.92, ((np.maximum(Rg, a) + 0.055) / 1.055) ** 2.4).astype( + Rg.dtype + ) def _srgb(R: np.ndarray) -> np.ndarray: @@ -1632,14 +1722,11 @@ def _srgb(R: np.ndarray) -> np.ndarray: - And colorspace.m from Peter Corke's Machine Vision Toolbox """ - Rg = np.empty(R.shape, dtype=np.float32) a = 0.0031306684425005883 b = 0.416666666666666667 - i = np.where(R <= a) - noti = np.where(R > a) - Rg[i] = R[i] * 12.92 - Rg[noti] = np.real(1.055 * (R[noti] ** b) - 0.055) - return Rg + return np.where(R <= a, R * 12.92, 1.055 * np.maximum(R, a) ** b - 0.055).astype( + R.dtype + ) # ------------------------------------------------------------------------- # diff --git a/tests/test_color_dtype.py b/tests/test_color_dtype.py new file mode 100644 index 00000000..f1137384 --- /dev/null +++ b/tests/test_color_dtype.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python +"""Input shape and data type handling of gamma_encode, gamma_decode and colorspace_convert. + +Integer data (uint8, uint16) spans 0 to the maximum of its type, and float data spans +0 to 1. The output type is the input type unless ``dtype`` says otherwise. HSV, HLS, +XYZ, L*a*b* and L*u*v* are always floating point, in their natural units. +""" + +import numpy as np +import numpy.testing as nt +import pytest + +from machinevisiontoolbox import Image +from machinevisiontoolbox.base.color import ( + colorspace_convert, + gamma_decode, + gamma_encode, +) + +DTYPES = [np.uint8, np.uint16, np.float32, np.float64] +SHAPES = [(), (5,), (4, 5), (4, 5, 3)] +NATURAL = ["hsv", "hls", "xyz", "lab", "luv"] + + +def make(shape, dtype, seed=0): + rng = np.random.default_rng(seed) + if np.issubdtype(dtype, np.integer): + return rng.integers(0, np.iinfo(dtype).max + 1, shape).astype(dtype) + return rng.random(shape).astype(dtype) + + +# --------------------------------------------------------------------------- +# gamma +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("func", [gamma_encode, gamma_decode]) +@pytest.mark.parametrize("gamma", ["sRGB", 2.2]) +@pytest.mark.parametrize("shape", SHAPES) +@pytest.mark.parametrize("dtype", DTYPES) +def test_gamma_keeps_shape_and_type(func, gamma, shape, dtype): + image = make(shape, dtype) + out = func(image, gamma) + assert out.shape == image.shape + assert out.dtype == np.dtype(dtype) + if np.issubdtype(dtype, np.floating): + assert np.all((out >= 0) & (out <= 1)) + + +@pytest.mark.parametrize("func", [gamma_encode, gamma_decode]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_gamma_1d_is_the_same_as_2d(func, dtype): + x = make((12,), dtype) + nt.assert_allclose(func(x), func(x.reshape(3, 4)).reshape(12), rtol=1e-6) + + +def test_gamma_srgb_values(): + # the linear segment, the curve and the end points + nt.assert_allclose(gamma_encode(np.array([0.0, 0.001, 0.5, 1.0])), [0, 0.01292, 0.735357, 1], atol=1e-5) + nt.assert_allclose(gamma_decode(np.array([0.0, 0.01, 0.5, 1.0])), [0, 0.000774, 0.214041, 1], atol=1e-5) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_gamma_round_trip_float(dtype): + x = make((200,), dtype) + tol = 2e-3 if dtype == np.float32 else 1e-9 + nt.assert_allclose(gamma_decode(gamma_encode(x)), x, atol=tol) + # a numeric gamma is the exponent, so decoding undoes encoding with its inverse + nt.assert_allclose(gamma_decode(gamma_encode(x, 1 / 2.2), 2.2), x, atol=tol) + + +def test_gamma_uint16_keeps_its_precision(): + x = np.array([1000, 1001, 30000, 65535], dtype=np.uint16) + out = gamma_decode(x, 2.2) + assert out.dtype == np.uint16 + assert out[-1] == 65535 + # converted via uint8 these would be squashed to 256 levels + assert len(set(gamma_encode(np.arange(1000, 1100, dtype=np.uint16), 0.45))) > 50 + + +def test_gamma_dtype_argument_converts_and_scales(): + x = np.array([0, 128, 255], dtype=np.uint8) + out = gamma_decode(x, 2.0, dtype="float32") + assert out.dtype == np.float32 + nt.assert_allclose(out, (np.array([0, 128, 255]) / 255) ** 2, atol=1e-6) + out = gamma_decode(np.array([0.0, 0.5, 1.0]), 2.0, dtype=np.uint8) + assert out.dtype == np.uint8 + nt.assert_array_equal(out, [0, 64, 255]) + assert gamma_decode(np.array([0.5], dtype=np.float32), 2.0, dtype="double").dtype == np.float64 + + +def test_gamma_float_out_of_range_is_clipped_for_integer_output(): + out = gamma_encode(np.array([1.5, -0.5, 0.5]), 0.5, dtype=np.uint8) + assert out.dtype == np.uint8 + assert out[0] == 255 # not wrapped round + + +@pytest.mark.parametrize("bad", [np.int32, np.int64, "bogus"]) +def test_gamma_bad_dtype(bad): + with pytest.raises((ValueError, TypeError)): + gamma_encode(np.array([0.5]), 2.0, dtype=bad) + + +def test_gamma_bad_integer_input(): + with pytest.raises(ValueError): + gamma_encode(np.array([1, 2, 3], dtype=np.int32)) + + +def test_gamma_bad_gamma(): + with pytest.raises(ValueError): + gamma_encode(np.array([0.5]), "bogus") + with pytest.raises(ValueError): + gamma_decode(np.array([0.5]), [1, 2]) # type: ignore[arg-type] + + +# --------------------------------------------------------------------------- +# colorspace_convert +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("dst", ["bgr", "ycrcb"]) +@pytest.mark.parametrize("shape", [(3,), (4, 3), (4, 5, 3)]) +@pytest.mark.parametrize("dtype", DTYPES) +def test_convert_image_like_keeps_shape_and_type(dst, shape, dtype): + image = make(shape, dtype) + out = colorspace_convert(image, "rgb", dst) + assert out.shape == image.shape + assert out.dtype == np.dtype(dtype) + + +@pytest.mark.parametrize("dst", NATURAL) +@pytest.mark.parametrize("shape", [(3,), (4, 3), (4, 5, 3)]) +@pytest.mark.parametrize("dtype", DTYPES) +def test_convert_natural_units_is_float(dst, shape, dtype): + image = make(shape, dtype) + out = colorspace_convert(image, "rgb", dst) + assert out.shape == image.shape + expect = np.float64 if dtype == np.float64 else np.float32 + assert out.dtype == np.dtype(expect) + + +@pytest.mark.parametrize("shape", [(3,), (4, 3), (4, 5, 3)]) +def test_convert_to_grey(shape): + out = colorspace_convert(make(shape, np.uint8), "rgb", "grey") + assert out.dtype == np.uint8 + assert out.shape == shape[:-1] or out.shape == (1,) + + +@pytest.mark.parametrize("shape", [(3,), (4, 3), (4, 5, 3)]) +def test_convert_integers_are_scaled_like_floats(shape): + u8 = make(shape, np.uint8) + u16 = (u8.astype(np.uint16) * 257).astype(np.uint16) # the same values in 16 bits + f = u8.astype(np.float64) / 255 + for dst in NATURAL: + expect = colorspace_convert(f, "rgb", dst) + nt.assert_allclose(colorspace_convert(u8, "rgb", dst), expect, rtol=1e-3, atol=1e-3) + nt.assert_allclose(colorspace_convert(u16, "rgb", dst), expect, rtol=1e-3, atol=1e-3) + + +def test_convert_vector_of_uint8_is_not_treated_as_float(): + # this used to give garbage: 255 was taken as a float + out = colorspace_convert(np.array([255, 0, 0], dtype=np.uint8), "rgb", "hsv") + nt.assert_allclose(out, [0, 1, 1], atol=1e-6) + nt.assert_allclose(out, colorspace_convert([1, 0, 0], "rgb", "hsv"), atol=1e-6) + + +def test_convert_list_is_float(): + out = colorspace_convert([0, 0, 1], "rgb", "hsv") + assert out.dtype == np.float64 + nt.assert_allclose(out, [240, 1, 1], atol=1e-5) + + +@pytest.mark.parametrize("space", NATURAL) +def test_convert_natural_units_need_float(space): + with pytest.raises(ValueError, match="floating point"): + colorspace_convert(make((4, 3), np.uint8), space, "rgb") + with pytest.raises(ValueError, match="floating point"): + colorspace_convert(make((4, 3), np.uint8), "rgb", space, dtype=np.uint8) + + +def test_convert_other_integer_types_are_not_images(): + with pytest.raises(ValueError): + colorspace_convert(np.array([[1, 2, 3]], dtype=np.int32), "rgb", "bgr") + with pytest.raises(ValueError): + colorspace_convert(np.array([[0.1, 0.2, 0.3]]), "rgb", "bgr", dtype=np.int32) + + +@pytest.mark.parametrize("shape", [(4, 3), (4, 5, 3)]) +@pytest.mark.parametrize("space", ["hsv", "hls", "xyz", "lab", "luv", "ycrcb"]) +def test_convert_round_trip_uint8(shape, space): + rng = np.random.default_rng(1) + rgb = rng.integers(20, 236, shape, dtype=np.uint8) + there = colorspace_convert(rgb, "rgb", space) + back = colorspace_convert(there, space, "rgb", dtype=np.uint8) + assert back.dtype == np.uint8 + nt.assert_allclose(back.astype(int), rgb.astype(int), atol=2) + + +def test_convert_dtype_argument(): + rgb = np.array([[0.2, 0.4, 0.6]]) + out = colorspace_convert(rgb, "rgb", "bgr", dtype=np.uint8) + assert out.dtype == np.uint8 + nt.assert_array_equal(out, [[153, 102, 51]]) + out = colorspace_convert(make((4, 3), np.uint8), "rgb", "bgr", dtype="float") + assert out.dtype == np.float32 + assert out.min() >= 0 and out.max() <= 1 + + +def test_convert_float64_and_uint16_images_work_for_every_space(): + # OpenCV cannot do these directly + for dtype in (np.float64, np.uint16): + image = make((4, 5, 3), dtype) + for dst in NATURAL + ["ycrcb", "bgr"]: + colorspace_convert(image, "rgb", dst) + + +def test_convert_bad_shape(): + with pytest.raises(ValueError): + colorspace_convert(np.zeros((4, 4)), "rgb", "hsv") + + +# --------------------------------------------------------------------------- +# Image.colorspace +# --------------------------------------------------------------------------- + + +def test_image_colorspace_uint8_to_natural_units(): + im = Image(make((6, 8, 3), np.uint8), colororder="RGB", dtype=True) + hsv = im.colorspace("hsv") + assert hsv.dtype == np.float32 + assert 0 <= hsv.array[..., 0].max() <= 360 and hsv.array[..., 0].max() > 180 + assert 0 <= hsv.array[..., 1].max() <= 1 + lab = im.colorspace("lab") + assert lab.array[..., 1].min() < 0 # a* is signed + + +def test_image_colorspace_keeps_type_for_image_like_spaces(): + for dtype in DTYPES: + im = Image(make((6, 8, 3), dtype), colororder="RGB", dtype=True) + assert im.colorspace("ycrcb").dtype == np.dtype(dtype) + + +def test_image_colorspace_dtype_argument(): + im = Image(make((6, 8, 3), np.uint8), colororder="RGB", dtype=True) + assert im.colorspace("bgr", dtype="float").dtype == np.float32 + assert im.colorspace("hsv", dtype="double").dtype == np.float64 diff --git a/tests/test_image_color.py b/tests/test_image_color.py index fab571e1..836846a8 100644 --- a/tests/test_image_color.py +++ b/tests/test_image_color.py @@ -321,8 +321,8 @@ def test_gamma_encode_sRGB_direct_color(self): def test_gamma_encode_int_image(self): img = np.full((2, 2), 128, dtype=np.uint8) out = gamma_encode(img, 2.2) - # gamma_encode returns float32 for integer input with numeric gamma - self.assertEqual(out.dtype, np.float32) + # an integer image gives an integer result of the same type + self.assertEqual(out.dtype, np.uint8) def test_gamma_decode_float_direct(self): img = np.array([[0.5]])