sinapsis-data-visualization 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- __init__.py +0 -0
- sinapsis_data_visualization/__init__.py +0 -0
- sinapsis_data_visualization/helpers/__init__.py +0 -0
- sinapsis_data_visualization/helpers/annotation_drawer_tools.py +252 -0
- sinapsis_data_visualization/helpers/annotation_drawer_types.py +56 -0
- sinapsis_data_visualization/helpers/color_utils.py +108 -0
- sinapsis_data_visualization/helpers/detection_utils.py +124 -0
- sinapsis_data_visualization/helpers/plot_distributions.py +130 -0
- sinapsis_data_visualization/helpers/scikit_pca_analysis.py +51 -0
- sinapsis_data_visualization/templates/__init__.py +25 -0
- sinapsis_data_visualization/templates/base_annotation_drawer.py +103 -0
- sinapsis_data_visualization/templates/bbox_drawer.py +105 -0
- sinapsis_data_visualization/templates/data_distribution_visualization_template.py +245 -0
- sinapsis_data_visualization/templates/key_points_drawer.py +122 -0
- sinapsis_data_visualization/templates/label_drawer.py +292 -0
- sinapsis_data_visualization/templates/oriented_bbox_drawer.py +121 -0
- sinapsis_data_visualization/templates/segmentation_mask_drawer.py +137 -0
- sinapsis_data_visualization-0.1.0.dist-info/METADATA +674 -0
- sinapsis_data_visualization-0.1.0.dist-info/RECORD +21 -0
- sinapsis_data_visualization-0.1.0.dist-info/WHEEL +5 -0
- sinapsis_data_visualization-0.1.0.dist-info/top_level.txt +2 -0
__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from typing import cast
|
|
3
|
+
|
|
4
|
+
import cv2
|
|
5
|
+
import numpy as np
|
|
6
|
+
from sinapsis_core.data_containers.annotations import BoundingBox, ImageAnnotations
|
|
7
|
+
|
|
8
|
+
from sinapsis_data_visualization.helpers.annotation_drawer_types import (
|
|
9
|
+
TextInstanceProperties,
|
|
10
|
+
TextStyle,
|
|
11
|
+
)
|
|
12
|
+
from sinapsis_data_visualization.helpers.color_utils import RGB_TYPE
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_text_coordinates(
|
|
16
|
+
image_shape: tuple[int, int],
|
|
17
|
+
text_coordinates: tuple[int, int],
|
|
18
|
+
text_box_to_border_offset: float = 0.01,
|
|
19
|
+
label_position: str = "top_right",
|
|
20
|
+
) -> tuple[int, int]:
|
|
21
|
+
"""
|
|
22
|
+
Compute x,y coordinates for text label according to selected label position.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
image_shape (tuple[int, int]): shape if the target image in width,
|
|
26
|
+
height coordinates.
|
|
27
|
+
text_coordinates (tuple[int, int]): coordinates where the text is
|
|
28
|
+
to be placed in width, height.
|
|
29
|
+
text_box_to_border_offset (float, optional): Weight to control offset of
|
|
30
|
+
text box to the image border. It defaults to 0.01.
|
|
31
|
+
label_position (str): Indicate location of label text box. Defaults to: "top_right"
|
|
32
|
+
Available options: "top_left", "top_right".
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
tuple[int, int]: Tuple of computed x and y coordinates.
|
|
36
|
+
"""
|
|
37
|
+
image_width, image_height = image_shape
|
|
38
|
+
text_height, text_width = text_coordinates
|
|
39
|
+
x, y = image_shape
|
|
40
|
+
match label_position:
|
|
41
|
+
case "top_left":
|
|
42
|
+
x = int(image_width * text_box_to_border_offset)
|
|
43
|
+
y = int(image_height * text_box_to_border_offset + text_height)
|
|
44
|
+
|
|
45
|
+
case "top_right":
|
|
46
|
+
x = int(
|
|
47
|
+
max(
|
|
48
|
+
(image_width * text_box_to_border_offset),
|
|
49
|
+
image_width - text_width - (image_width * text_box_to_border_offset),
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
y = int(image_height * text_box_to_border_offset + text_height)
|
|
53
|
+
return x, y
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_dynamic_text_properties(image: np.ndarray) -> tuple[float, float]:
|
|
57
|
+
"""Compute font size and font thickness according to image shape
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
image (np.ndarray): image to be drawn
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
tuple[float, float]: Tuple of computed font scale and font thickness
|
|
64
|
+
"""
|
|
65
|
+
size = max(round(sum(image.shape) / 2 * 0.003), 2)
|
|
66
|
+
font_thickness = max(size - 1, 1)
|
|
67
|
+
font_scale = size / 3
|
|
68
|
+
return font_scale, font_thickness
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_numeric_str(label: str, numeric_val: float | int) -> str:
|
|
72
|
+
"""Writes numeric value of label as string
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
label (str): label of the annotation
|
|
76
|
+
numeric_val (float|int): numeric_val to convert to string
|
|
77
|
+
Returns
|
|
78
|
+
string label
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
extra_text = f"{label}: {numeric_val:.2f}%" if isinstance(numeric_val, float) else f"{label}: {numeric_val}"
|
|
82
|
+
return extra_text
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get_text_size(text: str, text_style: TextStyle) -> tuple[int, int]:
|
|
86
|
+
"""
|
|
87
|
+
Returns the width and height of the text to be drawn.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
text (str): The text, whose size is to be calculated.
|
|
91
|
+
text_style (TextStyle): Properties of the text: font, size and thickness.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
tuple[int, int]: The (width, height) of the text.
|
|
95
|
+
"""
|
|
96
|
+
text_size = cv2.getTextSize(
|
|
97
|
+
text,
|
|
98
|
+
text_style.font,
|
|
99
|
+
text_style.font_scale,
|
|
100
|
+
text_style.thickness,
|
|
101
|
+
)[0]
|
|
102
|
+
text_size = cast(tuple[int, int], text_size)
|
|
103
|
+
return text_size
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def draw_text(
|
|
107
|
+
image: np.ndarray,
|
|
108
|
+
text: str,
|
|
109
|
+
text_properties: TextInstanceProperties,
|
|
110
|
+
text_style: TextStyle,
|
|
111
|
+
) -> np.ndarray:
|
|
112
|
+
"""
|
|
113
|
+
Draws the specified text on the image at the given position.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
image (np.ndarray): The image to draw on.
|
|
117
|
+
text (str): The text to be drawn.
|
|
118
|
+
text_properties (TextInstanceProperties): The properties of the text (position, color).
|
|
119
|
+
text_style (TextStyle): Properties of the text: font, size and thickness.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
np.ndarray: The image with the text drawn.
|
|
123
|
+
"""
|
|
124
|
+
cv2.putText(
|
|
125
|
+
image,
|
|
126
|
+
text,
|
|
127
|
+
(
|
|
128
|
+
int(text_properties.x_position),
|
|
129
|
+
int(text_properties.y_position),
|
|
130
|
+
),
|
|
131
|
+
text_style.font,
|
|
132
|
+
text_style.font_scale,
|
|
133
|
+
text_properties.text_color,
|
|
134
|
+
text_style.thickness,
|
|
135
|
+
)
|
|
136
|
+
return image
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def draw_extra_labels(
|
|
140
|
+
image: np.ndarray,
|
|
141
|
+
bbox: BoundingBox,
|
|
142
|
+
extra_str_repr: list[str],
|
|
143
|
+
text_y_offsets: list[int],
|
|
144
|
+
text_color: RGB_TYPE,
|
|
145
|
+
text_style: TextStyle,
|
|
146
|
+
) -> np.ndarray:
|
|
147
|
+
"""Draws additional labels (e.g., confidence score, extra annotations)
|
|
148
|
+
under the primary label.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
image (np.ndarray): The image to draw on.
|
|
152
|
+
bbox (BoundingBox): Bounding box with the X-coordinate and
|
|
153
|
+
Y-coordinates of the starting point for the text.
|
|
154
|
+
|
|
155
|
+
extra_str_repr (list[str]): List of extra label strings.
|
|
156
|
+
text_y_offsets (list[int]): List of Y offsets
|
|
157
|
+
text_color (RGB_TYPE): The color of the label text.
|
|
158
|
+
text_style (TextStyle): Properties of the text: font,
|
|
159
|
+
scale, and thickness.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
np.ndarray: The image with the extra labels drawn.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
y_position = int(bbox.y)
|
|
166
|
+
|
|
167
|
+
for str_repr, y_offset in zip(extra_str_repr, text_y_offsets):
|
|
168
|
+
y_position -= y_offset
|
|
169
|
+
image = draw_text(
|
|
170
|
+
image,
|
|
171
|
+
str_repr,
|
|
172
|
+
TextInstanceProperties(bbox.x, y_position, text_color),
|
|
173
|
+
text_style,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return image
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def draw_annotation_rectangle(
|
|
180
|
+
image: np.ndarray,
|
|
181
|
+
bbox: BoundingBox,
|
|
182
|
+
ann_color: RGB_TYPE,
|
|
183
|
+
text_h: float,
|
|
184
|
+
text_w: float,
|
|
185
|
+
) -> np.ndarray:
|
|
186
|
+
"""Draws the background rectangle for the label.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
image (np.ndarray): The image to draw on.
|
|
190
|
+
bbox (BoundingBox): The bounding box for positioning the rectangle.
|
|
191
|
+
ann_color (RGB_TYPE): The color of the rectangle.
|
|
192
|
+
text_h (float): The height of the text label.
|
|
193
|
+
text_w (float): The width of the text label.
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
np.ndarray: The image with the background rectangle drawn.
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
cv2.rectangle(
|
|
200
|
+
image,
|
|
201
|
+
(int(bbox.x), int(bbox.y - text_h)),
|
|
202
|
+
(int(bbox.x + text_w), int(bbox.y + 12)),
|
|
203
|
+
ann_color,
|
|
204
|
+
-1,
|
|
205
|
+
)
|
|
206
|
+
return image
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def get_extra_ann_labels(
|
|
210
|
+
annotation: ImageAnnotations,
|
|
211
|
+
text_w: int,
|
|
212
|
+
text_h: int,
|
|
213
|
+
text_style: TextStyle,
|
|
214
|
+
spacing: int = 5,
|
|
215
|
+
) -> tuple[list[int], list[str], int, int]:
|
|
216
|
+
"""
|
|
217
|
+
Extracts additional annotation labels and calculates their dimensions
|
|
218
|
+
and offsets for rendering.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
annotation (ImageAnnotations): The annotation object containing
|
|
222
|
+
extra label information.
|
|
223
|
+
text_w (int): The initial width of the text bounding box.
|
|
224
|
+
text_h (int): The initial height of the text bounding box.
|
|
225
|
+
text_style (TextStyle): Properties for the text: font, size
|
|
226
|
+
and thickness.
|
|
227
|
+
spacing (int, optional): The vertical spacing between labels.
|
|
228
|
+
The default value is 5.
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
tuple[list[int], list[str]]:
|
|
232
|
+
- 'list[int]': A list of vertical offsets for each
|
|
233
|
+
additional label.
|
|
234
|
+
- 'list[str]': A list of formatted strings for the
|
|
235
|
+
additional labels.
|
|
236
|
+
"""
|
|
237
|
+
text_y_offsets = []
|
|
238
|
+
extra_str_repr = []
|
|
239
|
+
for label_k, label_v in annotation.extra_labels.items():
|
|
240
|
+
extra_text: str = label_k
|
|
241
|
+
if isinstance(label_v, (float, int)):
|
|
242
|
+
extra_text = get_numeric_str(extra_text, label_v)
|
|
243
|
+
else:
|
|
244
|
+
extra_text = f"{label_k}: {label_v}"
|
|
245
|
+
extra_text_w, extra_text_h = get_text_size(extra_text, text_style)
|
|
246
|
+
|
|
247
|
+
extra_text_h += spacing
|
|
248
|
+
text_h += extra_text_h
|
|
249
|
+
text_w = max(extra_text_w, text_w)
|
|
250
|
+
text_y_offsets.append(extra_text_h)
|
|
251
|
+
extra_str_repr.append(extra_text)
|
|
252
|
+
return text_y_offsets, extra_str_repr, text_h, text_w
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from pydantic.dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
RGB_TYPE = tuple[int, int, int] | tuple[float, float, float]
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class KeyPointAppearance:
|
|
9
|
+
"""
|
|
10
|
+
Appearance of the keypoint
|
|
11
|
+
|
|
12
|
+
color (RGB_TYPE): color of the bounding box
|
|
13
|
+
thickness (Optional[int]): Line thickness.
|
|
14
|
+
The default value is 2.
|
|
15
|
+
radius (Optional[int], optional): radius o:75
|
|
16
|
+
f the circle. The default value is 2.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
color: RGB_TYPE
|
|
20
|
+
thickness: int = 2
|
|
21
|
+
radius: int = 2
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class TextStyle:
|
|
26
|
+
"""
|
|
27
|
+
font (int): Style of font
|
|
28
|
+
Available options:
|
|
29
|
+
FONT_HERSHEY_SIMPLEX = 0.
|
|
30
|
+
FONT_HERSHEY_PLAIN = 1.
|
|
31
|
+
FONT_HERSHEY_DUPLEX = 2.
|
|
32
|
+
FONT_HERSHEY_COMPLEX = 3.
|
|
33
|
+
FONT_HERSHEY_TRIPLEX = 4.
|
|
34
|
+
FONT_HERSHEY_COMPLEX_SMALL = 5.
|
|
35
|
+
FONT_HERSHEY_SCRIPT_SIMPLEX = 6.
|
|
36
|
+
FONT_HERSHEY_SCRIPT_COMPLEX = 7.
|
|
37
|
+
font_scale (float): Scale of font
|
|
38
|
+
thickness (int): Thickness of font
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
font: int = 0
|
|
42
|
+
font_scale: float = 0.5
|
|
43
|
+
thickness: int = 2
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class TextInstanceProperties:
|
|
48
|
+
"""
|
|
49
|
+
x_position (float): x coordinate for text
|
|
50
|
+
y_position (float): y coordinate for text
|
|
51
|
+
text_color (RGB_TYPE): color for text string
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
x_position: float
|
|
55
|
+
y_position: float
|
|
56
|
+
text_color: RGB_TYPE
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
import colorsys
|
|
3
|
+
import math
|
|
4
|
+
import random
|
|
5
|
+
|
|
6
|
+
from matplotlib import colors
|
|
7
|
+
|
|
8
|
+
from sinapsis_data_visualization.helpers.annotation_drawer_types import RGB_TYPE
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build_color_map(color_names: list[str] | None = None, shuffle: bool = True) -> dict[int, RGB_TYPE]:
|
|
12
|
+
"""
|
|
13
|
+
Method to generate a mapping of indices to RGB color values.
|
|
14
|
+
By default, it uses the CSS4 color names provided by Matplotlib,
|
|
15
|
+
but a custom list of color names can be supplied.
|
|
16
|
+
Optionally, the colors can be shuffled to randomize their order in the mapping.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
color_names (list[str] | None): A list of color names as strings. If 'None',
|
|
20
|
+
the full list of CSS4 color names is used.
|
|
21
|
+
shuffle (bool): If 'True', the order of colors in the color map is randomized. Defaults to 'True'.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
dict[int, RGB_TYPE]: A dictionary where keys are integers (starting from 0) and values
|
|
25
|
+
are RGB color tuples with values normalized to the 0-255 range.
|
|
26
|
+
|
|
27
|
+
"""
|
|
28
|
+
color_keys = list(colors.CSS4_COLORS.keys()) if color_names is None else color_names
|
|
29
|
+
if shuffle:
|
|
30
|
+
random.shuffle(color_keys)
|
|
31
|
+
color_dict: dict[int, RGB_TYPE] = {}
|
|
32
|
+
for idx, color_name in enumerate(color_keys):
|
|
33
|
+
normalized_color = colors.to_rgb(color_name)
|
|
34
|
+
color_dict[idx] = (
|
|
35
|
+
normalized_color[0] * 255,
|
|
36
|
+
normalized_color[1] * 255,
|
|
37
|
+
normalized_color[2] * 255,
|
|
38
|
+
)
|
|
39
|
+
return color_dict
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_color_rgb_tuple(
|
|
43
|
+
color_map: dict[int, RGB_TYPE],
|
|
44
|
+
class_id: int | None = None,
|
|
45
|
+
randomized: bool = True,
|
|
46
|
+
) -> RGB_TYPE:
|
|
47
|
+
"""
|
|
48
|
+
Method to fetch the RGB color combination associated with a specific class_id
|
|
49
|
+
from the provided color_map dictionary. If 'class_id' is not provided, or if it is
|
|
50
|
+
invalid, a random color is selected from the color_map dictionary. If randomized
|
|
51
|
+
is True, a random color is selected from the color_map dictionary.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
color_map (dict[int, RGB_TYPE]): A dictionary mapping class IDs (integers)
|
|
55
|
+
to RGB color tuples.
|
|
56
|
+
class_id (int | None): The class ID for which the color is requested. If 'None'
|
|
57
|
+
or invalid, a random color is selected. Defaults to 'None'.
|
|
58
|
+
randomized (bool): If 'True', the function ignores the provided 'class_id'
|
|
59
|
+
and returns a random color from the color map. Defaults to 'True'.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
RGB_TYPE: A tuple representing the RGB color, where each component is an
|
|
63
|
+
integer in the range 0-255.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: If 'color_map' is empty or invalid.
|
|
67
|
+
"""
|
|
68
|
+
if class_id is None or isinstance(class_id, str) or randomized:
|
|
69
|
+
class_id = random.randrange(0, len(color_map))
|
|
70
|
+
try:
|
|
71
|
+
return color_map[class_id]
|
|
72
|
+
except IndexError:
|
|
73
|
+
return color_map[random.randrange(0, len(color_map))]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_light_colour(rgb: RGB_TYPE) -> bool:
|
|
77
|
+
"""Checks the brightness of image to determine whether it is above a certain
|
|
78
|
+
threshold.
|
|
79
|
+
Args:
|
|
80
|
+
rgb (RGB_TYPE): Color model for RED, GREEN and BLUE
|
|
81
|
+
Returns
|
|
82
|
+
True if brightness is above the threshold. False otherwise
|
|
83
|
+
"""
|
|
84
|
+
red, green, blue = rgb
|
|
85
|
+
perceived_brightness = math.sqrt(0.299 * (red * red) + 0.587 * (green * green) + 0.114 * (blue * blue))
|
|
86
|
+
return perceived_brightness > 127.5
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def darken_or_lighten_color(rgb: RGB_TYPE, dark_scale: float = 1.5, light_scale: float = 0.2) -> RGB_TYPE:
|
|
90
|
+
"""Darkens or lightens the color based on brightness of the input color
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
rgb (RGB_TYPE): Color model for RED, GREEN and BLUE
|
|
94
|
+
dark_scale (float): the value of scale for dark color.
|
|
95
|
+
light_scale (float): the value of scale for lighter colors.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
RGB_TYPE: New RGB model for image
|
|
99
|
+
"""
|
|
100
|
+
scale = light_scale if is_light_colour(rgb) else dark_scale
|
|
101
|
+
max_rgb_val = 255.0
|
|
102
|
+
red, green, blue = rgb
|
|
103
|
+
|
|
104
|
+
hue, luminance, saturation = colorsys.rgb_to_hls(red / max_rgb_val, green / max_rgb_val, blue / max_rgb_val)
|
|
105
|
+
|
|
106
|
+
lightness = max(0, min(1, int(luminance * scale)))
|
|
107
|
+
red, green, blue = colorsys.hls_to_rgb(hue, lightness, saturation)
|
|
108
|
+
return int(red * 255), int(green * 255), int(blue * 255)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sinapsis_core.data_containers.annotations import BoundingBox
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def bbox_xyxy_to_xywh(xyxy_bbox: np.ndarray) -> tuple[float, float, float, float]:
|
|
8
|
+
"""
|
|
9
|
+
Converts the format for defining bounding boxes from xyxy to xywh
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
xyxy_bbox (np.ndarray): the bbox object in (x_min, y_min),
|
|
13
|
+
(x_max, y_max) coordinates
|
|
14
|
+
Returns:
|
|
15
|
+
(tuple[float, float, float, float]) : the coordinates of the bbox
|
|
16
|
+
in (x, y), (width and height) coordinates.
|
|
17
|
+
"""
|
|
18
|
+
x = float(xyxy_bbox[0])
|
|
19
|
+
y = float(xyxy_bbox[1])
|
|
20
|
+
w = float(xyxy_bbox[2]) - x
|
|
21
|
+
h = float(xyxy_bbox[3]) - y
|
|
22
|
+
return x, y, w, h
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def bbox_xywh_to_xyxy(xywh_bbox: BoundingBox) -> tuple[float, float, float, float]:
|
|
26
|
+
"""
|
|
27
|
+
Converts the format for defining bounding boxes from xywh to xyxy
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
xywh_bbox (BoundingBox): The BoundingBox object in format x, y, w, h
|
|
31
|
+
Returns:
|
|
32
|
+
(tuple[float, float, float, float]): the coordinates of the bbox
|
|
33
|
+
in x_min, y_min, x_max, y_max
|
|
34
|
+
|
|
35
|
+
"""
|
|
36
|
+
x1 = float(xywh_bbox.x)
|
|
37
|
+
y1 = float(xywh_bbox.y)
|
|
38
|
+
x2 = float(xywh_bbox.w) + x1
|
|
39
|
+
y2 = float(xywh_bbox.h) + y1
|
|
40
|
+
return x1, y1, x2, y2
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def bbox_iou_batch(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray:
|
|
44
|
+
"""Computes the Intersection over Union (IoU) metric.
|
|
45
|
+
|
|
46
|
+
This method calculates the IoU for each pair of bounding boxes in
|
|
47
|
+
'boxes_a' and 'boxes_b'. IoU measures the overlap between two bounding
|
|
48
|
+
boxes as the ratio of their intersection area to their combined area.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
boxes_a (np.ndarray): An array of shape '(N, 4)' representing N bounding boxes.
|
|
52
|
+
boxes_b (np.ndarray): An array of shape '(M, 4)' representing M bounding boxes.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
(np.ndarray): A 2D array containing the IoU values for each i, j values
|
|
56
|
+
of boxes_a and boxes_b, respectively.
|
|
57
|
+
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def box_area(box: np.ndarray) -> np.ndarray:
|
|
61
|
+
"""
|
|
62
|
+
Calculate the area of a bounding box.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
box (np.ndarray): A 2D array where each row represents a bounding box
|
|
66
|
+
in the format '[x_min, y_min, x_max, y_max]'.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
(np.ndarray): The area of the bounding box
|
|
70
|
+
"""
|
|
71
|
+
area: np.ndarray = (box[2] - box[0]) * (box[3] - box[1])
|
|
72
|
+
return area
|
|
73
|
+
|
|
74
|
+
area_a = box_area(boxes_a.T)
|
|
75
|
+
area_b = box_area(boxes_b.T)
|
|
76
|
+
|
|
77
|
+
top_left = np.maximum(boxes_a[:, None, :2], boxes_b[:, :2])
|
|
78
|
+
bottom_right = np.minimum(boxes_a[:, None, 2:], boxes_b[:, 2:])
|
|
79
|
+
|
|
80
|
+
area_inter = np.prod(np.clip(bottom_right - top_left, a_min=0, a_max=None), 2)
|
|
81
|
+
|
|
82
|
+
iou: np.ndarray = area_inter / (area_a[:, None] + area_b - area_inter)
|
|
83
|
+
return iou
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def non_max_suppression(predictions: np.ndarray, iou_threshold: float = 0.5) -> np.ndarray:
|
|
87
|
+
"""
|
|
88
|
+
Implements the non-maximum suppression algorithm for removal of redundant
|
|
89
|
+
bounding boxes. The goal of this method is to retain the most relevant
|
|
90
|
+
bounding boxes for each object.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
predictions (np.ndarray): Array containing the coordinates of the bounding
|
|
94
|
+
box and the confidence and category in each case, in the form:
|
|
95
|
+
'[x_min, y_min, x_max, y_max, confidence, category]'.
|
|
96
|
+
iou_threshold (float): The IoU threshold above which a bounding box is
|
|
97
|
+
considered redundant if it belongs to the same category. Defaults to '0.5'.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
np.ndarray: A boolean array where 'True' indicates that
|
|
101
|
+
the corresponding bounding box is kept, and 'False' indicates
|
|
102
|
+
it is suppressed.
|
|
103
|
+
|
|
104
|
+
"""
|
|
105
|
+
rows, _ = predictions.shape
|
|
106
|
+
|
|
107
|
+
sort_index = np.flip(predictions[:, 4].argsort())
|
|
108
|
+
predictions = predictions[sort_index]
|
|
109
|
+
|
|
110
|
+
boxes = predictions[:, :4]
|
|
111
|
+
categories = predictions[:, 5]
|
|
112
|
+
ious = bbox_iou_batch(boxes, boxes) - np.eye(rows)
|
|
113
|
+
|
|
114
|
+
keep = np.ones(rows, dtype=bool)
|
|
115
|
+
|
|
116
|
+
for index, (iou, category) in enumerate(zip(ious, categories)):
|
|
117
|
+
if not keep[index]:
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
condition = (iou > iou_threshold) & (categories == category)
|
|
121
|
+
keep = keep & ~condition
|
|
122
|
+
|
|
123
|
+
out: np.ndarray = keep[sort_index.argsort()]
|
|
124
|
+
return out
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from typing import Sequence
|
|
3
|
+
|
|
4
|
+
import matplotlib
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import numpy as np
|
|
7
|
+
from sinapsis_core.utils.logging_utils import sinapsis_logger
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def plot_distribution(
|
|
11
|
+
figure: matplotlib.figure.Figure,
|
|
12
|
+
labels: Sequence[str] | np.ndarray,
|
|
13
|
+
counts: list[float] | np.ndarray,
|
|
14
|
+
plot_type: str,
|
|
15
|
+
kwargs: dict,
|
|
16
|
+
) -> matplotlib.figure.Figure:
|
|
17
|
+
"""
|
|
18
|
+
Base method to plot a distribution.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
figure (matplotlib.figure.Figure): Original figure to add the plot on
|
|
22
|
+
labels (str | int): labels to group the data by
|
|
23
|
+
counts (list[float] | np.ndarray): number of
|
|
24
|
+
incidences a certain label is repeated
|
|
25
|
+
plot_type (str): Type of plot to be drawn on the figure. Options are: box,
|
|
26
|
+
histogram, pie chat and clustering
|
|
27
|
+
kwargs (dict): Extra kwargs for the plot, including color, size, symbol, etc.
|
|
28
|
+
returns:
|
|
29
|
+
matplotlib.figure.Figure : Modified figure with the actual distribution plotted
|
|
30
|
+
"""
|
|
31
|
+
if (isinstance(labels, np.ndarray) and not labels.any()) or (isinstance(labels, Sequence) and not labels):
|
|
32
|
+
sinapsis_logger.warning("No labels found to plot.")
|
|
33
|
+
|
|
34
|
+
elif (isinstance(counts, np.ndarray) and not counts.any()) or (isinstance(counts, list) and not labels):
|
|
35
|
+
sinapsis_logger.warning("No counts found to plot.")
|
|
36
|
+
|
|
37
|
+
else:
|
|
38
|
+
plot_map[plot_type](labels, counts, kwargs)
|
|
39
|
+
return figure
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def plot_histogram(labels: Sequence[str], counts: list[float] | np.ndarray, kwargs: dict) -> None:
|
|
43
|
+
"""
|
|
44
|
+
Plots a histogram of the data.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
|
|
48
|
+
labels (Sequence[str]): The categories or bins for the histogram.
|
|
49
|
+
counts (list [float] | np.ndarray): The values corresponding to each label.
|
|
50
|
+
Represents the height of the bars.
|
|
51
|
+
**kwargs (dic): Additional keyword arguments passed to 'matplotlib.pyplot.bar'.
|
|
52
|
+
|
|
53
|
+
The method plots a bar plot
|
|
54
|
+
"""
|
|
55
|
+
plt.bar(labels, counts, **kwargs)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def plot_boxplot(labels: Sequence[str], counts: list[float] | np.ndarray, kwargs: dict) -> None:
|
|
59
|
+
"""
|
|
60
|
+
Plots a boxplot.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
labels (Sequence[str]): The categories or labels for the data.
|
|
64
|
+
counts (list[float] | np.ndarray): The values representing the
|
|
65
|
+
frequency of data points for each label.
|
|
66
|
+
**kwargs (dict): Additional keyword arguments passed to
|
|
67
|
+
'matplotlib.pyplot.boxplot'.
|
|
68
|
+
|
|
69
|
+
Note:
|
|
70
|
+
|
|
71
|
+
Logs an error if the provided arguments are incompatible with
|
|
72
|
+
'plt.boxplot'.
|
|
73
|
+
"""
|
|
74
|
+
data_points = []
|
|
75
|
+
|
|
76
|
+
for label, count in zip(labels, counts):
|
|
77
|
+
data_points.extend([label] * count)
|
|
78
|
+
try:
|
|
79
|
+
plt.boxplot(x=data_points, label=labels, **kwargs)
|
|
80
|
+
except ValueError as e:
|
|
81
|
+
sinapsis_logger.logger.error(f"Incompatible arguments for boxplot: {e}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def plot_piechart(labels: Sequence[str], counts: list[float] | np.ndarray, kwargs: dict) -> None:
|
|
85
|
+
"""
|
|
86
|
+
Plots a basic pie chart.
|
|
87
|
+
Args:
|
|
88
|
+
labels (Sequence[str]): The labels for each section of
|
|
89
|
+
the pie chart.
|
|
90
|
+
counts (list[float], np.ndarray): The values representing
|
|
91
|
+
the size of each section.
|
|
92
|
+
**kwargs (dict): Additional keyword arguments passed to
|
|
93
|
+
'matplotlib.pyplot.pie'.
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
Notes:
|
|
97
|
+
The function supports various `matplotlib` pie chart customization options,
|
|
98
|
+
such as 'autopct', 'startangle', and 'rotatelabels'.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
plt.pie(
|
|
102
|
+
counts,
|
|
103
|
+
labels=labels,
|
|
104
|
+
**kwargs,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def plot_cluster(labels: Sequence[str], counts: list[float] | np.ndarray, kwargs: dict) -> None:
|
|
109
|
+
"""
|
|
110
|
+
Plots a scatter plot for clustered data.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
labels (Sequence[str]): Cluster labels for each data point.
|
|
114
|
+
counts (list[float] | np.ndarray): A 2D array with shape (n_samples, 2),
|
|
115
|
+
where each row represents a data point's coordinates.
|
|
116
|
+
**kwargs (dict): Additional keyword arguments passed to
|
|
117
|
+
'matplotlib.pyplot.scatter'.
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
"""
|
|
121
|
+
counts = np.asarray(counts)
|
|
122
|
+
plt.scatter(counts[:, 0], counts[:, 1], c=labels, **kwargs)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
plot_map: dict = {
|
|
126
|
+
"histogram": plot_histogram,
|
|
127
|
+
"pie_chart": plot_piechart,
|
|
128
|
+
"box_plot": plot_boxplot,
|
|
129
|
+
"k_means_clustering": plot_cluster,
|
|
130
|
+
}
|