Skip to content

API Reference

colormap_tool

Colormap Tools - A library for working with colormaps across different visualization libraries.

This package provides utilities for loading, converting, and using colormaps from various sources (matplotlib, OpenCV) in a consistent way. It allows using colormaps from one library in another, for example using a matplotlib colormap in OpenCV or vice versa.

The package loads colormaps from pickle files that store them as numpy arrays with shape (256, 1, 3) and dtype uint8. These colormaps can then be converted to the appropriate format for each visualization library.

Main components:

  • _cmps.py: Loads and stores colormap data from pickle files, provides RGB format colormaps and resampling utilities
  • _cv.py: Provides colormaps in OpenCV format (BGR)
  • _mpl.py: Provides colormaps in Matplotlib format

apply_colormap_with_numpy(src, cmp, dst=None)

Apply a colormap to an image using numpy instead of OpenCV.

Parameters:

Name Type Description Default

src

ndarray

The image to apply the colormap to.

required

cmp

ndarray

The colormap to apply. Should have shape (256, 1, 3) and dtype uint8.

required

dst

ndarray

The output array to store the result. If None, a new array will be created.

None

Returns:

Type Description
ndarray

The output array with the colormap applied.

Source code in src/colormap_tool/_cv.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def apply_colormap_with_numpy(src: np.ndarray, cmp: np.ndarray, dst: np.ndarray | None = None) -> np.ndarray:
    """Apply a colormap to an image using numpy instead of OpenCV.

    Parameters
    ----------
    src : numpy.ndarray
        The image to apply the colormap to.
    cmp : numpy.ndarray
        The colormap to apply. Should have shape (256, 1, 3) and dtype uint8.
    dst : numpy.ndarray, optional
        The output array to store the result. If None, a new array will be created.

    Returns
    -------
    numpy.ndarray
        The output array with the colormap applied.

    """
    if dst is None:
        dst = np.zeros_like(src)
    else:
        if dst.shape != src.shape:
            raise ValueError(
                f"The shape of the output array {dst.shape} does not match the shape of the input array {src.shape}.",
            )

    if src.dtype != np.uint8:
        raise ValueError(f"The dtype of the input array {src.dtype} is not uint8.")
    if cmp.shape != (256, 1, 3):
        raise ValueError(f"The shape of the colormap array {cmp.shape} is not (256, 1, 3).")
    if cmp.dtype != np.uint8:
        raise ValueError(f"The dtype of the colormap array {cmp.dtype} is not uint8.")

    dst = cmp.copy().squeeze()
    dst = dst[src]

    return dst

get_colormaps(name, namespace=None, n=None)

Return a colormap as an RGB LUT array.

Returns a (n, 3) uint8 array in RGB order, resampled to length n if specified. Useful for custom visualization, further conversion, or as a base for other formats.

Parameters:

Name Type Description Default

name

str

Colormap name. If namespace is None, use "namespace.name" format.

required

namespace

str

"cv" for OpenCV, "mpl" for Matplotlib.

None

n

int

Number of LUT entries. If None, defaults to 256.

None

Returns:

Type Description
ndarray

(n, 3) uint8 RGB LUT.

Raises:

Type Description
ValueError

If the colormap or namespace is not found.

Examples:

>>> lut = get_colormaps("mpl.viridis", n=128)
>>> plt.imshow(data, cmap=colormap_tools.uint8_rgb_arr2mpl_cmp(lut))
Source code in src/colormap_tool/_cmps.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def get_colormaps(name: str, namespace: str | None = None, n: int | None = None) -> np.ndarray:
    """Return a colormap as an RGB LUT array.

    Returns a (n, 3) uint8 array in RGB order, resampled to length n if specified.
    Useful for custom visualization, further conversion, or as a base for other formats.

    Parameters
    ----------
    name : str
        Colormap name. If namespace is None, use "namespace.name" format.
    namespace : str, optional
        "cv" for OpenCV, "mpl" for Matplotlib.
    n : int, optional
        Number of LUT entries. If None, defaults to 256.

    Returns
    -------
    np.ndarray
        (n, 3) uint8 RGB LUT.

    Raises
    ------
    ValueError
        If the colormap or namespace is not found.

    Examples
    --------
    >>> lut = get_colormaps("mpl.viridis", n=128)
    >>> plt.imshow(data, cmap=colormap_tools.uint8_rgb_arr2mpl_cmp(lut))

    """
    if namespace is not None:
        if "." in name:
            raise ValueError(f"Namespace {namespace} is provided, so name {name} should not include a dot.")
    else:
        namespace, name = name.split(".")

    namespace = namespace.lower()
    name = name.lower()
    if namespace not in CMPSPACE:
        raise ValueError(f"Namespace {namespace} is not recognized.")
    if name not in CMPSPACE[namespace]:
        raise ValueError(f"Colormap {name} is not found in namespace {namespace}.")

    # Get the original LUT
    lut = CMPSPACE[namespace][name]

    # Reshape to (256, 3)
    lut = lut.reshape(-1, 3)

    # Resample if requested
    if n is not None and n != lut.shape[0]:
        lut = resample_lut(lut, n)

    return lut

