labelme.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. import resources
  11. from lib import newAction, addActions
  12. from shape import Shape
  13. from canvas import Canvas
  14. from zoomWidget import ZoomWidget
  15. from labelDialog import LabelDialog
  16. __appname__ = 'labelme'
  17. # TODO:
  18. # - Zoom is too "steppy".
  19. ### Utility functions and classes.
  20. class WindowMixin(object):
  21. def menu(self, title, actions=None):
  22. menu = self.menuBar().addMenu(title)
  23. if actions:
  24. addActions(menu, actions)
  25. return menu
  26. def toolbar(self, title, actions=None):
  27. toolbar = QToolBar(title)
  28. toolbar.setObjectName(u'%sToolBar' % title)
  29. #toolbar.setOrientation(Qt.Vertical)
  30. toolbar.setContentsMargins(0,0,0,0)
  31. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  32. toolbar.layout().setContentsMargins(0,0,0,0)
  33. if actions:
  34. addActions(toolbar, actions)
  35. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  36. return toolbar
  37. class MainWindow(QMainWindow, WindowMixin):
  38. def __init__(self, filename=None):
  39. super(MainWindow, self).__init__()
  40. self.setWindowTitle(__appname__)
  41. self.setContentsMargins(0, 0, 0, 0)
  42. # Main widgets.
  43. self.label = LabelDialog(parent=self)
  44. self.zoom_widget = ZoomWidget()
  45. self.canvas = Canvas()
  46. #self.canvas.setAlignment(Qt.AlignCenter)
  47. self.canvas.setContextMenuPolicy(Qt.ActionsContextMenu)
  48. self.canvas.zoomRequest.connect(self.zoomRequest)
  49. scroll = QScrollArea()
  50. scroll.setWidget(self.canvas)
  51. scroll.setWidgetResizable(True)
  52. self.scrollBars = {
  53. Qt.Vertical: scroll.verticalScrollBar(),
  54. Qt.Horizontal: scroll.horizontalScrollBar()
  55. }
  56. self.canvas.scrollRequest.connect(self.scrollRequest)
  57. self.canvas.newShape.connect(self.newShape)
  58. self.setCentralWidget(scroll)
  59. # Actions
  60. action = partial(newAction, self)
  61. quit = action('&Quit', self.close,
  62. 'Ctrl+Q', 'quit', u'Exit application')
  63. open = action('&Open', self.openFile,
  64. 'Ctrl+O', 'open', u'Open file')
  65. color = action('&Color', self.chooseColor,
  66. 'Ctrl+C', 'color', u'Choose line color')
  67. label = action('&New Item', self.newLabel,
  68. 'Ctrl+N', 'new', u'Add new label')
  69. delete = action('&Delete', self.deleteSelectedShape,
  70. 'Ctrl+D', 'delete', u'Delete')
  71. zoom = QWidgetAction(self)
  72. zoom.setDefaultWidget(self.zoom_widget)
  73. fit_window = action('&Fit Window', self.setFitWindow,
  74. 'Ctrl+F', 'fit', u'Fit image to window', checkable=True)
  75. self.menus = struct(
  76. file=self.menu('&File'),
  77. edit=self.menu('&Image'),
  78. view=self.menu('&View'))
  79. addActions(self.menus.file, (open, quit))
  80. addActions(self.menus.edit, (label, color, fit_window))
  81. #addActions(self.menus.view, (labl,))
  82. self.tools = self.toolbar('Tools')
  83. addActions(self.tools, (open, color, None, label, delete, None,
  84. zoom, fit_window, None, quit))
  85. self.statusBar().showMessage('%s started.' % __appname__)
  86. self.statusBar().show()
  87. # Application state.
  88. self.image = QImage()
  89. self.filename = filename
  90. self.recent_files = []
  91. self.color = None
  92. self.zoom_level = 100
  93. self.fit_window = False
  94. # TODO: Could be completely declarative.
  95. # Restore application settings.
  96. types = {
  97. 'filename': QString,
  98. 'recent-files': QStringList,
  99. 'window/size': QSize,
  100. 'window/position': QPoint,
  101. 'window/geometry': QByteArray,
  102. # Docks and toolbars:
  103. 'window/state': QByteArray,
  104. }
  105. self.settings = settings = Settings(types)
  106. self.recent_files = settings['recent-files']
  107. size = settings.get('window/size', QSize(600, 500))
  108. position = settings.get('window/position', QPoint(0, 0))
  109. self.resize(size)
  110. self.move(position)
  111. # or simply:
  112. #self.restoreGeometry(settings['window/geometry']
  113. self.restoreState(settings['window/state'])
  114. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  115. # The file menu has default dynamically generated entries.
  116. self.updateFileMenu()
  117. # Since loading the file may take some time, make sure it runs in the background.
  118. self.queueEvent(partial(self.loadFile, self.filename))
  119. # Callbacks:
  120. self.zoom_widget.editingFinished.connect(self.paintCanvas)
  121. ## Callback functions:
  122. def newShape(self, position):
  123. """Pop-up and give focus to the label editor.
  124. position MUST be in global coordinates.
  125. """
  126. action = self.label.popUp(position)
  127. if action == self.label.OK:
  128. print "Setting label to %s" % self.label.text()
  129. self.canvas.setLastLabel(self.label.text())
  130. # TODO: Add to list of labels.
  131. elif action == self.label.UNDO:
  132. print "Undo last line"
  133. self.canvas.undoLastLine()
  134. elif action == self.label.DELETE:
  135. self.canvas.deleteLastShape()
  136. else:
  137. assert False, "unknown label action"
  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.paintCanvas()
  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.loadPixmap()
  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.paintCanvas()
  173. super(MainWindow, self).resizeEvent(event)
  174. def loadPixmap(self):
  175. assert not self.image.isNull(), "cannot load null image"
  176. self.canvas.pixmap = QPixmap.fromImage(self.image)
  177. def paintCanvas(self):
  178. assert not self.image.isNull(), "cannot paint null image"
  179. self.canvas.scale = self.fitSize() if self.fit_window\
  180. else 0.01 * self.zoom_widget.value()
  181. self.canvas.adjustSize()
  182. self.canvas.repaint()
  183. def fitSize(self):
  184. """Figure out the size of the pixmap in order to fit the main widget."""
  185. e = 2.0 # So that no scrollbars are generated.
  186. w1 = self.centralWidget().width() - e
  187. h1 = self.centralWidget().height() - e
  188. a1 = w1/ h1
  189. # Calculate a new scale value based on the pixmap's aspect ratio.
  190. w2 = self.canvas.pixmap.width() - 0.0
  191. h2 = self.canvas.pixmap.height() - 0.0
  192. a2 = w2 / h2
  193. return w1 / w2 if a2 >= a1 else h1 / h2
  194. def closeEvent(self, event):
  195. # TODO: Make sure changes are saved.
  196. s = self.settings
  197. s['filename'] = self.filename if self.filename else QString()
  198. s['window/size'] = self.size()
  199. s['window/position'] = self.pos()
  200. s['window/state'] = self.saveState()
  201. s['line/color'] = self.color
  202. #s['window/geometry'] = self.saveGeometry()
  203. def updateFileMenu(self):
  204. """Populate menu with recent files."""
  205. ## Dialogs.
  206. def openFile(self):
  207. if not self.check():
  208. return
  209. path = os.path.dirname(unicode(self.filename))\
  210. if self.filename else '.'
  211. formats = ['*.%s' % unicode(fmt).lower()\
  212. for fmt in QImageReader.supportedImageFormats()]
  213. filename = unicode(QFileDialog.getOpenFileName(self,
  214. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  215. if filename:
  216. self.loadFile(filename)
  217. def check(self):
  218. # TODO: Prompt user to save labels etc.
  219. return True
  220. def chooseColor(self):
  221. self.color = QColorDialog.getColor(self.color, self,
  222. u'Choose line color', QColorDialog.ShowAlphaChannel)
  223. # Change the color for all shape lines:
  224. Shape.line_color = self.color
  225. self.canvas.repaint()
  226. def newLabel(self):
  227. self.canvas.deSelectShape()
  228. self.canvas.startLabeling=True
  229. def deleteSelectedShape(self):
  230. self.canvas.deleteSelected()
  231. class Settings(object):
  232. """Convenience dict-like wrapper around QSettings."""
  233. def __init__(self, types=None):
  234. self.data = QSettings()
  235. self.types = defaultdict(lambda: QVariant, types if types else {})
  236. def __setitem__(self, key, value):
  237. t = self.types[key]
  238. self.data.setValue(key,
  239. t(value) if not isinstance(value, t) else value)
  240. def __getitem__(self, key):
  241. return self._cast(key, self.data.value(key))
  242. def get(self, key, default=None):
  243. return self._cast(key, self.data.value(key, default))
  244. def _cast(self, key, value):
  245. # XXX: Very nasty way of converting types to QVariant methods :P
  246. t = self.types[key]
  247. if t != QVariant:
  248. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  249. return method(value)
  250. return value
  251. class struct(object):
  252. def __init__(self, **kwargs):
  253. self.__dict__.update(kwargs)
  254. def main(argv):
  255. """Standard boilerplate Qt application code."""
  256. app = QApplication(argv)
  257. app.setApplicationName(__appname__)
  258. win = MainWindow(argv[1] if len(argv) == 2 else None)
  259. win.show()
  260. return app.exec_()
  261. if __name__ == '__main__':
  262. sys.exit(main(sys.argv))