labelme.py 8.0 KB

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