get_cv_colormaps(name, namespace=None)

Return a colormap suitable for OpenCV's cv2.applyColorMap.

Parameters:

Name Type Description Default

name

str

Colormap name. If namespace is None, use "namespace.name" format (e.g., "cv.jet", "mpl.viridis").

required

namespace

str

"cv" for OpenCV, "mpl" for Matplotlib. If provided, name should not include a dot.

None

Returns:

Type Description
int or ndarray

OpenCV colormap constant or a (256, 1, 3) uint8 LUT in BGR order.

Raises:

Type Description
ValueError

If the colormap or namespace is not found.

Examples:

>>> lut = get_cv_colormaps("mpl.viridis")
>>> img_color = cv2.applyColorMap(gray_img, lut)
>>> lut2 = get_cv_colormaps("jet", "cv")
>>> img_color2 = cv2.applyColorMap(gray_img, lut2)
Source code in src/colormap_tool/_cv.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def get_cv_colormaps(name: str, namespace: str | None = None) -> int | np.ndarray:
    """Return a colormap suitable for OpenCV's cv2.applyColorMap.

    Parameters
    ----------
    name : str
        Colormap name. If namespace is None, use "namespace.name" format (e.g., "cv.jet", "mpl.viridis").
    namespace : str, optional
        "cv" for OpenCV, "mpl" for Matplotlib. If provided, name should not include a dot.

    Returns
    -------
    int or np.ndarray
        OpenCV colormap constant or a (256, 1, 3) uint8 LUT in BGR order.

    Raises
    ------
    ValueError
        If the colormap or namespace is not found.

    Examples
    --------
    >>> lut = get_cv_colormaps("mpl.viridis")
    >>> img_color = cv2.applyColorMap(gray_img, lut)
    >>> lut2 = get_cv_colormaps("jet", "cv")
    >>> img_color2 = cv2.applyColorMap(gray_img, lut2)

    """
    if namespace is not None:
        if "." in name:
            raise ValueError(f"Namespace {namespace} is provided, so name {name} should not include a dot.")
    else:
        namespace, name = name.split(".")

    namespace = namespace.lower()
    name = name.lower()
    if namespace not in CMPSPACE:
        raise ValueError(f"Namespace {namespace} is not recognized.")
    if name not in CMPSPACE[namespace]:
        raise ValueError(f"Colormap {name} is not found in namespace {namespace}.")

    rgb_arr = CMPSPACE[namespace][name]
    bgr_arr = rgb_arr[:, :, ::-1]
    return bgr_arr

get_mpl_colormaps(name, namespace=None)

Get a colormap in Matplotlib format.

Parameters:

Name Type Description Default

name

str

The name of the colormap. If namespace is None, this should be in the format "namespace.name" (e.g., "cv.VIRIDIS", "mpl.viridis").

required

namespace

Optional[str]

The namespace of the colormap ("cv", "mpl"). If provided, the name parameter should not include the namespace prefix.

None

Returns:

Type Description
Colormap

A Matplotlib Colormap object that can be used with matplotlib plotting functions. For matplotlib colormaps (namespace="mpl"), returns the built-in colormap. For other colormaps, converts the numpy array to a Matplotlib ListedColormap.

Raises:

Type Description
AssertionError

If the namespace is not recognized or the colormap name is not found in the namespace.

Examples:

