labelme.py 16 KB

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