shape.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import copy
  2. import math
  3. from qtpy import QtCore
  4. from qtpy import QtGui
  5. import labelme.utils
  6. # TODO(unknown):
  7. # - [opt] Store paths instead of creating new ones at each paint.
  8. R, G, B = SHAPE_COLOR = 0, 255, 0 # green
  9. DEFAULT_LINE_COLOR = QtGui.QColor(R, G, B, 128) # bf hovering
  10. DEFAULT_FILL_COLOR = QtGui.QColor(R, G, B, 128) # hovering
  11. DEFAULT_SELECT_LINE_COLOR = QtGui.QColor(255, 255, 255) # selected
  12. DEFAULT_SELECT_FILL_COLOR = QtGui.QColor(R, G, B, 155) # selected
  13. DEFAULT_VERTEX_FILL_COLOR = QtGui.QColor(R, G, B, 255) # hovering
  14. DEFAULT_HVERTEX_FILL_COLOR = QtGui.QColor(255, 255, 255, 255) # hovering
  15. class Shape(object):
  16. P_SQUARE, P_ROUND = 0, 1
  17. MOVE_VERTEX, NEAR_VERTEX = 0, 1
  18. # The following class variables influence the drawing of all shape objects.
  19. line_color = DEFAULT_LINE_COLOR
  20. fill_color = DEFAULT_FILL_COLOR
  21. select_line_color = DEFAULT_SELECT_LINE_COLOR
  22. select_fill_color = DEFAULT_SELECT_FILL_COLOR
  23. vertex_fill_color = DEFAULT_VERTEX_FILL_COLOR
  24. hvertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR
  25. point_type = P_ROUND
  26. point_size = 8
  27. scale = 1.0
  28. def __init__(self, label=None, line_color=None, shape_type=None,
  29. flags=None, group_id=None):
  30. self.label = label
  31. self.group_id = group_id
  32. self.points = []
  33. self.fill = False
  34. self.selected = False
  35. self.shape_type = shape_type
  36. self.flags = flags
  37. self._highlightIndex = None
  38. self._highlightMode = self.NEAR_VERTEX
  39. self._highlightSettings = {
  40. self.NEAR_VERTEX: (4, self.P_ROUND),
  41. self.MOVE_VERTEX: (1.5, self.P_SQUARE),
  42. }
  43. self._closed = False
  44. if line_color is not None:
  45. # Override the class line_color attribute
  46. # with an object attribute. Currently this
  47. # is used for drawing the pending line a different color.
  48. self.line_color = line_color
  49. self.shape_type = shape_type
  50. @property
  51. def shape_type(self):
  52. return self._shape_type
  53. @shape_type.setter
  54. def shape_type(self, value):
  55. if value is None:
  56. value = 'polygon'
  57. if value not in ['polygon', 'rectangle', 'point',
  58. 'line', 'circle', 'linestrip']:
  59. raise ValueError('Unexpected shape_type: {}'.format(value))
  60. self._shape_type = value
  61. def close(self):
  62. self._closed = True
  63. def addPoint(self, point):
  64. if self.points and point == self.points[0]:
  65. self.close()
  66. else:
  67. self.points.append(point)
  68. def canAddPoint(self):
  69. return self.shape_type in ['polygon', 'linestrip']
  70. def popPoint(self):
  71. if self.points:
  72. return self.points.pop()
  73. return None
  74. def insertPoint(self, i, point):
  75. self.points.insert(i, point)
  76. def removePoint(self, i):
  77. self.points.pop(i)
  78. def isClosed(self):
  79. return self._closed
  80. def setOpen(self):
  81. self._closed = False
  82. def getRectFromLine(self, pt1, pt2):
  83. x1, y1 = pt1.x(), pt1.y()
  84. x2, y2 = pt2.x(), pt2.y()
  85. return QtCore.QRectF(x1, y1, x2 - x1, y2 - y1)
  86. def paint(self, painter):
  87. if self.points:
  88. color = self.select_line_color \
  89. if self.selected else self.line_color
  90. pen = QtGui.QPen(color)
  91. # Try using integer sizes for smoother drawing(?)
  92. pen.setWidth(max(1, int(round(2.0 / self.scale))))
  93. painter.setPen(pen)
  94. line_path = QtGui.QPainterPath()
  95. vrtx_path = QtGui.QPainterPath()
  96. if self.shape_type == 'rectangle':
  97. assert len(self.points) in [1, 2]
  98. if len(self.points) == 2:
  99. rectangle = self.getRectFromLine(*self.points)
  100. line_path.addRect(rectangle)
  101. for i in range(len(self.points)):
  102. self.drawVertex(vrtx_path, i)
  103. elif self.shape_type == "circle":
  104. assert len(self.points) in [1, 2]
  105. if len(self.points) == 2:
  106. rectangle = self.getCircleRectFromLine(self.points)
  107. line_path.addEllipse(rectangle)
  108. for i in range(len(self.points)):
  109. self.drawVertex(vrtx_path, i)
  110. elif self.shape_type == "linestrip":
  111. line_path.moveTo(self.points[0])
  112. for i, p in enumerate(self.points):
  113. line_path.lineTo(p)
  114. self.drawVertex(vrtx_path, i)
  115. else:
  116. line_path.moveTo(self.points[0])
  117. # Uncommenting the following line will draw 2 paths
  118. # for the 1st vertex, and make it non-filled, which
  119. # may be desirable.
  120. # self.drawVertex(vrtx_path, 0)
  121. for i, p in enumerate(self.points):
  122. line_path.lineTo(p)
  123. self.drawVertex(vrtx_path, i)
  124. if self.isClosed():
  125. line_path.lineTo(self.points[0])
  126. painter.drawPath(line_path)
  127. painter.drawPath(vrtx_path)
  128. painter.fillPath(vrtx_path, self._vertex_fill_color)
  129. if self.fill:
  130. color = self.select_fill_color \
  131. if self.selected else self.fill_color
  132. painter.fillPath(line_path, color)
  133. def drawVertex(self, path, i):
  134. d = self.point_size / self.scale
  135. shape = self.point_type
  136. point = self.points[i]
  137. if i == self._highlightIndex:
  138. size, shape = self._highlightSettings[self._highlightMode]
  139. d *= size
  140. if self._highlightIndex is not None:
  141. self._vertex_fill_color = self.hvertex_fill_color
  142. else:
  143. self._vertex_fill_color = self.vertex_fill_color
  144. if shape == self.P_SQUARE:
  145. path.addRect(point.x() - d / 2, point.y() - d / 2, d, d)
  146. elif shape == self.P_ROUND:
  147. path.addEllipse(point, d / 2.0, d / 2.0)
  148. else:
  149. assert False, "unsupported vertex shape"
  150. def nearestVertex(self, point, epsilon):
  151. min_distance = float('inf')
  152. min_i = None
  153. for i, p in enumerate(self.points):
  154. dist = labelme.utils.distance(p - point)
  155. if dist <= epsilon and dist < min_distance:
  156. min_distance = dist
  157. min_i = i
  158. return min_i
  159. def nearestEdge(self, point, epsilon):
  160. min_distance = float('inf')
  161. post_i = None
  162. for i in range(len(self.points)):
  163. line = [self.points[i - 1], self.points[i]]
  164. dist = labelme.utils.distancetoline(point, line)
  165. if dist <= epsilon and dist < min_distance:
  166. min_distance = dist
  167. post_i = i
  168. return post_i
  169. def containsPoint(self, point):
  170. return self.makePath().contains(point)
  171. def getCircleRectFromLine(self, line):
  172. """Computes parameters to draw with `QPainterPath::addEllipse`"""
  173. if len(line) != 2:
  174. return None
  175. (c, point) = line
  176. r = line[0] - line[1]
  177. d = math.sqrt(math.pow(r.x(), 2) + math.pow(r.y(), 2))
  178. rectangle = QtCore.QRectF(c.x() - d, c.y() - d, 2 * d, 2 * d)
  179. return rectangle
  180. def makePath(self):
  181. if self.shape_type == 'rectangle':
  182. path = QtGui.QPainterPath()
  183. if len(self.points) == 2:
  184. rectangle = self.getRectFromLine(*self.points)
  185. path.addRect(rectangle)
  186. elif self.shape_type == "circle":
  187. path = QtGui.QPainterPath()
  188. if len(self.points) == 2:
  189. rectangle = self.getCircleRectFromLine(self.points)
  190. path.addEllipse(rectangle)
  191. else:
  192. path = QtGui.QPainterPath(self.points[0])
  193. for p in self.points[1:]:
  194. path.lineTo(p)
  195. return path
  196. def boundingRect(self):
  197. return self.makePath().boundingRect()
  198. def moveBy(self, offset):
  199. self.points = [p + offset for p in self.points]
  200. def moveVertexBy(self, i, offset):
  201. self.points[i] = self.points[i] + offset
  202. def highlightVertex(self, i, action):
  203. self._highlightIndex = i
  204. self._highlightMode = action
  205. def highlightClear(self):
  206. self._highlightIndex = None
  207. def copy(self):
  208. return copy.deepcopy(self)
  209. def __len__(self):
  210. return len(self.points)
  211. def __getitem__(self, key):
  212. return self.points[key]
  213. def __setitem__(self, key, value):
  214. self.points[key] = value