>>> # Get a matplotlib built-in colormap
>>> cmap = get_mpl_colormaps("viridis", "mpl")
>>> # Or equivalently
>>> cmap = get_mpl_colormaps("mpl.viridis")
>>> plt.imshow(data, cmap=cmap)
>>> # Get an OpenCV colormap for use with matplotlib
>>> cmap = get_mpl_colormaps("VIRIDIS", "cv")
>>> # Or equivalently
>>> cmap = get_mpl_colormaps("cv.VIRIDIS")
>>> plt.imshow(data, cmap=cmap)
Source code in src/colormap_tool/_mpl.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def get_mpl_colormaps(name: str, namespace: str | None = None) -> Colormap:
    """Get a colormap in Matplotlib format.

    Parameters
    ----------
    name : str
        The name of the colormap. If namespace is None, this should be in the format
        "namespace.name" (e.g., "cv.VIRIDIS", "mpl.viridis").
    namespace : Optional[str], optional
        The namespace of the colormap ("cv", "mpl"). If provided, the name
        parameter should not include the namespace prefix.

    Returns
    -------
    matplotlib.colors.Colormap
        A Matplotlib Colormap object that can be used with matplotlib plotting functions.
        For matplotlib colormaps (namespace="mpl"), returns the built-in colormap.
        For other colormaps, converts the numpy array to a Matplotlib ListedColormap.

    Raises
    ------
    AssertionError
        If the namespace is not recognized or the colormap name is not found in the namespace.

    Examples
    --------
    >>> # Get a matplotlib built-in colormap
    >>> cmap = get_mpl_colormaps("viridis", "mpl")
    >>> # Or equivalently
    >>> cmap = get_mpl_colormaps("mpl.viridis")
    >>> plt.imshow(data, cmap=cmap)

    >>> # Get an OpenCV colormap for use with matplotlib
    >>> cmap = get_mpl_colormaps("VIRIDIS", "cv")
    >>> # Or equivalently
    >>> cmap = get_mpl_colormaps("cv.VIRIDIS")
    >>> plt.imshow(data, cmap=cmap)

    """
    try:
        import matplotlib as mpl
    except ImportError as err:
        raise ImportError("Missing optional dependency: matplotlib", name="matplotlib") from err
    if namespace is not None:
        if "." in name:
            raise ValueError(f"Namespace {namespace} is provided, so name {name} should not include a dot.")
    else:
        namespace, name = name.split(".")

    namespace = namespace.lower()
    name = name.lower()
    if namespace not in CMPSPACE:
        raise ValueError(f"Namespace {namespace} is not recognized.")
    if name not in CMPSPACE[namespace]:
        raise ValueError(f"Colormap {name} is not found in namespace {namespace}.")

    if namespace == "mpl":
        return mpl.colormaps[name]
    else:
        if name not in _cached_colormaps[namespace]:
            _cached_colormaps[namespace][name] = uint8_rgb_arr2mpl_cmp(
                CMPSPACE[namespace][name],
                f"{namespace}.{name}",
                alpha=1.0,
                mode="listed",
            )
        return _cached_colormaps[namespace][name]

register_all_cmps2mpl()

Register all available colormaps with the matplotlib.colormaps registry.

This function iterates through all namespaces and colormap names in CMPSPACE and registers each colormap with matplotlib. After calling this function, all colormaps can be accessed directly through matplotlib.colormaps.

Examples:

>>> register_all_cmps2mpl()
>>> import matplotlib.pyplot as plt
>>> plt.imshow(data, cmap="cv.VIRIDIS")
Source code in src/colormap_tool/_mpl.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def register_all_cmps2mpl() -> None:
    """Register all available colormaps with the matplotlib.colormaps registry.

    This function iterates through all namespaces and colormap names in CMPSPACE
    and registers each colormap with matplotlib. After calling this function,
    all colormaps can be accessed directly through matplotlib.colormaps.

    Examples
    --------
    >>> register_all_cmps2mpl()
    >>> import matplotlib.pyplot as plt
    >>> plt.imshow(data, cmap="cv.VIRIDIS")

    """
    try:
        import matplotlib as mpl
    except ImportError as err:
        raise ImportError("Missing optional dependency: matplotlib", name="matplotlib") from err
    global _is_registered
    if _is_registered:
        return
    for namespace in CMPSPACE:
        if namespace == "mpl":
            continue
        for name in CMPSPACE[namespace]:
            cmp = get_mpl_colormaps(name, namespace)
            mpl.colormaps.register(cmp)
    _is_registered = True

resample_lut(lut, n)

Resample a LUT to a new length.

Accepts (m, 3) or (m, 1, 3) uint8 arrays. Returns the same format with length n.

Parameters:

Name Type Description Default

lut

ndarray

Input LUT, shape (m, 3) or (m, 1, 3), dtype uint8.

required

n

int

Target length.

required

Returns:

Type Description
ndarray

Resampled LUT, same format as input, length n.

Raises:

Type Description
(TypeError, ValueError)

If input is not a valid LUT.

Examples:

