shape.py 8.5 KB

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