labelme.py 13 KB

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