shape.py 10 KB

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