显示colorspacious.rgb_to_lab源代码
时间: 2023-08-04 18:04:39 浏览: 183
RGB转为Lab空间
以下是 `colorspacious.rgb_to_lab` 函数的源代码,你可以在 Python 中查看:
```python
from . import util, CAM16UCS
import numpy as np
def rgb_to_lab(rgb, illuminant='D65', observer='2', out_dtype=np.float64,
in_gamut='error'):
"""
Convert from sRGB to CIELAB.
Parameters
----------
rgb : array_like
Input array of RGB values to convert to CIELAB. The last dimension
must be length 3, corresponding to red, green, and blue.
illuminant : str or array_like, optional
The name of the illuminant or an array of x, y, and Y values. See
the :ref:`illuminants` section for more information.
observer : str or array_like, optional
The name of the observer or an array of Cone Response Domain (CRD)
color matching functions. See the :ref:`observers` section for
more information.
out_dtype : data type, optional
The data type of the output. Default is ``np.float64``.
in_gamut : {'error', 'clip', 'nan'}, optional
How to handle input RGB values that are out of gamut for the RGB
working space. 'error' raises an exception, 'clip' clips the RGB
values to be within the RGB working space, and 'nan' returns NaN
values for all Lab channels.
Returns
-------
lab : ndarray
Array of Lab values. The last dimension will be length 3,
corresponding to L, a, and b.
Raises
------
ValueError
If the last dimension of `rgb` is not length 3.
Examples
--------
Convert a single RGB color to Lab:
>>> from colorspacious import cspace_convert
>>> rgb = [0.5, 0.0, 0.0]
>>> lab = cspace_convert(rgb, "sRGB255", "CIELab")
>>> lab
array([ 25.89249944, 53.58619948, 38.07171523])
Convert many RGB colors to Lab:
>>> import numpy as np
>>> from colorspacious import cspace_convert
>>> rgbs = np.random.rand(5, 5, 3)
>>> labs = cspace_convert(rgbs, "sRGB255", "CIELab")
>>> labs.shape
(5, 5, 3)
"""
if rgb.shape[-1] != 3:
raise ValueError("The last dimension of the input array must be length 3 "
"(corresponding to the red, green, and blue channels).")
rgb = util.convert_color(rgb, 'sRGB255', 'sRGB1', in_gamut=in_gamut)
xyz = util.convert_color(rgb, 'sRGB1', 'XYZ', illuminant=illuminant,
observer=observer)
lab = util.convert_color(xyz, 'XYZ', 'CIELab', illuminant=illuminant,
observer=observer)
return util.in_range(lab, 'CIELab', out_dtype)
```
这个函数的源代码比较简单,它主要是通过 `util.convert_color` 函数将 RGB 颜色转换为 XYZ 颜色,然后再将 XYZ 颜色转换为 Lab 颜色。在转换过程中,还可以指定光源和观察者的参数。最后,`in_range` 函数用于将输出的 Lab 颜色调整为合适的范围内。
阅读全文