labelme.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. self.addDockWidget(Qt.BottomDockWidgetArea, self.dock)
  69. self.setCentralWidget(self.canvas)
  70. # Actions
  71. quit = action(self, '&Quit', self.close, 'Ctrl+Q', u'Exit application')
  72. open = action(self, '&Open', self.openFile, 'Ctrl+O', u'Open file')
  73. color = action(self, '&Color', self.chooseColor, 'Ctrl+C', u'Choose line color')
  74. labl = self.dock.toggleViewAction()
  75. labl.setShortcut('Ctrl+L')
  76. zoom = QWidgetAction(self)
  77. zoom.setDefaultWidget(self.zoom_widget)
  78. fit_window = action(self, '&Fit Window', self.setFitWindow,
  79. 'Ctrl+F', u'Fit image to window', checkable=True)
  80. self.menus = struct(
  81. file=self.menu('&File'),
  82. edit=self.menu('&Image'),
  83. view=self.menu('&View'))
  84. add_actions(self.menus.file, (open, quit))
  85. add_actions(self.menus.edit, (color, fit_window))
  86. add_actions(self.menus.view, (labl,))
  87. self.tools = self.toolbar('Tools')
  88. add_actions(self.tools, (open, color, None, zoom, fit_window, None, quit))
  89. self.statusBar().showMessage('%s started.' % __appname__)
  90. self.statusBar().show()
  91. # Application state.
  92. self.image = QImage()
  93. self.filename = filename
  94. self.recent_files = []
  95. self.color = None
  96. self.zoom_level = 100
  97. self.fit_window = False
  98. # TODO: Could be completely declarative.
  99. # Restore application settings.
  100. types = {
  101. 'filename': QString,
  102. 'recent-files': QStringList,
  103. 'window/size': QSize,
  104. 'window/position': QPoint,
  105. 'window/geometry': QByteArray,
  106. # Docks and toolbars:
  107. 'window/state': QByteArray,
  108. }
  109. self.settings = settings = Settings(types)
  110. self.recent_files = settings['recent-files']
  111. size = settings.get('window/size', QSize(600, 500))
  112. position = settings.get('window/position', QPoint(0, 0))
  113. self.resize(size)
  114. self.move(position)
  115. # or simply:
  116. #self.restoreGeometry(settings['window/geometry']
  117. self.restoreState(settings['window/state'])
  118. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  119. # The file menu has default dynamically generated entries.
  120. self.updateFileMenu()
  121. # Since loading the file may take some time, make sure it runs in the background.
  122. self.queueEvent(partial(self.loadFile, self.filename))
  123. # Callbacks:
  124. self.zoom_widget.valueChanged.connect(self.showImage)
  125. ## Callback functions:
  126. def setFitWindow(self, value=True):
  127. self.zoom_widget.setEnabled(not value)
  128. self.fit_window = value
  129. self.showImage()
  130. def queueEvent(self, function):
  131. QTimer.singleShot(0, function)
  132. def loadFile(self, filename=None):
  133. """Load the specified file, or the last opened file if None."""
  134. if filename is None:
  135. filename = self.settings['filename']
  136. # FIXME: Load the actual file here.
  137. if QFile.exists(filename):
  138. # Load image
  139. image = QImage(filename)
  140. if image.isNull():
  141. message = "Failed to read %s" % filename
  142. else:
  143. message = "Loaded %s" % os.path.basename(unicode(filename))
  144. self.image = image
  145. self.filename = filename
  146. self.showImage()
  147. self.statusBar().showMessage(message)
  148. def resizeEvent(self, event):
  149. if self.fit_window and self.canvas and not self.image.isNull():
  150. self.showImage()
  151. super(MainWindow, self).resizeEvent(event)
  152. def showImage(self):
  153. if self.image.isNull():
  154. return
  155. size = self.imageSize()
  156. self.canvas.setPixmap(QPixmap.fromImage(self.image.scaled(
  157. size, Qt.KeepAspectRatio, Qt.SmoothTransformation)))
  158. self.canvas.show()
  159. def imageSize(self):
  160. """Calculate the size of the image based on current settings."""
  161. if self.fit_window:
  162. width, height = self.canvas.width(), self.canvas.height()
  163. else: # Follow zoom:
  164. s = self.zoom_widget.value() / 100.0
  165. width, height = s * self.image.width(), s * self.image.height()
  166. return QSize(width, height)
  167. def closeEvent(self, event):
  168. # TODO: Make sure changes are saved.
  169. s = self.settings
  170. s['filename'] = self.filename if self.filename else QString()
  171. s['window/size'] = self.size()
  172. s['window/position'] = self.pos()
  173. s['window/state'] = self.saveState()
  174. s['line/color'] = self.color
  175. #s['window/geometry'] = self.saveGeometry()
  176. def updateFileMenu(self):
  177. """Populate menu with recent files."""
  178. ## Dialogs.
  179. def openFile(self):
  180. if not self.check():
  181. return
  182. path = os.path.dirname(unicode(self.filename))\
  183. if self.filename else '.'
  184. formats = ['*.%s' % unicode(fmt).lower()\
  185. for fmt in QImageReader.supportedImageFormats()]
  186. filename = unicode(QFileDialog.getOpenFileName(self,
  187. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  188. if filename:
  189. self.loadFile(filename)
  190. def check(self):
  191. # TODO: Prompt user to save labels etc.
  192. return True
  193. def chooseColor(self):
  194. self.color = QColorDialog.getColor(self.color, self,
  195. u'Choose line color', QColorDialog.ShowAlphaChannel)
  196. class Settings(object):
  197. """Convenience dict-like wrapper around QSettings."""
  198. def __init__(self, types=None):
  199. self.data = QSettings()
  200. self.types = defaultdict(lambda: QVariant, types if types else {})
  201. def __setitem__(self, key, value):
  202. t = self.types[key]
  203. self.data.setValue(key,
  204. t(value) if not isinstance(value, t) else value)
  205. def __getitem__(self, key):
  206. return self._cast(key, self.data.value(key))
  207. def get(self, key, default=None):
  208. return self._cast(key, self.data.value(key, default))
  209. def _cast(self, key, value):
  210. # XXX: Very nasty way of converting types to QVariant methods :P
  211. t = self.types[key]
  212. if t != QVariant:
  213. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  214. return method(value)
  215. return value
  216. class struct(object):
  217. def __init__(self, **kwargs):
  218. self.__dict__.update(kwargs)
  219. def main(argv):
  220. """Standard boilerplate Qt application code."""
  221. app = QApplication(argv)
  222. app.setApplicationName(__appname__)
  223. win = MainWindow(argv[1] if len(argv) == 2 else None)
  224. win.show()
  225. return app.exec_()
  226. if __name__ == '__main__':
  227. sys.exit(main(sys.argv))