labelme.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 shape import Shape
  12. from canvas import Canvas
  13. from zoomwidget import ZoomWidget
  14. __appname__ = 'labelme'
  15. # TODO:
  16. # - Zoom is too "steppy".
  17. ### Utility functions and classes.
  18. def action(parent, text, slot=None, shortcut=None, icon=None,
  19. tip=None, checkable=False):
  20. """Create a new action and assign callbacks, shortcuts, etc."""
  21. a = QAction(text, parent)
  22. if icon is not None:
  23. a.setIcon(QIcon(u':/%s' % icon))
  24. if shortcut is not None:
  25. a.setShortcut(shortcut)
  26. if tip is not None:
  27. a.setToolTip(tip)
  28. a.setStatusTip(tip)
  29. if slot is not None:
  30. a.triggered.connect(slot)
  31. if checkable:
  32. a.setCheckable(True)
  33. return a
  34. def add_actions(widget, actions):
  35. for action in actions:
  36. if action is None:
  37. widget.addSeparator()
  38. else:
  39. widget.addAction(action)
  40. class WindowMixin(object):
  41. def menu(self, title, actions=None):
  42. menu = self.menuBar().addMenu(title)
  43. if actions:
  44. add_actions(menu, actions)
  45. return menu
  46. def toolbar(self, title, actions=None):
  47. toolbar = QToolBar(title)
  48. toolbar.setObjectName(u'%sToolBar' % title)
  49. #toolbar.setOrientation(Qt.Vertical)
  50. toolbar.setContentsMargins(0,0,0,0)
  51. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  52. toolbar.layout().setContentsMargins(0,0,0,0)
  53. if actions:
  54. add_actions(toolbar, actions)
  55. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  56. return toolbar
  57. class MainWindow(QMainWindow, WindowMixin):
  58. def __init__(self, filename=None):
  59. super(MainWindow, self).__init__()
  60. self.setWindowTitle(__appname__)
  61. self.setContentsMargins(0, 0, 0, 0)
  62. # Main widgets.
  63. self.label = QLineEdit(u'Hello world, مرحبا ، العالم, Γεια σου κόσμε!')
  64. self.dock = QDockWidget(u'Label', parent=self)
  65. self.dock.setObjectName(u'Label')
  66. self.dock.setWidget(self.label)
  67. self.zoom_widget = ZoomWidget()
  68. #self.dock.setFeatures(QDockWidget.DockWidgetMovable|QDockWidget.DockWidgetFloatable)
  69. self.canvas = Canvas()
  70. #self.canvas.setAlignment(Qt.AlignCenter)
  71. self.canvas.setContextMenuPolicy(Qt.ActionsContextMenu)
  72. self.canvas.zoomRequest.connect(self.zoomRequest)
  73. scroll = QScrollArea()
  74. scroll.setWidget(self.canvas)
  75. scroll.setWidgetResizable(True)
  76. self.scrollBars = {
  77. Qt.Vertical: scroll.verticalScrollBar(),
  78. Qt.Horizontal: scroll.horizontalScrollBar()
  79. }
  80. self.canvas.scrollRequest.connect(self.scrollRequest)
  81. self.setCentralWidget(scroll)
  82. self.addDockWidget(Qt.BottomDockWidgetArea, self.dock)
  83. # Actions
  84. quit = action(self, '&Quit', self.close,
  85. 'Ctrl+Q', 'quit', u'Exit application')
  86. open = action(self, '&Open', self.openFile,
  87. 'Ctrl+O', 'open', u'Open file')
  88. color = action(self, '&Color', self.chooseColor,
  89. 'Ctrl+C', 'color', u'Choose line color')
  90. label = action(self,'&New Label', self.newLabel,
  91. 'Ctrl+N', 'new', u'Add new label')
  92. delete = action(self,'&delete', self.deleteSelectedShape,
  93. 'Ctrl+D', 'delete', u'Delete')
  94. labl = self.dock.toggleViewAction()
  95. labl.setShortcut('Ctrl+L')
  96. zoom = QWidgetAction(self)
  97. zoom.setDefaultWidget(self.zoom_widget)
  98. fit_window = action(self, '&Fit Window', self.setFitWindow,
  99. 'Ctrl+F', 'fit', u'Fit image to window', checkable=True)
  100. self.menus = struct(
  101. file=self.menu('&File'),
  102. edit=self.menu('&Image'),
  103. view=self.menu('&View'))
  104. add_actions(self.menus.file, (open, quit))
  105. add_actions(self.menus.edit, (label, color, fit_window))
  106. add_actions(self.menus.view, (labl,))
  107. self.tools = self.toolbar('Tools')
  108. add_actions(self.tools, (open, color, None, label, delete, None,
  109. zoom, fit_window, None, quit))
  110. self.statusBar().showMessage('%s started.' % __appname__)
  111. self.statusBar().show()
  112. # Application state.
  113. self.image = QImage()
  114. self.filename = filename
  115. self.recent_files = []
  116. self.color = None
  117. self.zoom_level = 100
  118. self.fit_window = False
  119. # TODO: Could be completely declarative.
  120. # Restore application settings.
  121. types = {
  122. 'filename': QString,
  123. 'recent-files': QStringList,
  124. 'window/size': QSize,
  125. 'window/position': QPoint,
  126. 'window/geometry': QByteArray,
  127. # Docks and toolbars:
  128. 'window/state': QByteArray,
  129. }
  130. self.settings = settings = Settings(types)
  131. self.recent_files = settings['recent-files']
  132. size = settings.get('window/size', QSize(600, 500))
  133. position = settings.get('window/position', QPoint(0, 0))
  134. self.resize(size)
  135. self.move(position)
  136. # or simply:
  137. #self.restoreGeometry(settings['window/geometry']
  138. self.restoreState(settings['window/state'])
  139. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  140. # The file menu has default dynamically generated entries.
  141. self.updateFileMenu()
  142. # Since loading the file may take some time, make sure it runs in the background.
  143. self.queueEvent(partial(self.loadFile, self.filename))
  144. # Callbacks:
  145. self.zoom_widget.editingFinished.connect(self.paintCanvas)
  146. ## Callback functions:
  147. def scrollRequest(self, delta, orientation):
  148. units = - delta / (8 * 15)
  149. bar = self.scrollBars[orientation]
  150. bar.setValue(bar.value() + bar.singleStep() * units)
  151. def zoomRequest(self, delta):
  152. if not self.fit_window:
  153. units = delta / (8 * 15)
  154. scale = 10
  155. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  156. self.zoom_widget.editingFinished.emit()
  157. def setFitWindow(self, value=True):
  158. self.zoom_widget.setEnabled(not value)
  159. self.fit_window = value
  160. self.paintCanvas()
  161. def queueEvent(self, function):
  162. QTimer.singleShot(0, function)
  163. def loadFile(self, filename=None):
  164. """Load the specified file, or the last opened file if None."""
  165. if filename is None:
  166. filename = self.settings['filename']
  167. # FIXME: Load the actual file here.
  168. if QFile.exists(filename):
  169. # Load image
  170. image = QImage(filename)
  171. if image.isNull():
  172. message = "Failed to read %s" % filename
  173. else:
  174. message = "Loaded %s" % os.path.basename(unicode(filename))
  175. self.image = image
  176. self.filename = filename
  177. self.loadPixmap()
  178. self.statusBar().showMessage(message)
  179. def resizeEvent(self, event):
  180. if self.fit_window and self.canvas and not self.image.isNull():
  181. self.paintCanvas()
  182. super(MainWindow, self).resizeEvent(event)
  183. def loadPixmap(self):
  184. assert not self.image.isNull(), "cannot load null image"
  185. self.canvas.pixmap = QPixmap.fromImage(self.image)
  186. def paintCanvas(self):
  187. assert not self.image.isNull(), "cannot paint null image"
  188. self.canvas.scale = self.fitSize() if self.fit_window\
  189. else 0.01 * self.zoom_widget.value()
  190. self.canvas.adjustSize()
  191. self.canvas.repaint()
  192. def fitSize(self):
  193. """Figure out the size of the pixmap in order to fit the main widget."""
  194. e = 2.0 # So that no scrollbars are generated.
  195. w1 = self.centralWidget().width() - e
  196. h1 = self.centralWidget().height() - e
  197. a1 = w1/ h1
  198. # Calculate a new scale value based on the pixmap's aspect ratio.
  199. w2 = self.canvas.pixmap.width() - 0.0
  200. h2 = self.canvas.pixmap.height() - 0.0
  201. a2 = w2 / h2
  202. return w1 / w2 if a2 >= a1 else h1 / h2
  203. def closeEvent(self, event):
  204. # TODO: Make sure changes are saved.
  205. s = self.settings
  206. s['filename'] = self.filename if self.filename else QString()
  207. s['window/size'] = self.size()
  208. s['window/position'] = self.pos()
  209. s['window/state'] = self.saveState()
  210. s['line/color'] = self.color
  211. #s['window/geometry'] = self.saveGeometry()
  212. def updateFileMenu(self):
  213. """Populate menu with recent files."""
  214. ## Dialogs.
  215. def openFile(self):
  216. if not self.check():
  217. return
  218. path = os.path.dirname(unicode(self.filename))\
  219. if self.filename else '.'
  220. formats = ['*.%s' % unicode(fmt).lower()\
  221. for fmt in QImageReader.supportedImageFormats()]
  222. filename = unicode(QFileDialog.getOpenFileName(self,
  223. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  224. if filename:
  225. self.loadFile(filename)
  226. def check(self):
  227. # TODO: Prompt user to save labels etc.
  228. return True
  229. def chooseColor(self):
  230. self.color = QColorDialog.getColor(self.color, self,
  231. u'Choose line color', QColorDialog.ShowAlphaChannel)
  232. # Change the color for all shape lines:
  233. Shape.line_color = self.color
  234. self.canvas.repaint()
  235. def newLabel(self):
  236. self.canvas.deSelectShape()
  237. self.canvas.startLabeling=True
  238. def deleteSelectedShape(self):
  239. self.canvas.deleteSelected()
  240. class Settings(object):
  241. """Convenience dict-like wrapper around QSettings."""
  242. def __init__(self, types=None):
  243. self.data = QSettings()
  244. self.types = defaultdict(lambda: QVariant, types if types else {})
  245. def __setitem__(self, key, value):
  246. t = self.types[key]
  247. self.data.setValue(key,
  248. t(value) if not isinstance(value, t) else value)
  249. def __getitem__(self, key):
  250. return self._cast(key, self.data.value(key))
  251. def get(self, key, default=None):
  252. return self._cast(key, self.data.value(key, default))
  253. def _cast(self, key, value):
  254. # XXX: Very nasty way of converting types to QVariant methods :P
  255. t = self.types[key]
  256. if t != QVariant:
  257. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  258. return method(value)
  259. return value
  260. class struct(object):
  261. def __init__(self, **kwargs):
  262. self.__dict__.update(kwargs)
  263. def main(argv):
  264. """Standard boilerplate Qt application code."""
  265. app = QApplication(argv)
  266. app.setApplicationName(__appname__)
  267. win = MainWindow(argv[1] if len(argv) == 2 else None)
  268. win.show()
  269. return app.exec_()
  270. if __name__ == '__main__':
  271. sys.exit(main(sys.argv))