labelme.py 12 KB

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