labelme.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. copy = action('&Copy', self.copySelectedShape,
  79. 'Ctrl+C', 'copy', u'Copy')
  80. delete = action('&Delete', self.deleteSelectedShape,
  81. 'Ctrl+D', 'delete', u'Delete')
  82. hide = action('&Hide labels', self.hideLabelsToggle,
  83. 'Ctrl+H', 'hide', u'Hide background labels when drawing',
  84. checkable=True)
  85. self.canvas.setContextMenuPolicy( Qt.CustomContextMenu )
  86. self.canvas.customContextMenuRequested.connect(self.popContextMenu)
  87. # Popup Menu
  88. self.popMenu = QMenu(self )
  89. self.popMenu.addAction( label )
  90. self.popMenu.addAction(copy)
  91. self.popMenu.addAction( delete )
  92. labels = self.dock.toggleViewAction()
  93. labels.setShortcut('Ctrl+L')
  94. zoom = QWidgetAction(self)
  95. zoom.setDefaultWidget(self.zoom_widget)
  96. fit_window = action('&Fit Window', self.setFitWindow,
  97. 'Ctrl+F', 'fit', u'Fit image to window', checkable=True)
  98. self.menus = struct(
  99. file=self.menu('&File'),
  100. edit=self.menu('&Image'),
  101. view=self.menu('&View'))
  102. addActions(self.menus.file, (open, quit))
  103. addActions(self.menus.edit, (label, color, fit_window))
  104. addActions(self.menus.view, (labels,))
  105. self.tools = self.toolbar('Tools')
  106. addActions(self.tools, (open, color, None, label, delete, hide, None,
  107. zoom, fit_window, None, quit))
  108. self.statusBar().showMessage('%s started.' % __appname__)
  109. self.statusBar().show()
  110. # Application state.
  111. self.image = QImage()
  112. self.filename = filename
  113. self.recent_files = []
  114. self.color = None
  115. self.zoom_level = 100
  116. self.fit_window = False
  117. # TODO: Could be completely declarative.
  118. # Restore application settings.
  119. types = {
  120. 'filename': QString,
  121. 'recent-files': QStringList,
  122. 'window/size': QSize,
  123. 'window/position': QPoint,
  124. 'window/geometry': QByteArray,
  125. # Docks and toolbars:
  126. 'window/state': QByteArray,
  127. }
  128. self.settings = settings = Settings(types)
  129. self.recent_files = settings['recent-files']
  130. size = settings.get('window/size', QSize(600, 500))
  131. position = settings.get('window/position', QPoint(0, 0))
  132. self.resize(size)
  133. self.move(position)
  134. # or simply:
  135. #self.restoreGeometry(settings['window/geometry']
  136. self.restoreState(settings['window/state'])
  137. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  138. # The file menu has default dynamically generated entries.
  139. self.updateFileMenu()
  140. # Since loading the file may take some time, make sure it runs in the background.
  141. self.queueEvent(partial(self.loadFile, self.filename))
  142. # Callbacks:
  143. self.zoom_widget.editingFinished.connect(self.paintCanvas)
  144. def popContextMenu(self, point):
  145. self.popMenu.exec_(self.canvas.mapToGlobal(point))
  146. def addLabel(self, shape):
  147. item = QListWidgetItem(shape.label)
  148. self.labels[item] = shape
  149. self.labelList.addItem(item)
  150. def copySelectedShape(self):
  151. self.addLabel(self.copySelectedShape())
  152. def highlightLabel(self, item):
  153. if self.highlighted:
  154. self.highlighted.fill_color = Shape.fill_color
  155. shape = self.labels[item]
  156. shape.fill_color = inverted(Shape.fill_color)
  157. self.highlighted = shape
  158. self.canvas.repaint()
  159. ## Callback functions:
  160. def newShape(self, position):
  161. """Pop-up and give focus to the label editor.
  162. position MUST be in global coordinates.
  163. """
  164. action = self.label.popUp(position)
  165. if action == self.label.OK:
  166. self.addLabel(self.canvas.setLastLabel(self.label.text()))
  167. elif action == self.label.UNDO:
  168. self.canvas.undoLastLine()
  169. elif action == self.label.DELETE:
  170. self.canvas.deleteLastShape()
  171. else:
  172. assert False, "unknown label action"
  173. def scrollRequest(self, delta, orientation):
  174. units = - delta / (8 * 15)
  175. bar = self.scrollBars[orientation]
  176. bar.setValue(bar.value() + bar.singleStep() * units)
  177. def zoomRequest(self, delta):
  178. if not self.fit_window:
  179. units = delta / (8 * 15)
  180. scale = 10
  181. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  182. self.zoom_widget.editingFinished.emit()
  183. def setFitWindow(self, value=True):
  184. self.zoom_widget.setEnabled(not value)
  185. self.fit_window = value
  186. self.paintCanvas()
  187. def queueEvent(self, function):
  188. QTimer.singleShot(0, function)
  189. def hideLabelsToggle(self, value):
  190. self.canvas.hideBackroundShapes(value)
  191. def loadFile(self, filename=None):
  192. """Load the specified file, or the last opened file if None."""
  193. if filename is None:
  194. filename = self.settings['filename']
  195. # FIXME: Load the actual file here.
  196. if QFile.exists(filename):
  197. # Load image
  198. image = QImage(filename)
  199. if image.isNull():
  200. message = "Failed to read %s" % filename
  201. else:
  202. message = "Loaded %s" % os.path.basename(unicode(filename))
  203. self.image = image
  204. self.filename = filename
  205. self.loadPixmap()
  206. self.statusBar().showMessage(message)
  207. def resizeEvent(self, event):
  208. if self.fit_window and self.canvas and not self.image.isNull():
  209. self.paintCanvas()
  210. super(MainWindow, self).resizeEvent(event)
  211. def loadPixmap(self):
  212. assert not self.image.isNull(), "cannot load null image"
  213. self.canvas.pixmap = QPixmap.fromImage(self.image)
  214. def paintCanvas(self):
  215. assert not self.image.isNull(), "cannot paint null image"
  216. self.canvas.scale = self.fitSize() if self.fit_window\
  217. else 0.01 * self.zoom_widget.value()
  218. self.canvas.adjustSize()
  219. self.canvas.repaint()
  220. def fitSize(self):
  221. """Figure out the size of the pixmap in order to fit the main widget."""
  222. e = 2.0 # So that no scrollbars are generated.
  223. w1 = self.centralWidget().width() - e
  224. h1 = self.centralWidget().height() - e
  225. a1 = w1/ h1
  226. # Calculate a new scale value based on the pixmap's aspect ratio.
  227. w2 = self.canvas.pixmap.width() - 0.0
  228. h2 = self.canvas.pixmap.height() - 0.0
  229. a2 = w2 / h2
  230. return w1 / w2 if a2 >= a1 else h1 / h2
  231. def closeEvent(self, event):
  232. # TODO: Make sure changes are saved.
  233. s = self.settings
  234. s['filename'] = self.filename if self.filename else QString()
  235. s['window/size'] = self.size()
  236. s['window/position'] = self.pos()
  237. s['window/state'] = self.saveState()
  238. s['line/color'] = self.color
  239. # ask the use for where to save the labels
  240. #s['window/geometry'] = self.saveGeometry()
  241. def updateFileMenu(self):
  242. """Populate menu with recent files."""
  243. ## Dialogs.
  244. def openFile(self):
  245. if not self.check():
  246. return
  247. path = os.path.dirname(unicode(self.filename))\
  248. if self.filename else '.'
  249. formats = ['*.%s' % unicode(fmt).lower()\
  250. for fmt in QImageReader.supportedImageFormats()]
  251. filename = unicode(QFileDialog.getOpenFileName(self,
  252. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  253. if filename:
  254. self.loadFile(filename)
  255. def check(self):
  256. # TODO: Prompt user to save labels etc.
  257. return True
  258. def chooseColor(self):
  259. self.color = QColorDialog.getColor(self.color, self,
  260. u'Choose line color', QColorDialog.ShowAlphaChannel)
  261. # Change the color for all shape lines:
  262. Shape.line_color = self.color
  263. self.canvas.repaint()
  264. def newLabel(self):
  265. self.canvas.deSelectShape()
  266. self.canvas.setEditing()
  267. def deleteSelectedShape(self):
  268. self.canvas.deleteSelected()
  269. class Settings(object):
  270. """Convenience dict-like wrapper around QSettings."""
  271. def __init__(self, types=None):
  272. self.data = QSettings()
  273. self.types = defaultdict(lambda: QVariant, types if types else {})
  274. def __setitem__(self, key, value):
  275. t = self.types[key]
  276. self.data.setValue(key,
  277. t(value) if not isinstance(value, t) else value)
  278. def __getitem__(self, key):
  279. return self._cast(key, self.data.value(key))
  280. def get(self, key, default=None):
  281. return self._cast(key, self.data.value(key, default))
  282. def _cast(self, key, value):
  283. # XXX: Very nasty way of converting types to QVariant methods :P
  284. t = self.types[key]
  285. if t != QVariant:
  286. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  287. return method(value)
  288. return value
  289. def inverted(color):
  290. return QColor(*[255 - v for v in color.getRgb()])
  291. class struct(object):
  292. def __init__(self, **kwargs):
  293. self.__dict__.update(kwargs)
  294. def main(argv):
  295. """Standard boilerplate Qt application code."""
  296. app = QApplication(argv)
  297. app.setApplicationName(__appname__)
  298. win = MainWindow(argv[1] if len(argv) == 2 else None)
  299. win.show()
  300. return app.exec_()
  301. if __name__ == '__main__':
  302. sys.exit(main(sys.argv))