labelme.py 9.2 KB

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