>>> lut = np.array([[0, 0, 0], [255, 255, 255]], dtype=np.uint8)
>>> resample_lut(lut, 5).shape
(5, 3)
Source code in src/colormap_tool/_cmps.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def resample_lut(lut: np.ndarray, n: int) -> np.ndarray:
    """Resample a LUT to a new length.

    Accepts (m, 3) or (m, 1, 3) uint8 arrays. Returns the same format with length n.

    Parameters
    ----------
    lut : np.ndarray
        Input LUT, shape (m, 3) or (m, 1, 3), dtype uint8.
    n : int
        Target length.

    Returns
    -------
    np.ndarray
        Resampled LUT, same format as input, length n.

    Raises
    ------
    TypeError, ValueError
        If input is not a valid LUT.

    Examples
    --------
    >>> lut = np.array([[0, 0, 0], [255, 255, 255]], dtype=np.uint8)
    >>> resample_lut(lut, 5).shape
    (5, 3)

    """
    msg = "The shape of the lut must be (n, 3) or (n, 1, 3)."

    if lut.ndim == 2:
        if lut.shape[1] != 3:
            raise ValueError(msg)
        lut2d = lut
        out_shape = (n, 3)
    elif lut.ndim == 3:
        if lut.shape[1] != 1 or lut.shape[2] != 3:
            raise ValueError(msg)
        lut2d = lut.reshape(-1, 3)
        out_shape = (n, 1, 3)
    else:
        raise ValueError(msg)

    m = lut2d.shape[0]
    if n == m:
        return lut.copy() if lut.shape[0] == n else lut2d.reshape(out_shape)

    x_old = np.linspace(0, 1, m)
    x_new = np.linspace(0, 1, n)
    resampled = np.empty((n, 3), dtype=np.float32)
    for c in range(3):
        resampled[:, c] = np.interp(x_new, x_old, lut2d[:, c])
    resampled = np.clip(resampled, 0, 255).astype(np.uint8)
    return resampled.reshape(out_shape)

uint8_rgb_arr2mpl_cmp(arr, name, alpha=1.0, mode='listed')

Convert a uint8 RGB array to a Matplotlib Colormap object.

Parameters:

Name Type Description Default

arr

ndarray

A numpy array of RGB values with shape (N, 3) or (N, 1, 3) and dtype uint8. Values should be in the range [0, 255].

required

name

str

The name to give to the colormap.

required

alpha

float

The alpha (opacity) value for the colormap, by default 1.0 (fully opaque).

1.0

mode

('listed', 'linear')

The type of colormap to create: - "listed": Creates a ListedColormap (discrete colors) - "linear": Creates a LinearSegmentedColormap (interpolated colors) Default is "listed".

"listed"

Returns:

Type Description
Colormap

A Matplotlib Colormap object (either ListedColormap or LinearSegmentedColormap depending on the mode parameter).

Raises:

Type Description
AssertionError

If the input array has an invalid shape or dtype.

ValueError

If the mode parameter is not "listed" or "linear".

Notes

The function converts the uint8 values [0-255] to float values [0-1] required by Matplotlib.

Source code in src/colormap_tool/_mpl.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def uint8_rgb_arr2mpl_cmp(
    arr: np.ndarray,
    name: str,
    alpha: float = 1.0,
    mode: Literal["listed", "linear"] = "listed",
) -> Colormap:
    """Convert a uint8 RGB array to a Matplotlib Colormap object.

    Parameters
    ----------
    arr : numpy.ndarray
        A numpy array of RGB values with shape (N, 3) or (N, 1, 3) and dtype uint8.
        Values should be in the range [0, 255].
    name : str
        The name to give to the colormap.
    alpha : float, optional
        The alpha (opacity) value for the colormap, by default 1.0 (fully opaque).
    mode : {"listed", "linear"}, optional
        The type of colormap to create:
        - "listed": Creates a ListedColormap (discrete colors)
        - "linear": Creates a LinearSegmentedColormap (interpolated colors)
        Default is "listed".

    Returns
    -------
    matplotlib.colors.Colormap
        A Matplotlib Colormap object (either ListedColormap or LinearSegmentedColormap
        depending on the mode parameter).

    Raises
    ------
    AssertionError
        If the input array has an invalid shape or dtype.
    ValueError
        If the mode parameter is not "listed" or "linear".

    Notes
    -----
    The function converts the uint8 values [0-255] to float values [0-1] required by Matplotlib.

    """
    try:
        from matplotlib.colors import LinearSegmentedColormap, ListedColormap
    except ImportError as err:
        raise ImportError("Missing optional dependency: matplotlib", name="matplotlib") from err
    if arr.ndim == 2 and arr.shape[1] != 3:
        raise ValueError(f"The shape of the input array {arr.shape} is not (N, 3).")
    if arr.ndim == 3:
        if arr.shape[1] != 1:
            raise ValueError(f"The shape of the input array {arr.shape} is not (N, 1, 3).")
        if arr.shape[2] != 3:
            raise ValueError(f"The shape of the input array {arr.shape} is not (N, 1, 3).")
        arr = arr.squeeze(1)

    if arr.dtype != np.uint8:
        raise ValueError(f"The dtype of the input array {arr.dtype} is not uint8.")

    # convert [0-255] uint8 to [0-1] float
    arr = arr.astype(np.float64) / 255.0

    alpha = np.full((arr.shape[0], 1), alpha)

    arr = np.concatenate((arr, alpha), axis=1)

    if mode == "listed":
        return ListedColormap(arr, name=name)
    elif mode == "linear":
        return LinearSegmentedColormap.from_list(name, arr)
    else:
        raise ValueError("mode must be 'listed' or 'linear'")