shape.py 9.1 KB

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