shape.py 8.5 KB

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