• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ghiggi / ximage / 23169211772

16 Mar 2026 10:37PM UTC coverage: 94.953%. Remained the same
23169211772

Pull #21

github

web-flow
Merge 31815bcf3 into f10b9569e
Pull Request #21: [pre-commit.ci] pre-commit autoupdate

8 of 8 new or added lines in 8 files covered. (100.0%)

21 existing lines in 4 files now uncovered.

809 of 852 relevant lines covered (94.95%)

0.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.83
/ximage/labels/plot_labels.py
1
# -----------------------------------------------------------------------------.
2
# MIT License
3

4
# Copyright (c) 2024-2026 ximage developers
5
#
6
# This file is part of ximage.
7

8
# Permission is hereby granted, free of charge, to any person obtaining a copy
9
# of this software and associated documentation files (the "Software"), to deal
10
# in the Software without restriction, including without limitation the rights
11
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
# copies of the Software, and to permit persons to whom the Software is
13
# furnished to do so, subject to the following conditions:
14
#
15
# The above copyright notice and this permission notice shall be included in all
16
# copies or substantial portions of the Software.
17
#
18
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
# SOFTWARE.
25

26
# -----------------------------------------------------------------------------.
27
"""Utilities to plot labels."""
28
import matplotlib as mpl
1✔
29
import matplotlib.pyplot as plt
1✔
30
import numpy as np
1✔
31

32
from ximage.labels.labels import get_label_indices
1✔
33

34

35
def get_label_colorbar_settings(label_indices, cmap="Paired"):
1✔
36
    """Return plot and cbar kwargs to plot properly a label array."""
37
    # Cast to int the label_indices
38
    label_indices = label_indices.astype(int)
1✔
39
    # Compute number of required colors
40
    n_labels = len(label_indices)
1✔
41

42
    # Get colormap if string
43
    if isinstance(cmap, str):
1✔
44
        cmap = plt.get_cmap(cmap)
1✔
45

46
    # Extract colors
47
    color_list = [cmap(i) for i in range(cmap.N)]
1✔
48

49
    # Create the new colormap
50
    cmap_new = mpl.colors.LinearSegmentedColormap.from_list("Label Classes", color_list, n_labels)
1✔
51

52
    # Define the bins and normalize
53
    bounds = np.linspace(1, n_labels + 1, n_labels + 1)
1✔
54
    norm = mpl.colors.BoundaryNorm(bounds, cmap_new.N)
1✔
55

56
    # Define the plot kwargs
57
    plot_kwargs = {}
1✔
58
    plot_kwargs["cmap"] = cmap_new
1✔
59
    plot_kwargs["norm"] = norm
1✔
60

61
    # Define colorbar kwargs
62
    ticks = bounds[:-1] + 0.5
1✔
63
    ticklabels = label_indices
1✔
64
    assert len(ticks) == len(ticklabels)
1✔
65
    cbar_kwargs = {}
1✔
66
    cbar_kwargs["label"] = "Label IDs"
1✔
67
    cbar_kwargs["ticks"] = ticks
1✔
68
    cbar_kwargs["ticklabels"] = ticklabels
1✔
69
    return plot_kwargs, cbar_kwargs
1✔
70

71

72
def plot_labels(
1✔
73
    dataarray,
74
    x=None,
75
    y=None,
76
    ax=None,
77
    max_n_labels=50,
78
    add_colorbar=True,
79
    cmap="Paired",
80
    use_imshow=False,
81
    **plot_kwargs,
82
):
83
    """Plot labels.
84

85
    The maximum allowed number of labels to plot is 'max_n_labels'.
86
    """
87
    # Check that datarray has two dimensions only
88
    if len(dataarray.dims) != 2:
1✔
UNCOV
89
        raise ValueError(f"The dataarray must have two dimensions only to be plotted. Got {dataarray.dims}")
×
90

91
    # Compute the dataarray if needed
92
    dataarray = dataarray.compute()
1✔
93

94
    # Retrieve label indices
95
    label_indices = get_label_indices(dataarray)
1✔
96
    n_labels = len(label_indices)
1✔
97
    if add_colorbar and n_labels > max_n_labels:
1✔
98
        msg = f"""The array currently contains {n_labels} labels and 'max_n_labels'
1✔
99
            is set to {max_n_labels}. The colorbar is not displayed!"""
100
        print(msg)
1✔
101
        add_colorbar = False
1✔
102

103
    # Redefine label array to have consecutive integers starting from 1
104
    # dataarray = redefine_label_array(dataarray, label_indices=label_indices)
105

106
    # Replace 0 with nan
107
    dataarray = dataarray.where(dataarray > 0)
1✔
108

109
    # Define appropriate colormap
110
    plot_kwargs, cbar_kwargs = get_label_colorbar_settings(label_indices, cmap=cmap)
1✔
111

112
    # Plot image
113
    ticklabels = cbar_kwargs.pop("ticklabels", None)
1✔
114
    if not add_colorbar:
1✔
115
        cbar_kwargs = {}
1✔
116
    if use_imshow:
1✔
117
        p = dataarray.plot.imshow(
1✔
118
            x=x,
119
            y=y,
120
            ax=ax,
121
            add_colorbar=add_colorbar,
122
            cbar_kwargs=cbar_kwargs,
123
            **plot_kwargs,
124
        )
125
    else:
126
        p = dataarray.plot.pcolormesh(
1✔
127
            x=x,
128
            y=y,
129
            ax=ax,
130
            add_colorbar=add_colorbar,
131
            cbar_kwargs=cbar_kwargs,
132
            **plot_kwargs,
133
        )
134
    plt.title(dataarray.name)
1✔
135
    if add_colorbar and ticklabels is not None:
1✔
136
        p.colorbar.ax.set_yticklabels(ticklabels)
1✔
137
    return p
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc