shape.py 8.4 KB

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