1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
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
124
125
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
196
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
230
231
232
233
234
235
236
|
"""
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__author__ = "Théo de la Hogue"
__credits__ = []
__copyright__ = "Copyright 2023, Ecole Nationale de l'Aviation Civile (ENAC)"
__license__ = "GPLv3"
from typing import Self
from argaze import DataFeatures
from argaze.AreaOfInterest import AOIFeatures, AOI3DScene
from argaze import GazeFeatures
import cv2
import numpy
from xml.dom import minidom
class AOI2DScene(AOIFeatures.AOIScene):
"""Define AOI 2D scene."""
def __init__(self, aoi_2d: dict = None):
super().__init__(2, aoi_2d)
@classmethod
def from_svg(self, svg_filepath: str) -> Self:
"""
Load areas from .svg file.
Parameters:
svg_filepath: path to svg file
!!! note
Available SVG elements are: path, rect and circle.
!!! warning
Available SVG path d-string commands are: MoveTo (M) LineTo (L) and ClosePath (Z) commands.
"""
with minidom.parse(svg_filepath) as description_file:
new_areas = {}
# Load SVG path
for path in description_file.getElementsByTagName('path'):
# Convert d-string into array
d_string = path.getAttribute('d')
assert(d_string[0] == 'M')
assert(d_string[-1] == 'Z')
points = [(float(x), float(y)) for x, y in [p.split(',') for p in d_string[1:-1].split('L')]]
new_areas[path.getAttribute('id')] = AOIFeatures.AreaOfInterest(points)
# Load SVG rect
for rect in description_file.getElementsByTagName('rect'):
# Convert rect element into dict
rect_dict = {
"Rectangle": {
'x': float(rect.getAttribute('x')),
'y': float(rect.getAttribute('y')),
'width': float(rect.getAttribute('width')),
'height': float(rect.getAttribute('height'))
}
}
new_areas[rect.getAttribute('id')] = AOIFeatures.AreaOfInterest.from_dict(rect_dict)
# Load SVG circle
for circle in description_file.getElementsByTagName('circle'):
# Convert circle element into dict
circle_dict = {
"Circle": {
'cx': float(circle.getAttribute('cx')),
'cy': float(circle.getAttribute('cy')),
'radius': float(circle.getAttribute('r'))
}
}
new_areas[circle.getAttribute('id')] = AOIFeatures.AreaOfInterest.from_dict(circle_dict)
# Load SVG ellipse
for ellipse in description_file.getElementsByTagName('ellipse'):
# Convert ellipse element into dict
ellipse_dict = {
"Ellipse": {
'cx': float(circle.getAttribute('cx')),
'cy': float(circle.getAttribute('cy')),
'rx': float(circle.getAttribute('rx')),
'ry': float(circle.getAttribute('ry'))
}
}
new_areas[ellipse.getAttribute('id')] = AOIFeatures.AreaOfInterest.from_dict(ellipse_dict)
return AOI2DScene(new_areas)
def draw(self, image: numpy.array, draw_aoi: dict = None, exclude=[]):
"""Draw AOI polygons on image.
Parameters:
draw_aoi: AOIFeatures.AOI.draw parameters (if None, no aoi is drawn)
"""
for name, aoi in self.items():
if name in exclude:
continue
if draw_aoi:
aoi.draw(image, **draw_aoi)
def raycast(self, pointer:tuple) -> tuple[str, "AOIFeatures.AreaOfInterest", bool]:
"""Iterate over aoi to know which aoi is matching the given pointer position.
Returns:
aoi name
aoi object
matching status
"""
for name, aoi in self.items():
matching = aoi.contains_point(pointer)
yield name, aoi, matching
def draw_raycast(self, image: numpy.array, pointer:tuple, exclude=[], base_color=(0, 0, 255), matching_color=(0, 255, 0)):
"""Draw AOI with their matching status."""
for name, aoi, matching in self.raycast(pointer):
if name in exclude:
continue
color = matching_color if matching else base_color
if matching:
top_left_corner_pixel = numpy.rint(aoi.clockwise()[0]).astype(int)
cv2.putText(image, name, top_left_corner_pixel, cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)
# Draw form
aoi.draw(image, color)
def circlecast(self, center:tuple, radius:float) -> tuple[str, "AOIFeatures.AreaOfInterest", numpy.array, float, float]:
"""Iterate over areas to know which aoi is matched circle.
Returns:
aoi name
aoi object
matching region points
ratio of matched region area relatively to aoi area
ratio of matched region area relatively to circle area
"""
for name, aoi in self.items():
matched_region, aoi_ratio, circle_ratio = aoi.circle_intersection(center, radius)
yield name, aoi, matched_region, aoi_ratio, circle_ratio
'''DEPRECATED: but maybe still usefull?
def reframe(self, aoi: AOIFeatures.AreaOfInterest, size: tuple) -> AOI2DScene:
"""
Reframe whole scene to a scene bounded by a 4 vertices 2D AOI.
Parameters:
aoi: 4 vertices 2D AOI used to reframe scene
size: size of reframed scene
Returns:
reframed AOI 2D scene
"""
assert(aoi.dimension == 2)
assert(aoi.points_number == 4)
# Edit affine transformation (M) allowing to transform source axis (Src) into destination axis (Dst)
Src = aoi.clockwise().astype(numpy.float32)
Src_origin = Src[0]
Src = Src - Src_origin
Dst = numpy.float32([[0, 0], [size[0], 0], [size[0], size[1]], [0, size[1]]])
M = cv2.getAffineTransform(Src[:3], Dst[:3])[:, :2]
# Apply affine transformationto each AOI
aoi2D_scene = AOI2DScene()
for name, aoi2D in self.items():
aoi2D_scene[name] = numpy.matmul(aoi2D - Src_origin, M.T)
return aoi2D_scene
'''
def dimensionalize(self, rectangle_3d: AOIFeatures.AreaOfInterest, size: tuple) -> AOI3DScene.AOI3DScene:
"""
Convert to 3D scene considering it is inside of 3D rectangular frame.
Parameters:
rectangle_3d: rectangle 3D AOI to use as referential plane
size: size of the frame in pixel
Returns:
AOI 3D scene
"""
assert(rectangle_3d.dimension == 3)
assert(rectangle_3d.points_number == 4)
# Vectorize outter_axis function
vfunc = numpy.vectorize(rectangle_3d.outter_axis)
# Prepare new AOI 3D scene
aoi3D_scene = AOI3DScene.AOI3DScene()
for name, aoi2D in self.items():
X, Y = (aoi2D / size).T
aoi3D_scene[name] = numpy.array(vfunc(X, Y)).T.view(AOIFeatures.AreaOfInterest)
return aoi3D_scene
|