labelme.py 9.6 KB

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