Skip to content

Plots

siapy.utils.plots

pixels_select_click

pixels_select_click(image: ImageType) -> Pixels
PARAMETER DESCRIPTION
image

TYPE: ImageType

Source code in siapy/utils/plots.py
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
63
64
65
66
67
68
69
70
def pixels_select_click(image: ImageType) -> Pixels:
    image_display = validate_image_to_numpy_3channels(image)

    coordinates = []
    fig, ax = plt.subplots(1, 1)
    ax.imshow(image_display)
    fig.tight_layout()
    enter_clicked = 0

    def onclick(event):
        nonlocal coordinates, fig
        logger.info(f"Pressed coordinate: X = {event.xdata}, Y = {event.ydata}")
        x_coor = round(event.xdata)
        y_coor = round(event.ydata)
        coordinates.append([x_coor, y_coor])

        ax.scatter(
            int(x_coor),
            int(y_coor),
            marker="x",
            c="red",
        )
        fig.canvas.draw()

    def accept(event):
        nonlocal enter_clicked
        if event.key == "enter":
            logger.info("Enter clicked.")
            enter_clicked = 1
            plt.close()

    def onexit(event):
        nonlocal enter_clicked
        if not enter_clicked:
            logger.info("Exiting application.")
            plt.close()
            sys.exit(0)

    fig.canvas.mpl_connect("button_press_event", onclick)
    fig.canvas.mpl_connect("key_press_event", accept)
    fig.canvas.mpl_connect("close_event", onexit)
    plt.show()
    return Pixels.from_iterable(coordinates)

pixels_select_lasso

pixels_select_lasso(image: ImageType, selector_props: dict[str, Any] | None = None) -> list[Pixels]
PARAMETER DESCRIPTION
image

TYPE: ImageType

selector_props

TYPE: dict[str, Any] | None DEFAULT: None

Source code in siapy/utils/plots.py
 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
124
125
126
127
128
129
130
131
132
133
def pixels_select_lasso(
    image: ImageType, selector_props: dict[str, Any] | None = None
) -> list[Pixels]:
    image_display = validate_image_to_numpy_3channels(image)

    x, y = np.meshgrid(
        np.arange(image_display.shape[1]), np.arange(image_display.shape[0])
    )
    pixes_all_stack = np.vstack((x.flatten(), y.flatten())).T

    fig, ax = plt.subplots(1, 1)
    ax.imshow(image_display)
    fig.tight_layout()

    indices = 0
    indices_list = []
    enter_clicked = 0

    def onselect(vertices_selected, eps=1e-8):
        logger.info("Selected.")
        nonlocal indices
        path = Path(vertices_selected)
        indices = path.contains_points(pixes_all_stack)

    def onrelease(_):
        nonlocal indices, indices_list
        indices_list.append(indices)

    def onexit(event):
        nonlocal enter_clicked
        if not enter_clicked:
            logger.info("Exiting application.")
            plt.close()
            sys.exit(0)

    def accept(event):
        nonlocal enter_clicked
        if event.key == "enter":
            logger.info("Enter clicked.")
            enter_clicked = 1
            plt.close()

    props = (
        selector_props
        if selector_props is not None
        else {"color": "red", "linewidth": 2, "linestyle": "-"}
    )
    lasso = LassoSelector(ax, onselect, props=props)  # noqa: F841
    fig.canvas.mpl_connect("button_release_event", onrelease)
    fig.canvas.mpl_connect("close_event", onexit)
    fig.canvas.mpl_connect("key_press_event", accept)

    plt.show()

    selected_areas = []
    for indices in indices_list:
        coordinates = pixes_all_stack[indices]
        selected_areas.append(Pixels.from_iterable(coordinates))

    logger.info(f"Number of selected areas: {len(selected_areas)}")
    return selected_areas

display_image_with_areas

display_image_with_areas(image: ImageType, areas: Pixels | list[Pixels], *, color: str = 'red')
PARAMETER DESCRIPTION
image

TYPE: ImageType

areas

TYPE: Pixels | list[Pixels]

color

TYPE: str DEFAULT: 'red'

Source code in siapy/utils/plots.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def display_image_with_areas(
    image: ImageType,
    areas: Pixels | list[Pixels],
    *,
    color: str = "red",
):
    if not isinstance(areas, list):
        areas = [areas]

    image_display = validate_image_to_numpy_3channels(image)
    fig, ax = plt.subplots()
    ax.imshow(image_display)

    for pixels in areas:
        ax.scatter(
            pixels.u(),
            pixels.v(),
            lw=0,
            marker="o",
            c=color,
            s=(72.0 / fig.dpi) ** 2,
        )

    plt.show()

display_multiple_images_with_areas

display_multiple_images_with_areas(images_with_areas: list[tuple[ImageType, Pixels | list[Pixels]]], *, color: str = 'red', plot_interactive_buttons: bool = True) -> InteractiveButtonsEnum | None
PARAMETER DESCRIPTION
images_with_areas

TYPE: list[tuple[ImageType, Pixels | list[Pixels]]]

color

TYPE: str DEFAULT: 'red'

plot_interactive_buttons

TYPE: bool DEFAULT: True

