labelme.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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, labelValidator
  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. # FIXME
  21. # - [low] Label validation/postprocessing breaks with TAB.
  22. # TODO:
  23. # - Add a new column in list widget with checkbox to show/hide shape.
  24. # - Make sure the `save' action is disabled when no labels are
  25. # present in the image, e.g. when all of them are deleted.
  26. # - [easy] Add button to Hide/Show all labels.
  27. # - Zoom is too "steppy".
  28. ### Utility functions and classes.
  29. class WindowMixin(object):
  30. def menu(self, title, actions=None):
  31. menu = self.menuBar().addMenu(title)
  32. if actions:
  33. addActions(menu, actions)
  34. return menu
  35. def toolbar(self, title, actions=None):
  36. toolbar = QToolBar(title)
  37. toolbar.setObjectName(u'%sToolBar' % title)
  38. #toolbar.setOrientation(Qt.Vertical)
  39. toolbar.setContentsMargins(0,0,0,0)
  40. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  41. toolbar.layout().setContentsMargins(0,0,0,0)
  42. if actions:
  43. addActions(toolbar, actions)
  44. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  45. return toolbar
  46. class MainWindow(QMainWindow, WindowMixin):
  47. def __init__(self, filename=None):
  48. super(MainWindow, self).__init__()
  49. self.setWindowTitle(__appname__)
  50. self.setContentsMargins(0, 0, 0, 0)
  51. # Main widgets.
  52. self.label = LabelDialog(parent=self)
  53. self.labels = {}
  54. self.highlighted = None
  55. self.labelList = QListWidget()
  56. self.dock = QDockWidget(u'Labels', self)
  57. self.dock.setObjectName(u'Labels')
  58. self.dock.setWidget(self.labelList)
  59. self.zoom_widget = ZoomWidget()
  60. self.labelList.setItemDelegate(LabelDelegate())
  61. self.labelList.itemActivated.connect(self.highlightLabel)
  62. # Connect to itemChanged to detect checkbox changes.
  63. self.labelList.itemChanged.connect(self.labelItemChanged)
  64. self.canvas = Canvas()
  65. #self.canvas.setAlignment(Qt.AlignCenter)
  66. self.canvas.setContextMenuPolicy(Qt.ActionsContextMenu)
  67. self.canvas.zoomRequest.connect(self.zoomRequest)
  68. scroll = QScrollArea()
  69. scroll.setWidget(self.canvas)
  70. scroll.setWidgetResizable(True)
  71. self.scrollBars = {
  72. Qt.Vertical: scroll.verticalScrollBar(),
  73. Qt.Horizontal: scroll.horizontalScrollBar()
  74. }
  75. self.canvas.scrollRequest.connect(self.scrollRequest)
  76. self.canvas.newShape.connect(self.newShape)
  77. self.setCentralWidget(scroll)
  78. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  79. # Actions
  80. action = partial(newAction, self)
  81. quit = action('&Quit', self.close,
  82. 'Ctrl+Q', 'quit', u'Exit application')
  83. open = action('&Open', self.openFile,
  84. 'Ctrl+O', 'open', u'Open file')
  85. save = action('&Save', self.saveFile,
  86. 'Ctrl+S', 'save', u'Save file')
  87. color = action('&Color', self.chooseColor,
  88. 'Ctrl+C', 'color', u'Choose line color')
  89. label = action('&New Item', self.newLabel,
  90. 'Ctrl+N', 'new', u'Add new label')
  91. delete = action('&Delete', self.deleteSelectedShape,
  92. 'Ctrl+D', 'delete', u'Delete')
  93. labels = self.dock.toggleViewAction()
  94. labels.setShortcut('Ctrl+L')
  95. zoom = QWidgetAction(self)
  96. zoom.setDefaultWidget(self.zoom_widget)
  97. # Store actions for further handling.
  98. self.actions = struct(save=save, open=open, color=color,
  99. label=label, delete=delete, zoom=zoom)
  100. save.setEnabled(False)
  101. fit_window = action('&Fit Window', self.setFitWindow,
  102. 'Ctrl+F', 'fit', u'Fit image to window', checkable=True)
  103. self.menus = struct(
  104. file=self.menu('&File'),
  105. edit=self.menu('&Image'),
  106. view=self.menu('&View'))
  107. addActions(self.menus.file, (open, save, quit))
  108. addActions(self.menus.edit, (label, color, fit_window))
  109. addActions(self.menus.view, (labels,))
  110. self.tools = self.toolbar('Tools')
  111. addActions(self.tools, (open, save, color, None, label, delete, None,
  112. zoom, fit_window, None, quit))
  113. self.statusBar().showMessage('%s started.' % __appname__)
  114. self.statusBar().show()
  115. # Application state.
  116. self.image = QImage()
  117. self.filename = filename
  118. self.recent_files = []
  119. self.color = None
  120. self.zoom_level = 100
  121. self.fit_window = False
  122. # TODO: Could be completely declarative.
  123. # Restore application settings.
  124. types = {
  125. 'filename': QString,
  126. 'recent-files': QStringList,
  127. 'window/size': QSize,
  128. 'window/position': QPoint,
  129. 'window/geometry': QByteArray,
  130. # Docks and toolbars:
  131. 'window/state': QByteArray,
  132. }
  133. self.settings = settings = Settings(types)
  134. self.recent_files = settings['recent-files']
  135. size = settings.get('window/size', QSize(600, 500))
  136. position = settings.get('window/position', QPoint(0, 0))
  137. self.resize(size)
  138. self.move(position)
  139. # or simply:
  140. #self.restoreGeometry(settings['window/geometry']
  141. self.restoreState(settings['window/state'])
  142. self.color = QColor(settings.get('line/color', QColor(0, 255, 0, 128)))
  143. # The file menu has default dynamically generated entries.
  144. self.updateFileMenu()
  145. # Since loading the file may take some time, make sure it runs in the background.
  146. self.queueEvent(partial(self.loadFile, self.filename))
  147. # Callbacks:
  148. self.zoom_widget.editingFinished.connect(self.paintCanvas)
  149. def loadLabels(self, shapes):
  150. s = []
  151. for label, points in shapes:
  152. shape = Shape(label=label)
  153. shape.fill = True
  154. for x, y in points:
  155. shape.addPoint(QPointF(x, y))
  156. s.append(shape)
  157. self.addLabel(label, shape)
  158. self.canvas.loadShapes(s)
  159. def saveLabels(self, filename):
  160. lf = LabelFile()
  161. shapes = [(unicode(shape.label), [(p.x(), p.y()) for p in shape.points])\
  162. for shape in self.canvas.shapes]
  163. lf.save(filename, shapes, unicode(self.filename), self.imageData)
  164. def addLabel(self, label, shape):
  165. item = QListWidgetItem(label)
  166. item.setFlags(item.flags() | Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
  167. item.setCheckState(Qt.Checked)
  168. self.labels[item] = shape
  169. self.labelList.addItem(item)
  170. def highlightLabel(self, item):
  171. if self.highlighted:
  172. self.highlighted.fill_color = Shape.fill_color
  173. shape = self.labels[item]
  174. shape.fill_color = inverted(Shape.fill_color)
  175. self.highlighted = shape
  176. self.canvas.repaint()
  177. def labelItemChanged(self, item):
  178. shape = self.labels[item]
  179. label = unicode(item.text())
  180. if label != shape.label:
  181. self.stateChanged()
  182. shape.label = unicode(item.text())
  183. else: # User probably changed item visibility
  184. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  185. def stateChanged(self):
  186. self.actions.save.setEnabled(True)
  187. ## Callback functions:
  188. def newShape(self, position):
  189. """Pop-up and give focus to the label editor.
  190. position MUST be in global coordinates.
  191. """
  192. action = self.label.popUp(position)
  193. if action == self.label.OK:
  194. label = self.label.text()
  195. shape = self.canvas.setLastLabel(label)
  196. self.addLabel(label, shape)
  197. # Enable the save action.
  198. self.actions.save.setEnabled(True)
  199. # TODO: Add to list of labels.
  200. elif action == self.label.UNDO:
  201. self.canvas.undoLastLine()
  202. elif action == self.label.DELETE:
  203. self.canvas.deleteLastShape()
  204. else:
  205. assert False, "unknown label action"
  206. def scrollRequest(self, delta, orientation):
  207. units = - delta / (8 * 15)
  208. bar = self.scrollBars[orientation]
  209. bar.setValue(bar.value() + bar.singleStep() * units)
  210. def zoomRequest(self, delta):
  211. if not self.fit_window:
  212. units = delta / (8 * 15)
  213. scale = 10
  214. self.zoom_widget.setValue(self.zoom_widget.value() + scale * units)
  215. self.zoom_widget.editingFinished.emit()
  216. def setFitWindow(self, value=True):
  217. self.zoom_widget.setEnabled(not value)
  218. self.fit_window = value
  219. self.paintCanvas()
  220. def queueEvent(self, function):
  221. QTimer.singleShot(0, function)
  222. def loadFile(self, filename=None):
  223. """Load the specified file, or the last opened file if None."""
  224. if filename is None:
  225. filename = self.settings['filename']
  226. filename = unicode(filename)
  227. if QFile.exists(filename):
  228. if LabelFile.isLabelFile(filename):
  229. # TODO: Error handling.
  230. lf = LabelFile()
  231. lf.load(filename)
  232. self.labelFile = lf
  233. self.imageData = lf.imageData
  234. else:
  235. # Load image:
  236. # read data first and store for saving into label file.
  237. self.imageData = read(filename, None)
  238. self.labelFile = None
  239. image = QImage.fromData(self.imageData)
  240. if image.isNull():
  241. message = "Failed to read %s" % filename
  242. else:
  243. message = "Loaded %s" % os.path.basename(unicode(filename))
  244. self.image = image
  245. self.filename = filename
  246. self.labels = {}
  247. self.labelList.clear()
  248. self.canvas.loadPixmap(QPixmap.fromImage(image))
  249. if self.labelFile:
  250. self.loadLabels(self.labelFile.shapes)
  251. self.statusBar().showMessage(message)
  252. def resizeEvent(self, event):
  253. if self.fit_window and self.canvas and not self.image.isNull():
  254. self.paintCanvas()
  255. super(MainWindow, self).resizeEvent(event)
  256. def paintCanvas(self):
  257. assert not self.image.isNull(), "cannot paint null image"
  258. self.canvas.scale = self.fitSize() if self.fit_window\
  259. else 0.01 * self.zoom_widget.value()
  260. self.canvas.adjustSize()
  261. self.canvas.repaint()
  262. def fitSize(self):
  263. """Figure out the size of the pixmap in order to fit the main widget."""
  264. e = 2.0 # So that no scrollbars are generated.
  265. w1 = self.centralWidget().width() - e
  266. h1 = self.centralWidget().height() - e
  267. a1 = w1/ h1
  268. # Calculate a new scale value based on the pixmap's aspect ratio.
  269. w2 = self.canvas.pixmap.width() - 0.0
  270. h2 = self.canvas.pixmap.height() - 0.0
  271. a2 = w2 / h2
  272. return w1 / w2 if a2 >= a1 else h1 / h2
  273. def closeEvent(self, event):
  274. # TODO: Make sure changes are saved.
  275. s = self.settings
  276. s['filename'] = self.filename if self.filename else QString()
  277. s['window/size'] = self.size()
  278. s['window/position'] = self.pos()
  279. s['window/state'] = self.saveState()
  280. s['line/color'] = self.color
  281. #s['window/geometry'] = self.saveGeometry()
  282. def updateFileMenu(self):
  283. """Populate menu with recent files."""
  284. ## Dialogs.
  285. def openFile(self):
  286. if not self.check():
  287. return
  288. path = os.path.dirname(unicode(self.filename))\
  289. if self.filename else '.'
  290. formats = ['*.%s' % unicode(fmt).lower()\
  291. for fmt in QImageReader.supportedImageFormats()]
  292. filters = 'Image files (%s)\nLabel files (*%s)'\
  293. % (' '.join(formats), LabelFile.suffix)
  294. filename = unicode(QFileDialog.getOpenFileName(self,
  295. '%s - Choose Image', path, filters))
  296. if filename:
  297. self.loadFile(filename)
  298. def saveFile(self):
  299. assert not self.image.isNull(), "cannot save empty image"
  300. # XXX: What if user wants to remove label file?
  301. assert self.labels, "cannot save empty labels"
  302. path = os.path.dirname(unicode(self.filename))\
  303. if self.filename else '.'
  304. formats = ['*%s' % LabelFile.suffix]
  305. filename = unicode(QFileDialog.getSaveFileName(self,
  306. '%s - Choose File', path, 'Label files (%s)' % ''.join(formats)))
  307. if filename:
  308. self.saveLabels(filename)
  309. def check(self):
  310. # TODO: Prompt user to save labels etc.
  311. return True
  312. def chooseColor(self):
  313. self.color = QColorDialog.getColor(self.color, self,
  314. u'Choose line color', QColorDialog.ShowAlphaChannel)
  315. # Change the color for all shape lines:
  316. Shape.line_color = self.color
  317. self.canvas.repaint()
  318. def newLabel(self):
  319. self.canvas.deSelectShape()
  320. self.canvas.setEditing()
  321. def deleteSelectedShape(self):
  322. self.canvas.deleteSelected()
  323. class LabelDelegate(QItemDelegate):
  324. def __init__(self, parent=None):
  325. super(LabelDelegate, self).__init__(parent)
  326. self.validator = labelValidator()
  327. # FIXME: Validation and trimming are completely broken if the
  328. # user navigates away from the editor with something like TAB.
  329. def createEditor(self, parent, option, index):
  330. """Make sure the user cannot enter empty labels.
  331. Also remove trailing whitespace."""
  332. edit = super(LabelDelegate, self).createEditor(parent, option, index)
  333. if isinstance(edit, QLineEdit):
  334. edit.setValidator(self.validator)
  335. def strip():
  336. edit.setText(edit.text().trimmed())
  337. edit.editingFinished.connect(strip)
  338. return edit
  339. class Settings(object):
  340. """Convenience dict-like wrapper around QSettings."""
  341. def __init__(self, types=None):
  342. self.data = QSettings()
  343. self.types = defaultdict(lambda: QVariant, types if types else {})
  344. def __setitem__(self, key, value):
  345. t = self.types[key]
  346. self.data.setValue(key,
  347. t(value) if not isinstance(value, t) else value)
  348. def __getitem__(self, key):
  349. return self._cast(key, self.data.value(key))
  350. def get(self, key, default=None):
  351. return self._cast(key, self.data.value(key, default))
  352. def _cast(self, key, value):
  353. # XXX: Very nasty way of converting types to QVariant methods :P
  354. t = self.types[key]
  355. if t != QVariant:
  356. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  357. return method(value)
  358. return value
  359. def inverted(color):
  360. return QColor(*[255 - v for v in color.getRgb()])
  361. def read(filename, default=None):
  362. try:
  363. with open(filename, 'rb') as f:
  364. return f.read()
  365. except:
  366. return default
  367. class struct(object):
  368. def __init__(self, **kwargs):
  369. self.__dict__.update(kwargs)
  370. def main(argv):
  371. """Standard boilerplate Qt application code."""
  372. app = QApplication(argv)
  373. app.setApplicationName(__appname__)
  374. win = MainWindow(argv[1] if len(argv) == 2 else None)
  375. win.show()
  376. return app.exec_()
  377. if __name__ == '__main__':
  378. sys.exit(main(sys.argv))