shape.py 9.8 KB

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