-
Notifications
You must be signed in to change notification settings - Fork 53
/
shape.py
326 lines (275 loc) · 10.4 KB
/
shape.py
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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import copy
import math
from qtpy import QtCore
from qtpy import QtGui
import labelme.utils
# TODO(unknown):
# - [opt] Store paths instead of creating new ones at each paint.
DEFAULT_LINE_COLOR = QtGui.QColor(0, 255, 0, 128) # bf hovering
DEFAULT_FILL_COLOR = QtGui.QColor(0, 255, 0, 128) # hovering
DEFAULT_SELECT_LINE_COLOR = QtGui.QColor(255, 255, 255) # selected
DEFAULT_SELECT_FILL_COLOR = QtGui.QColor(0, 255, 0, 155) # selected
DEFAULT_VERTEX_FILL_COLOR = QtGui.QColor(0, 255, 0, 255) # hovering
DEFAULT_HVERTEX_FILL_COLOR = QtGui.QColor(255, 255, 255, 255) # hovering
DEFAULT_Negative_FILL_COLOR = QtGui.QColor(255, 0, 0) # hovering
class Shape(object):
# Render handles as squares
P_SQUARE = 0
# Render handles as circles
P_ROUND = 1
# Flag for the handles we would move if dragging
MOVE_VERTEX = 0
# Flag for all other handles on the curent shape
NEAR_VERTEX = 1
# The following class variables influence the drawing of all shape objects.
line_color = DEFAULT_LINE_COLOR
fill_color = DEFAULT_FILL_COLOR
select_line_color = DEFAULT_SELECT_LINE_COLOR
select_fill_color = DEFAULT_SELECT_FILL_COLOR
vertex_fill_color = DEFAULT_VERTEX_FILL_COLOR
nvertex_fill_color = DEFAULT_Negative_FILL_COLOR
hvertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR
point_type = P_ROUND
point_size = 3
scale = 1.0
def __init__(
self,
label=None,
line_color=None,
shape_type=None,
flags=None,
group_id=None,
):
self.label = label
self.group_id = group_id
self.points = []
self.fill = False
self.selected = False
self.shape_type = shape_type
self.flags = flags
self.other_data = {}
self._highlightIndex = None
self._highlightMode = self.NEAR_VERTEX
self._highlightSettings = {
self.NEAR_VERTEX: (4, self.P_ROUND),
self.MOVE_VERTEX: (1.5, self.P_SQUARE),
}
self._closed = False
if line_color is not None:
# Override the class line_color attribute
# with an object attribute. Currently this
# is used for drawing the pending line a different color.
self.line_color = line_color
self.shape_type = shape_type
@property
def shape_type(self):
return self._shape_type
@shape_type.setter
def shape_type(self, value):
if value is None:
value = "polygon"
if value not in [
"polygon",
"rectangle",
"point",
"line",
"circle",
"linestrip",
]:
raise ValueError("Unexpected shape_type: {}".format(value))
self._shape_type = value
def close(self):
self._closed = True
def addPoint(self, point):
if self.points and point == self.points[0]:
self.close()
else:
self.points.append(point)
def canAddPoint(self):
return self.shape_type in ["polygon", "linestrip"]
def popPoint(self):
if self.points:
return self.points.pop()
return None
def insertPoint(self, i, point):
self.points.insert(i, point)
def removePoint(self, i):
self.points.pop(i)
def isClosed(self):
return self._closed
def setOpen(self):
self._closed = False
def getRectFromLine(self, pt1, pt2):
x1, y1 = pt1.x(), pt1.y()
x2, y2 = pt2.x(), pt2.y()
return QtCore.QRectF(x1, y1, x2 - x1, y2 - y1)
def paint(self, painter, flag = 1, proposal_flag = 0):
if self.points:
color = (
self.select_line_color if self.selected else self.line_color
)
if proposal_flag == 1:
color = (
QtGui.QColor(30, 30, 200)
)
pen = QtGui.QPen(color)
npen = QtGui.QPen(self.nvertex_fill_color)
if flag == 1:
# Try using integer sizes for smoother drawing(?)
pen.setWidth(max(1, int(round(2.0 / self.scale))))
painter.setPen(pen)
else:
npen.setWidth(max(1, int(round(2.0 / self.scale))))
painter.setPen(npen)
line_path = QtGui.QPainterPath()
vrtx_path = QtGui.QPainterPath()
if self.shape_type == "rectangle":
assert len(self.points) in [1, 2]
if len(self.points) == 2:
rectangle = self.getRectFromLine(*self.points)
line_path.addRect(rectangle)
for i in range(len(self.points)):
self.drawVertex(vrtx_path, i)
elif self.shape_type == "circle":
assert len(self.points) in [1, 2]
if len(self.points) == 2:
rectangle = self.getCircleRectFromLine(self.points)
line_path.addEllipse(rectangle)
for i in range(len(self.points)):
self.drawVertex(vrtx_path, i)
elif self.shape_type == "linestrip":
line_path.moveTo(self.points[0])
for i, p in enumerate(self.points):
line_path.lineTo(p)
self.drawVertex(vrtx_path, i)
elif self.shape_type == "point":
for i, p in enumerate(self.points):
self.drawVertex(vrtx_path, i)
else:
line_path.moveTo(self.points[0])
# Uncommenting the following line will draw 2 paths
# for the 1st vertex, and make it non-filled, which
# may be desirable.
# self.drawVertex(vrtx_path, 0)
for i, p in enumerate(self.points):
line_path.lineTo(p)
self.drawVertex(vrtx_path, i)
if self.isClosed():
line_path.lineTo(self.points[0])
painter.drawPath(line_path)
if proposal_flag == 0:
painter.drawPath(vrtx_path)
painter.fillPath(vrtx_path, self._vertex_fill_color)
if self.fill:
color = (
self.select_fill_color
if self.selected
else self.fill_color
)
if proposal_flag == 1:
color = (
QtGui.QColor(30, 30, 200,100)
)
painter.fillPath(line_path, color)
if proposal_flag == 0:
cx, cy = self.get_center_points(self.points)
if self.group_id is not None:
painter.drawText(int(cx), int(cy), self.label + ',' + str(self.group_id))
else:
painter.drawText(int(cx), int(cy), self.label)
def get_center_points(self, points):
xs = []
ys = []
for point in points:
xs.append(point.x())
ys.append(point.y())
return sum(xs)/len(xs) - 15, max(ys) + 10
def drawVertex(self, path, i):
d = self.point_size / self.scale
shape = self.point_type
point = self.points[i]
if i == self._highlightIndex:
size, shape = self._highlightSettings[self._highlightMode]
d *= size
if self._highlightIndex is not None:
self._vertex_fill_color = self.hvertex_fill_color
else:
self._vertex_fill_color = self.vertex_fill_color
if shape == self.P_SQUARE:
path.addRect(point.x() - d / 2, point.y() - d / 2, d, d)
elif shape == self.P_ROUND:
path.addEllipse(point, d / 2.0, d / 2.0)
else:
assert False, "unsupported vertex shape"
def nearestVertex(self, point, epsilon):
min_distance = float("inf")
min_i = None
for i, p in enumerate(self.points):
dist = labelme.utils.distance(p - point)
if dist <= epsilon and dist < min_distance:
min_distance = dist
min_i = i
return min_i
def nearestEdge(self, point, epsilon):
min_distance = float("inf")
post_i = None
for i in range(len(self.points)):
line = [self.points[i - 1], self.points[i]]
dist = labelme.utils.distancetoline(point, line)
if dist <= epsilon and dist < min_distance:
min_distance = dist
post_i = i
return post_i
def containsPoint(self, point):
return self.makePath().contains(point)
def getCircleRectFromLine(self, line):
"""Computes parameters to draw with `QPainterPath::addEllipse`"""
if len(line) != 2:
return None
(c, point) = line
r = line[0] - line[1]
d = math.sqrt(math.pow(r.x(), 2) + math.pow(r.y(), 2))
rectangle = QtCore.QRectF(c.x() - d, c.y() - d, 2 * d, 2 * d)
return rectangle
def makePath(self):
if self.shape_type == "rectangle":
path = QtGui.QPainterPath()
if len(self.points) == 2:
rectangle = self.getRectFromLine(*self.points)
path.addRect(rectangle)
elif self.shape_type == "circle":
path = QtGui.QPainterPath()
if len(self.points) == 2:
rectangle = self.getCircleRectFromLine(self.points)
path.addEllipse(rectangle)
else:
path = QtGui.QPainterPath(self.points[0])
for p in self.points[1:]:
path.lineTo(p)
return path
def boundingRect(self):
return self.makePath().boundingRect()
def moveBy(self, offset):
self.points = [p + offset for p in self.points]
def moveVertexBy(self, i, offset):
self.points[i] = self.points[i] + offset
def highlightVertex(self, i, action):
"""Highlight a vertex appropriately based on the current action
Args:
i (int): The vertex index
action (int): The action
(see Shape.NEAR_VERTEX and Shape.MOVE_VERTEX)
"""
self._highlightIndex = i
self._highlightMode = action
def highlightClear(self):
"""Clear the highlighted point"""
self._highlightIndex = None
def copy(self):
return copy.deepcopy(self)
def __len__(self):
return len(self.points)
def __getitem__(self, key):
return self.points[key]
def __setitem__(self, key, value):
self.points[key] = value