labelme.py 10 KB

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