shape.py 8.6 KB

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