labelme.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. self.canvas.setLastLabel(self.label.text())
  129. # TODO: Add to list of labels.
  130. elif action == self.label.UNDO:
  131. self.canvas.undoLastLine()
  132. elif action == self.label.DELETE:
  133. self.canvas.deleteLastShape()
  134. else:
  135. assert False, "unknown label action"
  136. def scrollRequest(self, delta, orientation):
  137. units = - delta / (8 * 15)
  138. bar = self.scrollBars[orientation]
  139. bar.setValue(bar.value() + bar.singleStep() * units)
  140. def zoomRequest(self, delta):
  141. if not self.fit_window:
  142. units = delta / (8 * 15)
  143. scale = 10
  144. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  145. self.zoom_widget.editingFinished.emit()
  146. def setFitWindow(self, value=True):
  147. self.zoom_widget.setEnabled(not value)
  148. self.fit_window = value
  149. self.paintCanvas()
  150. def queueEvent(self, function):
  151. QTimer.singleShot(0, function)
  152. def loadFile(self, filename=None):
  153. """Load the specified file, or the last opened file if None."""
  154. if filename is None:
  155. filename = self.settings['filename']
  156. # FIXME: Load the actual file here.
  157. if QFile.exists(filename):
  158. # Load image
  159. image = QImage(filename)
  160. if image.isNull():
  161. message = "Failed to read %s" % filename
  162. else:
  163. message = "Loaded %s" % os.path.basename(unicode(filename))
  164. self.image = image
  165. self.filename = filename
  166. self.loadPixmap()
  167. self.statusBar().showMessage(message)
  168. def resizeEvent(self, event):
  169. if self.fit_window and self.canvas and not self.image.isNull():
  170. self.paintCanvas()
  171. super(MainWindow, self).resizeEvent(event)
  172. def loadPixmap(self):
  173. assert not self.image.isNull(), "cannot load null image"
  174. self.canvas.pixmap = QPixmap.fromImage(self.image)
  175. def paintCanvas(self):
  176. assert not self.image.isNull(), "cannot paint null image"
  177. self.canvas.scale = self.fitSize() if self.fit_window\
  178. else 0.01 * self.zoom_widget.value()
  179. self.canvas.adjustSize()
  180. self.canvas.repaint()
  181. def fitSize(self):
  182. """Figure out the size of the pixmap in order to fit the main widget."""
  183. e = 2.0 # So that no scrollbars are generated.
  184. w1 = self.centralWidget().width() - e
  185. h1 = self.centralWidget().height() - e
  186. a1 = w1/ h1
  187. # Calculate a new scale value based on the pixmap's aspect ratio.
  188. w2 = self.canvas.pixmap.width() - 0.0
  189. h2 = self.canvas.pixmap.height() - 0.0
  190. a2 = w2 / h2
  191. return w1 / w2 if a2 >= a1 else h1 / h2
  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. def newLabel(self):
  225. self.canvas.deSelectShape()
  226. self.canvas.setEditing()
  227. def deleteSelectedShape(self):
  228. self.canvas.deleteSelected()
  229. class Settings(object):
  230. """Convenience dict-like wrapper around QSettings."""
  231. def __init__(self, types=None):
  232. self.data = QSettings()
  233. self.types = defaultdict(lambda: QVariant, types if types else {})
  234. def __setitem__(self, key, value):
  235. t = self.types[key]
  236. self.data.setValue(key,
  237. t(value) if not isinstance(value, t) else value)
  238. def __getitem__(self, key):
  239. return self._cast(key, self.data.value(key))
  240. def get(self, key, default=None):
  241. return self._cast(key, self.data.value(key, default))
  242. def _cast(self, key, value):
  243. # XXX: Very nasty way of converting types to QVariant methods :P
  244. t = self.types[key]
  245. if t != QVariant:
  246. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  247. return method(value)
  248. return value
  249. class struct(object):
  250. def __init__(self, **kwargs):
  251. self.__dict__.update(kwargs)
  252. def main(argv):
  253. """Standard boilerplate Qt application code."""
  254. app = QApplication(argv)
  255. app.setApplicationName(__appname__)
  256. win = MainWindow(argv[1] if len(argv) == 2 else None)
  257. win.show()
  258. return app.exec_()
  259. if __name__ == '__main__':
  260. sys.exit(main(sys.argv))