shape.py 8.7 KB

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