shape.py 11 KB

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