Source code in siapy/utils/plots.py
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
def display_multiple_images_with_areas(
    images_with_areas: list[tuple[ImageType, Pixels | list[Pixels]]],
    *,
    color: str = "red",
    plot_interactive_buttons: bool = True,
) -> InteractiveButtonsEnum | None:
    num_images = len(images_with_areas)
    fig, axes = plt.subplots(1, num_images, figsize=(num_images * 5, 5))

    if isinstance(axes, Axes):
        axes = np.array([axes])

    for ax, (image, selected_areas) in zip(axes, images_with_areas):
        if not isinstance(selected_areas, list):
            selected_areas = [selected_areas]

        image_display = validate_image_to_numpy_3channels(image)
        ax.imshow(image_display)

        for pixels in selected_areas:
            ax.scatter(
                pixels.u(),
                pixels.v(),
                lw=0,
                marker="o",
                c=color,
                s=(72.0 / fig.dpi) ** 2,
            )
    if plot_interactive_buttons:
        return interactive_buttons()

    plt.show()
    return None

interactive_buttons

interactive_buttons()
Source code in siapy/utils/plots.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def interactive_buttons():
    flag = InteractiveButtonsEnum.REPEAT

    def repeat(event):
        nonlocal flag
        logger.info("Pressed repeat button.")
        plt.close()
        flag = InteractiveButtonsEnum.REPEAT

    def save(event):
        nonlocal flag
        logger.info("Pressed save button.")
        plt.close()
        flag = InteractiveButtonsEnum.SAVE

    def skip(event):
        nonlocal flag
        logger.info("Pressed skip button.")
        plt.close()
        flag = InteractiveButtonsEnum.SKIP

    axcolor = "lightgoldenrodyellow"
    position = plt.axes((0.9, 0.1, 0.1, 0.04))
    button_save = Button(position, "Save", color=axcolor, hovercolor="0.975")
    button_save.on_clicked(save)
    position = plt.axes((0.9, 0.15, 0.1, 0.04))
    button_repeat = Button(position, "Repeat", color=axcolor, hovercolor="0.975")
    button_repeat.on_clicked(repeat)
    position = plt.axes((0.9, 0.2, 0.1, 0.04))
    button_skip = Button(position, "Skip", color=axcolor, hovercolor="0.975")
    button_skip.on_clicked(skip)
    plt.show()
    return flag

display_signals

display_signals(data: TabularDatasetData, *, figsize: tuple[int, int] = (6, 4), dpi: int = 150, colormap: str = 'viridis', x_label: str = 'Spectral bands', y_label: str = '', label_fontsize: int = 14, tick_params_label_size: int = 12, legend_fontsize: int = 10, legend_frameon: bool = True)
PARAMETER DESCRIPTION
data

TYPE: TabularDatasetData

figsize

TYPE: tuple[int, int] DEFAULT: (6, 4)

dpi

TYPE: int DEFAULT: 150

colormap

TYPE: str DEFAULT: 'viridis'

x_label

TYPE: str DEFAULT: 'Spectral bands'

y_label

TYPE: str DEFAULT: ''

label_fontsize

TYPE: int DEFAULT: 14

tick_params_label_size

TYPE: int DEFAULT: 12

legend_fontsize

TYPE: int DEFAULT: 10

legend_frameon

TYPE: bool DEFAULT: True

Source code in siapy/utils/plots.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def display_signals(
    data: TabularDatasetData,
    *,
    figsize: tuple[int, int] = (6, 4),
    dpi: int = 150,
    colormap: str = "viridis",
    x_label: str = "Spectral bands",
    y_label: str = "",
    label_fontsize: int = 14,
    tick_params_label_size: int = 12,
    legend_fontsize: int = 10,
    legend_frameon: bool = True,
):
    if not isinstance(data.target, ClassificationTarget):
        raise InvalidInputError(
            input_value=data.target,
            message="The target must be an instance of ClassificationTarget.",
        )

    signals = data.signals.copy()
    target = data.target.model_copy()
    y_data_encoded = target.value
    classes = list(target.encoding.to_dict().values())

    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    cmap = plt.get_cmap(colormap)
    unique_labels = np.unique(y_data_encoded)
    no_colors = len(unique_labels)

    if no_colors > 2:
        colors = list(cmap(np.linspace(0, 1, no_colors)))
    else:
        colors = ["darkgoldenrod", "forestgreen"]

    x_values = list(range(len(signals.columns)))

    grouped_data = signals.groupby(y_data_encoded.to_numpy())
    mean_values = grouped_data.mean()
    std_values = grouped_data.std()

    for idx in unique_labels:
        mean = mean_values.loc[idx].tolist()
        std = std_values.loc[idx].tolist()
        ax.plot(x_values, mean, color=colors[idx], label=classes[idx], alpha=0.6)
        ax.fill_between(
            x_values,
            [m - s for m, s in zip(mean, std)],
            [m + s for m, s in zip(mean, std)],
            color=colors[idx],
            alpha=0.2,
        )

    custom_lines = []
    for idx in unique_labels:
        custom_lines.append(Line2D([0], [0], color=colors[idx], lw=2))

    ax.set_ylabel(y_label, fontsize=label_fontsize)
    ax.set_xlabel(x_label, fontsize=label_fontsize)
    ax.tick_params(axis="both", which="major", labelsize=tick_params_label_size)
    ax.tick_params(axis="both", which="minor", labelsize=tick_params_label_size)
    # ax.set_ylim([0, 1])
    # ax.spines["bottom"].set_linewidth(2)
    # ax.spines["left"].set_linewidth(2)
    ax.spines["right"].set_linewidth(0)
    ax.spines["top"].set_linewidth(0)
    ax.set_xticks(x_values)
    ax.set_xticklabels(signals.columns, rotation=0)
    ax.legend(
        loc="upper left",
        fontsize=legend_fontsize,
        framealpha=1,
        frameon=legend_frameon,
    )
    plt.show()