labelme.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #!/usr/bin/env python
  2. # -*- coding: utf8 -*-
  3. import os.path
  4. import re
  5. import sys
  6. from functools import partial
  7. from collections import defaultdict
  8. from PyQt4.QtGui import *
  9. from PyQt4.QtCore import *
  10. import resources
  11. from lib import newAction, addActions, labelValidator
  12. from shape import Shape
  13. from canvas import Canvas
  14. from zoomWidget import ZoomWidget
  15. from labelDialog import LabelDialog
  16. from labelFile import LabelFile
  17. __appname__ = 'labelme'
  18. # FIXME
  19. # - Select shapes with right click as well.
  20. # - [low] Label validation/postprocessing breaks with TAB.
  21. # TODO:
  22. # - [easy] Add button to Hide/Show all labels.
  23. # - Zoom is too "steppy".
  24. ### Utility functions and classes.
  25. class WindowMixin(object):
  26. def menu(self, title, actions=None):
  27. menu = self.menuBar().addMenu(title)
  28. if actions:
  29. addActions(menu, actions)
  30. return menu
  31. def toolbar(self, title, actions=None):
  32. toolbar = QToolBar(title)
  33. toolbar.setObjectName(u'%sToolBar' % title)
  34. #toolbar.setOrientation(Qt.Vertical)
  35. toolbar.setContentsMargins(0,0,0,0)
  36. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  37. toolbar.layout().setContentsMargins(0,0,0,0)
  38. if actions:
  39. addActions(toolbar, actions)
  40. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  41. return toolbar
  42. class MainWindow(QMainWindow, WindowMixin):
  43. def __init__(self, filename=None):
  44. super(MainWindow, self).__init__()
  45. self.setWindowTitle(__appname__)
  46. self.setContentsMargins(0, 0, 0, 0)
  47. # Main widgets.
  48. self.label = LabelDialog(parent=self)
  49. self.labels = {}
  50. self.items = {}
  51. self.highlighted = None
  52. self.labelList = QListWidget()
  53. self.dock = QDockWidget(u'Labels', self)
  54. self.dock.setObjectName(u'Labels')
  55. self.dock.setWidget(self.labelList)
  56. self.zoom_widget = ZoomWidget()
  57. self.labelList.setItemDelegate(LabelDelegate())
  58. self.labelList.itemActivated.connect(self.highlightLabel)
  59. # Connect to itemChanged to detect checkbox changes.
  60. self.labelList.itemChanged.connect(self.labelItemChanged)
  61. self.canvas = Canvas()
  62. #self.canvas.setAlignment(Qt.AlignCenter)
  63. self.canvas.zoomRequest.connect(self.zoomRequest)
  64. scroll = QScrollArea()
  65. scroll.setWidget(self.canvas)
  66. scroll.setWidgetResizable(True)
  67. self.scrollBars = {
  68. Qt.Vertical: scroll.verticalScrollBar(),
  69. Qt.Horizontal: scroll.horizontalScrollBar()
  70. }
  71. self.canvas.scrollRequest.connect(self.scrollRequest)
  72. self.canvas.newShape.connect(self.newShape)
  73. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  74. self.setCentralWidget(scroll)
  75. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  76. # Actions
  77. action = partial(newAction, self)
  78. quit = action('&Quit', self.close,
  79. 'Ctrl+Q', 'quit', u'Exit application')
  80. open = action('&Open', self.openFile,
  81. 'Ctrl+O', 'open', u'Open file')
  82. save = action('&Save', self.saveFile,
  83. 'Ctrl+S', 'save', u'Save file')
  84. color = action('&Color', self.chooseColor,
  85. 'Ctrl+C', 'color', u'Choose line color')
  86. label = action('&New Item', self.newLabel,
  87. 'Ctrl+N', 'new', u'Add new label')
  88. copy = action('&Copy', self.copySelectedShape,
  89. 'Ctrl+C', 'copy', u'Copy', enabled=False)
  90. delete = action('&Delete', self.deleteSelectedShape,
  91. 'Ctrl+D', 'delete', u'Delete', enabled=False)
  92. hide = action('&Hide labels', self.hideLabelsToggle,
  93. 'Ctrl+H', 'hide', u'Hide background labels when drawing',
  94. checkable=True)
  95. # Custom context menu for the canvas widget:
  96. self.popMenu = QMenu(self)
  97. addActions(self.popMenu, (label, copy, delete))
  98. self.canvas.setContextMenuPolicy(Qt.CustomContextMenu)
  99. self.canvas.customContextMenuRequested.connect(self.popContextMenu)
  100. labels = self.dock.toggleViewAction()
  101. labels.setShortcut('Ctrl+L')
  102. zoom = QWidgetAction(self)
  103. zoom.setDefaultWidget(self.zoom_widget)
  104. # Store actions for further handling.
  105. self.actions = struct(save=save, open=open, color=color,
  106. label=label, delete=delete, zoom=zoom, copy=copy)
  107. save.setEnabled(False)
  108. fit_window = action('&Fit Window', self.setFitWindow,
  109. 'Ctrl+F', 'fit', u'Fit image to window', checkable=True)
  110. self.menus = struct(
  111. file=self.menu('&File'),
  112. edit=self.menu('&Image'),
  113. view=self.menu('&View'))
  114. addActions(self.menus.file, (open, save, quit))
  115. addActions(self.menus.edit, (label, color, fit_window))
  116. addActions(self.menus.view, (labels,))
  117. self.tools = self.toolbar('Tools')
  118. addActions(self.tools, (open, save, color, labels, None, label, delete, hide, None,
  119. zoom, fit_window, None, quit))
  120. self.statusBar().showMessage('%s started.' % __appname__)
  121. self.statusBar().show()
  122. # Application state.
  123. self.image = QImage()
  124. self.filename = filename
  125. self.recent_files = []
  126. self.color = None
  127. self.zoom_level = 100
  128. self.fit_window = False
  129. # TODO: Could be completely declarative.
  130. # Restore application settings.
  131. types = {
  132. 'filename': QString,
  133. 'recent-files': QStringList,
  134. 'window/size': QSize,
  135. 'window/position': QPoint,
  136. 'window/geometry': QByteArray,
  137. # Docks and toolbars:
  138. 'window/state': QByteArray,
  139. }
  140. self.settings = settings = Settings(types)
  141. self.recent_files = settings['recent-files']
  142. size = settings.get('window/size', QSize(600, 500))
  143. position = settings.get('window/position', QPoint(0, 0))
  144. self.resize(size)
  145. self.move(position)
  146. # or simply:
  147. #self.restoreGeometry(settings['window/geometry']
  148. self.restoreState(settings['window/state'])
  149. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  150. # The file menu has default dynamically generated entries.
  151. self.updateFileMenu()
  152. # Since loading the file may take some time, make sure it runs in the background.
  153. self.queueEvent(partial(self.loadFile, self.filename))
  154. # Callbacks:
  155. self.zoom_widget.editingFinished.connect(self.paintCanvas)
  156. def shapeSelectionChanged(self, selected=False):
  157. self.actions.delete.setEnabled(selected)
  158. self.actions.copy.setEnabled(selected)
  159. def popContextMenu(self, point):
  160. self.popMenu.exec_(self.canvas.mapToGlobal(point))
  161. def addLabel(self, shape):
  162. item = QListWidgetItem(shape.label)
  163. item.setFlags(item.flags() | Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
  164. item.setCheckState(Qt.Checked)
  165. self.labels[item] = shape
  166. self.items[shape] = item
  167. self.labelList.addItem(item)
  168. def remLabel(self, shape):
  169. item = self.items.get(shape, None)
  170. self.labelList.takeItem(self.labelList.row(item))
  171. def loadLabels(self, shapes):
  172. s = []
  173. for label, points in shapes:
  174. shape = Shape(label=label)
  175. shape.fill = True
  176. for x, y in points:
  177. shape.addPoint(QPointF(x, y))
  178. s.append(shape)
  179. self.addLabel(shape)
  180. self.canvas.loadShapes(s)
  181. def saveLabels(self, filename):
  182. lf = LabelFile()
  183. shapes = [(unicode(shape.label), [(p.x(), p.y()) for p in shape.points])\
  184. for shape in self.canvas.shapes]
  185. lf.save(filename, shapes, unicode(self.filename), self.imageData)
  186. def copySelectedShape(self):
  187. self.addLabel(self.canvas.copySelectedShape())
  188. def highlightLabel(self, item):
  189. if self.highlighted:
  190. self.highlighted.fill_color = Shape.fill_color
  191. shape = self.labels[item]
  192. shape.fill_color = inverted(Shape.fill_color)
  193. self.highlighted = shape
  194. self.canvas.repaint()
  195. def labelItemChanged(self, item):
  196. shape = self.labels[item]
  197. label = unicode(item.text())
  198. if label != shape.label:
  199. self.stateChanged()
  200. shape.label = unicode(item.text())
  201. else: # User probably changed item visibility
  202. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  203. def stateChanged(self):
  204. self.actions.save.setEnabled(True)
  205. ## Callback functions:
  206. def newShape(self, position):
  207. """Pop-up and give focus to the label editor.
  208. position MUST be in global coordinates.
  209. """
  210. action = self.label.popUp(position)
  211. if action == self.label.OK:
  212. self.addLabel(self.canvas.setLastLabel(self.label.text()))
  213. # Enable appropriate actions.
  214. self.actions.save.setEnabled(True)
  215. self.actions.label.setEnabled(True)
  216. elif action == self.label.UNDO:
  217. self.canvas.undoLastLine()
  218. elif action == self.label.DELETE:
  219. self.canvas.deleteLastShape()
  220. else:
  221. assert False, "unknown label action"
  222. def scrollRequest(self, delta, orientation):
  223. units = - delta / (8 * 15)
  224. bar = self.scrollBars[orientation]
  225. bar.setValue(bar.value() + bar.singleStep() * units)
  226. def zoomRequest(self, delta):
  227. if not self.fit_window:
  228. units = delta / (8 * 15)
  229. scale = 10
  230. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  231. self.zoom_widget.editingFinished.emit()
  232. def setFitWindow(self, value=True):
  233. self.zoom_widget.setEnabled(not value)
  234. self.fit_window = value
  235. self.paintCanvas()
  236. def queueEvent(self, function):
  237. QTimer.singleShot(0, function)
  238. def hideLabelsToggle(self, value):
  239. self.canvas.hideBackroundShapes(value)
  240. def loadFile(self, filename=None):
  241. """Load the specified file, or the last opened file if None."""
  242. if filename is None:
  243. filename = self.settings['filename']
  244. filename = unicode(filename)
  245. if QFile.exists(filename):
  246. if LabelFile.isLabelFile(filename):
  247. # TODO: Error handling.
  248. lf = LabelFile()
  249. lf.load(filename)
  250. self.labelFile = lf
  251. self.imageData = lf.imageData
  252. else:
  253. # Load image:
  254. # read data first and store for saving into label file.
  255. self.imageData = read(filename, None)
  256. self.labelFile = None
  257. image = QImage.fromData(self.imageData)
  258. if image.isNull():
  259. message = "Failed to read %s" % filename
  260. else:
  261. message = "Loaded %s" % os.path.basename(unicode(filename))
  262. self.image = image
  263. self.filename = filename
  264. self.labels = {}
  265. self.labelList.clear()
  266. self.canvas.loadPixmap(QPixmap.fromImage(image))
  267. if self.labelFile:
  268. self.loadLabels(self.labelFile.shapes)
  269. self.statusBar().showMessage(message)
  270. def resizeEvent(self, event):
  271. if self.fit_window and self.canvas and not self.image.isNull():
  272. self.paintCanvas()
  273. super(MainWindow, self).resizeEvent(event)
  274. def paintCanvas(self):
  275. assert not self.image.isNull(), "cannot paint null image"
  276. self.canvas.scale = self.fitSize() if self.fit_window\
  277. else 0.01 * self.zoom_widget.value()
  278. self.canvas.adjustSize()
  279. self.canvas.repaint()
  280. def fitSize(self):
  281. """Figure out the size of the pixmap in order to fit the main widget."""
  282. e = 2.0 # So that no scrollbars are generated.
  283. w1 = self.centralWidget().width() - e
  284. h1 = self.centralWidget().height() - e
  285. a1 = w1/ h1
  286. # Calculate a new scale value based on the pixmap's aspect ratio.
  287. w2 = self.canvas.pixmap.width() - 0.0
  288. h2 = self.canvas.pixmap.height() - 0.0
  289. a2 = w2 / h2
  290. return w1 / w2 if a2 >= a1 else h1 / h2
  291. def closeEvent(self, event):
  292. # TODO: Make sure changes are saved.
  293. s = self.settings
  294. s['filename'] = self.filename if self.filename else QString()
  295. s['window/size'] = self.size()
  296. s['window/position'] = self.pos()
  297. s['window/state'] = self.saveState()
  298. s['line/color'] = self.color
  299. # ask the use for where to save the labels
  300. #s['window/geometry'] = self.saveGeometry()
  301. def updateFileMenu(self):
  302. """Populate menu with recent files."""
  303. ## Dialogs.
  304. def openFile(self):
  305. if not self.check():
  306. return
  307. path = os.path.dirname(unicode(self.filename))\
  308. if self.filename else '.'
  309. formats = ['*.%s' % unicode(fmt).lower()\
  310. for fmt in QImageReader.supportedImageFormats()]
  311. filters = 'Image files (%s)\nLabel files (*%s)'\
  312. % (' '.join(formats), LabelFile.suffix)
  313. filename = unicode(QFileDialog.getOpenFileName(self,
  314. '%s - Choose Image', path, filters))
  315. if filename:
  316. self.loadFile(filename)
  317. def saveFile(self):
  318. assert not self.image.isNull(), "cannot save empty image"
  319. # XXX: What if user wants to remove label file?
  320. assert self.labels, "cannot save empty labels"
  321. path = os.path.dirname(unicode(self.filename))\
  322. if self.filename else '.'
  323. formats = ['*%s' % LabelFile.suffix]
  324. filename = unicode(QFileDialog.getSaveFileName(self,
  325. '%s - Choose File', path, 'Label files (%s)' % ''.join(formats)))
  326. if filename:
  327. self.saveLabels(filename)
  328. def check(self):
  329. # TODO: Prompt user to save labels etc.
  330. return True
  331. def chooseColor(self):
  332. self.color = QColorDialog.getColor(self.color, self,
  333. u'Choose line color', QColorDialog.ShowAlphaChannel)
  334. # Change the color for all shape lines:
  335. Shape.line_color = self.color
  336. self.canvas.repaint()
  337. def newLabel(self):
  338. self.canvas.deSelectShape()
  339. self.canvas.setEditing()
  340. self.actions.label.setEnabled(False)
  341. def deleteSelectedShape(self):
  342. self.remLabel(self.canvas.deleteSelected())
  343. class LabelDelegate(QItemDelegate):
  344. def __init__(self, parent=None):
  345. super(LabelDelegate, self).__init__(parent)
  346. self.validator = labelValidator()
  347. # FIXME: Validation and trimming are completely broken if the
  348. # user navigates away from the editor with something like TAB.
  349. def createEditor(self, parent, option, index):
  350. """Make sure the user cannot enter empty labels.
  351. Also remove trailing whitespace."""
  352. edit = super(LabelDelegate, self).createEditor(parent, option, index)
  353. if isinstance(edit, QLineEdit):
  354. edit.setValidator(self.validator)
  355. def strip():
  356. edit.setText(edit.text().trimmed())
  357. edit.editingFinished.connect(strip)
  358. return edit
  359. class Settings(object):
  360. """Convenience dict-like wrapper around QSettings."""
  361. def __init__(self, types=None):
  362. self.data = QSettings()
  363. self.types = defaultdict(lambda: QVariant, types if types else {})
  364. def __setitem__(self, key, value):
  365. t = self.types[key]
  366. self.data.setValue(key,
  367. t(value) if not isinstance(value, t) else value)
  368. def __getitem__(self, key):
  369. return self._cast(key, self.data.value(key))
  370. def get(self, key, default=None):
  371. return self._cast(key, self.data.value(key, default))
  372. def _cast(self, key, value):
  373. # XXX: Very nasty way of converting types to QVariant methods :P
  374. t = self.types[key]
  375. if t != QVariant:
  376. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  377. return method(value)
  378. return value
  379. def inverted(color):
  380. return QColor(*[255 - v for v in color.getRgb()])
  381. def read(filename, default=None):
  382. try:
  383. with open(filename, 'rb') as f:
  384. return f.read()
  385. except:
  386. return default
  387. class struct(object):
  388. def __init__(self, **kwargs):
  389. self.__dict__.update(kwargs)
  390. def main(argv):
  391. """Standard boilerplate Qt application code."""
  392. app = QApplication(argv)
  393. app.setApplicationName(__appname__)
  394. win = MainWindow(argv[1] if len(argv) == 2 else None)
  395. win.show()
  396. return app.exec_()
  397. if __name__ == '__main__':
  398. sys.exit(main(sys.argv))