labelme.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. __appname__ = 'labelme'
  11. ### Utility functions and classes.
  12. def action(parent, text, slot=None, shortcut=None, icon=None,
  13. tip=None, checkable=False):
  14. """Create a new action and assign callbacks, shortcuts, etc."""
  15. a = QAction(text, parent)
  16. if icon is not None:
  17. a.setIcon(QIcon(u':/%s' % icon))
  18. if shortcut is not None:
  19. a.setShortcut(shortcut)
  20. if tip is not None:
  21. a.setToolTip(tip)
  22. a.setStatusTip(tip)
  23. if slot is not None:
  24. a.triggered.connect(slot)
  25. if checkable:
  26. a.setCheckable(True)
  27. return a
  28. def add_actions(widget, actions):
  29. for action in actions:
  30. if action is None:
  31. widget.addSeparator()
  32. else:
  33. widget.addAction(action)
  34. class WindowMixin(object):
  35. def menu(self, title, actions=None):
  36. menu = self.menuBar().addMenu(title)
  37. if actions:
  38. add_actions(menu, actions)
  39. return menu
  40. def toolbar(self, title, actions=None):
  41. toolbar = QToolBar(title)
  42. toolbar.setObjectName(u'%sToolBar' % title)
  43. #toolbar.setOrientation(Qt.Vertical)
  44. toolbar.setContentsMargins(0,0,0,0)
  45. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  46. toolbar.layout().setContentsMargins(0,0,0,0)
  47. if actions:
  48. add_actions(toolbar, actions)
  49. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  50. return toolbar
  51. class MainWindow(QMainWindow, WindowMixin):
  52. def __init__(self, filename=None):
  53. super(MainWindow, self).__init__()
  54. self.setWindowTitle(__appname__)
  55. self.setContentsMargins(0, 0, 0, 0)
  56. # Main widgets.
  57. self.label = QLineEdit(u'Hello world, مرحبا ، العالم, Γεια σου κόσμε!')
  58. self.dock = QDockWidget(u'Label', parent=self)
  59. self.dock.setObjectName(u'Label')
  60. self.dock.setWidget(self.label)
  61. #self.dock.setFeatures(QDockWidget.DockWidgetMovable|QDockWidget.DockWidgetFloatable)
  62. self.imageWidget = QLabel()
  63. self.imageWidget.setAlignment(Qt.AlignCenter)
  64. self.imageWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
  65. self.addDockWidget(Qt.BottomDockWidgetArea, self.dock)
  66. self.setCentralWidget(self.imageWidget)
  67. # Actions
  68. quit = action(self, '&Quit', self.close, 'Ctrl+Q', u'Exit application')
  69. open = action(self, '&Open', self.openFile, 'Ctrl+O', u'Open file')
  70. labl = self.dock.toggleViewAction()
  71. labl.setShortcut('Ctrl+L')
  72. add_actions(self.menu('&File'), (open, None, labl, None, quit))
  73. add_actions(self.toolbar('Tools'), (open, None, labl, None, quit))
  74. self.statusBar().showMessage('%s started.' % __appname__)
  75. self.statusBar().show()
  76. # Application state.
  77. self.image = QImage()
  78. self.filename = filename
  79. self.recent_files = []
  80. # TODO: Could be completely declarative.
  81. # Restore application settings.
  82. types = {
  83. 'filename': QString,
  84. 'recent-files': QStringList,
  85. 'window/size': QSize,
  86. 'window/position': QPoint,
  87. 'window/geometry': QByteArray,
  88. # Docks and toolbars:
  89. 'window/state': QByteArray,
  90. }
  91. self.settings = settings = Settings(types)
  92. self.recent_files = settings['recent-files']
  93. size = settings.get('window/size', QSize(600, 500))
  94. position = settings.get('window/position', QPoint(0, 0))
  95. self.resize(size)
  96. self.move(position)
  97. # or simply:
  98. #self.restoreGeometry(settings['window/geometry']
  99. self.restoreState(settings['window/state'])
  100. # The file menu has default dynamically generated entries.
  101. self.updateFileMenu()
  102. # Since loading the file may take some time, make sure it runs in the background.
  103. self.queueEvent(partial(self.loadFile, self.filename))
  104. def queueEvent(self, function):
  105. QTimer.singleShot(0, function)
  106. def loadFile(self, filename=None):
  107. """Load the specified file, or the last opened file if None."""
  108. if filename is None:
  109. filename = self.settings['filename']
  110. # FIXME: Load the actual file here.
  111. if QFile.exists(filename):
  112. # Load image
  113. image = QImage(filename)
  114. if image.isNull():
  115. message = "Failed to read %s" % filename
  116. else:
  117. message = "Loaded %s" % os.path.basename(unicode(filename))
  118. self.image = image
  119. self.filename = filename
  120. self.showImage()
  121. self.statusBar().showMessage(message)
  122. def showImage(self):
  123. if self.image.isNull():
  124. return
  125. self.imageWidget.setPixmap(QPixmap.fromImage(self.image))
  126. self.imageWidget.show()
  127. def closeEvent(self, event):
  128. # TODO: Make sure changes are saved.
  129. s = self.settings
  130. s['filename'] = self.filename if self.filename else QString()
  131. s['window/size'] = self.size()
  132. s['window/position'] = self.pos()
  133. s['window/state'] = self.saveState()
  134. #s['window/geometry'] = self.saveGeometry()
  135. def updateFileMenu(self):
  136. """Populate menu with recent files."""
  137. ## Dialogs.
  138. def openFile(self):
  139. if not self.check():
  140. return
  141. path = os.path.dirname(unicode(self.filename))\
  142. if self.filename else '.'
  143. formats = ['*.%s' % unicode(fmt).lower()\
  144. for fmt in QImageReader.supportedImageFormats()]
  145. filename = unicode(QFileDialog.getOpenFileName(self,
  146. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  147. if filename:
  148. self.loadFile(filename)
  149. def check(self):
  150. # TODO: Prompt user to save labels etc.
  151. return True
  152. class Settings(object):
  153. """Convenience dict-like wrapper around QSettings."""
  154. def __init__(self, types=None):
  155. self.data = QSettings()
  156. self.types = defaultdict(lambda: QVariant, types if types else {})
  157. def __setitem__(self, key, value):
  158. t = self.types[key]
  159. self.data.setValue(key,
  160. t(value) if not isinstance(value, t) else value)
  161. def __getitem__(self, key):
  162. return self._cast(key, self.data.value(key))
  163. def get(self, key, default=None):
  164. return self._cast(key, self.data.value(key, default))
  165. def _cast(self, key, value):
  166. # XXX: Very nasty way of converting types to QVariant methods :P
  167. t = self.types[key]
  168. if t != QVariant:
  169. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  170. return method(value)
  171. return value
  172. def main(argv):
  173. """Standard boilerplate Qt application code."""
  174. app = QApplication(argv)
  175. app.setApplicationName(__appname__)
  176. win = MainWindow(argv[1] if len(argv) == 2 else None)
  177. win.show()
  178. return app.exec_()
  179. if __name__ == '__main__':
  180. sys.exit(main(sys.argv))