labelme.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 base64 import b64encode, b64decode
  9. import json
  10. from PyQt4.QtGui import *
  11. from PyQt4.QtCore import *
  12. import resources
  13. from lib import newAction, addActions
  14. from shape import Shape
  15. from canvas import Canvas
  16. from zoomWidget import ZoomWidget
  17. from labelDialog import LabelDialog
  18. from labelFile import LabelFile
  19. __appname__ = 'labelme'
  20. # TODO:
  21. # - Zoom is too "steppy".
  22. # - Add a new column in list widget with checkbox to show/hide shape.
  23. # - Make sure the `save' action is disabled when no labels are
  24. # present in the image, e.g. when all of them are deleted.
  25. ### Utility functions and classes.
  26. class WindowMixin(object):
  27. def menu(self, title, actions=None):
  28. menu = self.menuBar().addMenu(title)
  29. if actions:
  30. addActions(menu, actions)
  31. return menu
  32. def toolbar(self, title, actions=None):
  33. toolbar = QToolBar(title)
  34. toolbar.setObjectName(u'%sToolBar' % title)
  35. #toolbar.setOrientation(Qt.Vertical)
  36. toolbar.setContentsMargins(0,0,0,0)
  37. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  38. toolbar.layout().setContentsMargins(0,0,0,0)
  39. if actions:
  40. addActions(toolbar, actions)
  41. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  42. return toolbar
  43. class MainWindow(QMainWindow, WindowMixin):
  44. def __init__(self, filename=None):
  45. super(MainWindow, self).__init__()
  46. self.setWindowTitle(__appname__)
  47. self.setContentsMargins(0, 0, 0, 0)
  48. # Main widgets.
  49. self.label = LabelDialog(parent=self)
  50. self.labels = {}
  51. self.highlighted = None
  52. self.labelList = QListWidget()
  53. self.dock = QDockWidget(u'Labels', self)
  54. self.dock.setObjectName(u'Labels')
  55. self.dock.setWidget(self.labelList)
  56. self.zoom_widget = ZoomWidget()
  57. self.labelList.itemActivated.connect(self.highlightLabel)
  58. self.canvas = Canvas()
  59. #self.canvas.setAlignment(Qt.AlignCenter)
  60. self.canvas.setContextMenuPolicy(Qt.ActionsContextMenu)
  61. self.canvas.zoomRequest.connect(self.zoomRequest)
  62. scroll = QScrollArea()
  63. scroll.setWidget(self.canvas)
  64. scroll.setWidgetResizable(True)
  65. self.scrollBars = {
  66. Qt.Vertical: scroll.verticalScrollBar(),
  67. Qt.Horizontal: scroll.horizontalScrollBar()
  68. }
  69. self.canvas.scrollRequest.connect(self.scrollRequest)
  70. self.canvas.newShape.connect(self.newShape)
  71. self.setCentralWidget(scroll)
  72. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  73. # Actions
  74. action = partial(newAction, self)
  75. quit = action('&Quit', self.close,
  76. 'Ctrl+Q', 'quit', u'Exit application')
  77. open = action('&Open', self.openFile,
  78. 'Ctrl+O', 'open', u'Open file')
  79. save = action('&Save', self.saveFile,
  80. 'Ctrl+S', 'save', u'Save file')
  81. color = action('&Color', self.chooseColor,
  82. 'Ctrl+C', 'color', u'Choose line color')
  83. label = action('&New Item', self.newLabel,
  84. 'Ctrl+N', 'new', u'Add new label')
  85. delete = action('&Delete', self.deleteSelectedShape,
  86. 'Ctrl+D', 'delete', u'Delete')
  87. labels = self.dock.toggleViewAction()
  88. labels.setShortcut('Ctrl+L')
  89. zoom = QWidgetAction(self)
  90. zoom.setDefaultWidget(self.zoom_widget)
  91. # Store actions for further handling.
  92. self.actions = struct(save=save, open=open, color=color,
  93. label=label, delete=delete, zoom=zoom)
  94. save.setEnabled(False)
  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, save, 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, save, color, None, label, delete, 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 loadLabels(self, shapes):
  144. s = []
  145. for label, points in shapes:
  146. shape = Shape(label=label)
  147. shape.fill = True
  148. for x, y in points:
  149. shape.addPoint(QPointF(x, y))
  150. s.append(shape)
  151. self.addLabel(label, shape)
  152. self.canvas.loadShapes(s)
  153. def saveLabels(self, filename):
  154. lf = LabelFile()
  155. shapes = [(unicode(shape.label), [(p.x(), p.y()) for p in shape.points])\
  156. for shape in self.canvas.shapes]
  157. lf.save(filename, shapes, unicode(self.filename), self.imageData)
  158. def addLabel(self, label, shape):
  159. item = QListWidgetItem(label)
  160. self.labels[item] = shape
  161. self.labelList.addItem(item)
  162. def highlightLabel(self, item):
  163. if self.highlighted:
  164. self.highlighted.fill_color = Shape.fill_color
  165. shape = self.labels[item]
  166. shape.fill_color = inverted(Shape.fill_color)
  167. self.highlighted = shape
  168. self.canvas.repaint()
  169. ## Callback functions:
  170. def newShape(self, position):
  171. """Pop-up and give focus to the label editor.
  172. position MUST be in global coordinates.
  173. """
  174. action = self.label.popUp(position)
  175. if action == self.label.OK:
  176. label = self.label.text()
  177. shape = self.canvas.setLastLabel(label)
  178. self.addLabel(label, shape)
  179. # Enable the save action.
  180. self.actions.save.setEnabled(True)
  181. # TODO: Add to list of labels.
  182. elif action == self.label.UNDO:
  183. self.canvas.undoLastLine()
  184. elif action == self.label.DELETE:
  185. self.canvas.deleteLastShape()
  186. else:
  187. assert False, "unknown label action"
  188. def scrollRequest(self, delta, orientation):
  189. units = - delta / (8 * 15)
  190. bar = self.scrollBars[orientation]
  191. bar.setValue(bar.value() + bar.singleStep() * units)
  192. def zoomRequest(self, delta):
  193. if not self.fit_window:
  194. units = delta / (8 * 15)
  195. scale = 10
  196. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  197. self.zoom_widget.editingFinished.emit()
  198. def setFitWindow(self, value=True):
  199. self.zoom_widget.setEnabled(not value)
  200. self.fit_window = value
  201. self.paintCanvas()
  202. def queueEvent(self, function):
  203. QTimer.singleShot(0, function)
  204. def loadFile(self, filename=None):
  205. """Load the specified file, or the last opened file if None."""
  206. if filename is None:
  207. filename = self.settings['filename']
  208. filename = unicode(filename)
  209. if QFile.exists(filename):
  210. if LabelFile.isLabelFile(filename):
  211. # TODO: Error handling.
  212. lf = LabelFile()
  213. lf.load(filename)
  214. self.labelFile = lf
  215. self.imageData = lf.imageData
  216. else:
  217. # Load image:
  218. # read data first and store for saving into label file.
  219. self.imageData = read(filename, None)
  220. self.labelFile = None
  221. image = QImage.fromData(self.imageData)
  222. if image.isNull():
  223. message = "Failed to read %s" % filename
  224. else:
  225. message = "Loaded %s" % os.path.basename(unicode(filename))
  226. self.image = image
  227. self.filename = filename
  228. self.labels = {}
  229. self.labelList.clear()
  230. self.canvas.loadPixmap(QPixmap.fromImage(image))
  231. if self.labelFile:
  232. self.loadLabels(self.labelFile.shapes)
  233. self.statusBar().showMessage(message)
  234. def resizeEvent(self, event):
  235. if self.fit_window and self.canvas and not self.image.isNull():
  236. self.paintCanvas()
  237. super(MainWindow, self).resizeEvent(event)
  238. def paintCanvas(self):
  239. assert not self.image.isNull(), "cannot paint null image"
  240. self.canvas.scale = self.fitSize() if self.fit_window\
  241. else 0.01 * self.zoom_widget.value()
  242. self.canvas.adjustSize()
  243. self.canvas.repaint()
  244. def fitSize(self):
  245. """Figure out the size of the pixmap in order to fit the main widget."""
  246. e = 2.0 # So that no scrollbars are generated.
  247. w1 = self.centralWidget().width() - e
  248. h1 = self.centralWidget().height() - e
  249. a1 = w1/ h1
  250. # Calculate a new scale value based on the pixmap's aspect ratio.
  251. w2 = self.canvas.pixmap.width() - 0.0
  252. h2 = self.canvas.pixmap.height() - 0.0
  253. a2 = w2 / h2
  254. return w1 / w2 if a2 >= a1 else h1 / h2
  255. def closeEvent(self, event):
  256. # TODO: Make sure changes are saved.
  257. s = self.settings
  258. s['filename'] = self.filename if self.filename else QString()
  259. s['window/size'] = self.size()
  260. s['window/position'] = self.pos()
  261. s['window/state'] = self.saveState()
  262. s['line/color'] = self.color
  263. #s['window/geometry'] = self.saveGeometry()
  264. def updateFileMenu(self):
  265. """Populate menu with recent files."""
  266. ## Dialogs.
  267. def openFile(self):
  268. if not self.check():
  269. return
  270. path = os.path.dirname(unicode(self.filename))\
  271. if self.filename else '.'
  272. formats = ['*.%s' % unicode(fmt).lower()\
  273. for fmt in QImageReader.supportedImageFormats()]
  274. filters = 'Image files (%s)\nLabel files (*%s)'\
  275. % (' '.join(formats), LabelFile.suffix)
  276. filename = unicode(QFileDialog.getOpenFileName(self,
  277. '%s - Choose Image', path, filters))
  278. if filename:
  279. self.loadFile(filename)
  280. def saveFile(self):
  281. assert not self.image.isNull(), "cannot save empty image"
  282. # XXX: What if user wants to remove label file?
  283. assert self.labels, "cannot save empty labels"
  284. path = os.path.dirname(unicode(self.filename))\
  285. if self.filename else '.'
  286. formats = ['*%s' % LabelFile.suffix]
  287. filename = unicode(QFileDialog.getSaveFileName(self,
  288. '%s - Choose File', path, 'Label files (%s)' % ''.join(formats)))
  289. if filename:
  290. self.saveLabels(filename)
  291. def check(self):
  292. # TODO: Prompt user to save labels etc.
  293. return True
  294. def chooseColor(self):
  295. self.color = QColorDialog.getColor(self.color, self,
  296. u'Choose line color', QColorDialog.ShowAlphaChannel)
  297. # Change the color for all shape lines:
  298. Shape.line_color = self.color
  299. self.canvas.repaint()
  300. def newLabel(self):
  301. self.canvas.deSelectShape()
  302. self.canvas.setEditing()
  303. def deleteSelectedShape(self):
  304. self.canvas.deleteSelected()
  305. class Settings(object):
  306. """Convenience dict-like wrapper around QSettings."""
  307. def __init__(self, types=None):
  308. self.data = QSettings()
  309. self.types = defaultdict(lambda: QVariant, types if types else {})
  310. def __setitem__(self, key, value):
  311. t = self.types[key]
  312. self.data.setValue(key,
  313. t(value) if not isinstance(value, t) else value)
  314. def __getitem__(self, key):
  315. return self._cast(key, self.data.value(key))
  316. def get(self, key, default=None):
  317. return self._cast(key, self.data.value(key, default))
  318. def _cast(self, key, value):
  319. # XXX: Very nasty way of converting types to QVariant methods :P
  320. t = self.types[key]
  321. if t != QVariant:
  322. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  323. return method(value)
  324. return value
  325. def inverted(color):
  326. return QColor(*[255 - v for v in color.getRgb()])
  327. def read(filename, default=None):
  328. try:
  329. with open(filename, 'rb') as f:
  330. return f.read()
  331. except:
  332. return default
  333. class struct(object):
  334. def __init__(self, **kwargs):
  335. self.__dict__.update(kwargs)
  336. def main(argv):
  337. """Standard boilerplate Qt application code."""
  338. app = QApplication(argv)
  339. app.setApplicationName(__appname__)
  340. win = MainWindow(argv[1] if len(argv) == 2 else None)
  341. win.show()
  342. return app.exec_()
  343. if __name__ == '__main__':
  344. sys.exit(main(sys.argv))