labelme.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 struct, newAction, addActions, labelValidator
  12. from shape import Shape, DEFAULT_LINE_COLOR, DEFAULT_FILL_COLOR
  13. from canvas import Canvas
  14. from zoomWidget import ZoomWidget
  15. from labelDialog import LabelDialog
  16. from colorDialog import ColorDialog
  17. from labelFile import LabelFile, LabelFileError
  18. from toolBar import ToolBar
  19. __appname__ = 'labelme'
  20. # FIXME
  21. # - [medium] Set max zoom value to something big enough for FitWidth/Window
  22. # - [medium] Disabling the save button prevents the user from saving to
  23. # alternate files. Either keep enabled, or add "Save As" button.
  24. # - [low] Label validation/postprocessing breaks with TAB.
  25. # TODO:
  26. # - [medium] Highlight label list on shape selection and vice-verca.
  27. # - [medium] Add undo button for vertex addition.
  28. # - [medium,maybe] Support vertex moving.
  29. # - [low,easy] Add button to Hide/Show all labels.
  30. # - [low,maybe] Open images with drag & drop.
  31. # - [low,maybe] Preview images on file dialogs.
  32. # - [low,maybe] Sortable label list.
  33. # - [extra] Add beginner/advanced mode, where different settings are set for
  34. # the application, e.g. closable labels, different toolbuttons etc.
  35. # - Zoom is too "steppy".
  36. ### Utility functions and classes.
  37. class WindowMixin(object):
  38. def menu(self, title, actions=None):
  39. menu = self.menuBar().addMenu(title)
  40. if actions:
  41. addActions(menu, actions)
  42. return menu
  43. def toolbar(self, title, actions=None):
  44. toolbar = ToolBar(title)
  45. toolbar.setObjectName(u'%sToolBar' % title)
  46. #toolbar.setOrientation(Qt.Vertical)
  47. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  48. if actions:
  49. addActions(toolbar, actions)
  50. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  51. return toolbar
  52. class MainWindow(QMainWindow, WindowMixin):
  53. FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = range(3)
  54. def __init__(self, filename=None):
  55. super(MainWindow, self).__init__()
  56. self.setWindowTitle(__appname__)
  57. # Not sure this does anything really.
  58. self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
  59. # Whether we need to save or not.
  60. self.dirty = False
  61. # Main widgets.
  62. self.label = LabelDialog(parent=self)
  63. self.labels = {}
  64. self.items = {}
  65. self.highlighted = None
  66. self.labelList = QListWidget()
  67. self.dock = QDockWidget(u'Labels', self)
  68. self.dock.setObjectName(u'Labels')
  69. self.dock.setWidget(self.labelList)
  70. self.zoomWidget = ZoomWidget()
  71. self.colorDialog = ColorDialog(parent=self)
  72. self.labelList.setItemDelegate(LabelDelegate())
  73. self.labelList.itemActivated.connect(self.highlightLabel)
  74. # Connect to itemChanged to detect checkbox changes.
  75. self.labelList.itemChanged.connect(self.labelItemChanged)
  76. self.canvas = Canvas()
  77. self.canvas.zoomRequest.connect(self.zoomRequest)
  78. scroll = QScrollArea()
  79. scroll.setWidget(self.canvas)
  80. scroll.setWidgetResizable(True)
  81. self.scrollBars = {
  82. Qt.Vertical: scroll.verticalScrollBar(),
  83. Qt.Horizontal: scroll.horizontalScrollBar()
  84. }
  85. self.canvas.scrollRequest.connect(self.scrollRequest)
  86. self.canvas.newShape.connect(self.newShape)
  87. self.canvas.shapeMoved.connect(self.setDirty)
  88. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  89. self.setCentralWidget(scroll)
  90. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  91. # Actions
  92. action = partial(newAction, self)
  93. quit = action('&Quit', self.close,
  94. 'Ctrl+Q', 'quit', u'Exit application')
  95. open = action('&Open', self.openFile,
  96. 'Ctrl+O', 'open', u'Open file')
  97. save = action('&Save', self.saveFile,
  98. 'Ctrl+S', 'save', u'Save file')
  99. color1 = action('&Line Color', self.chooseColor1,
  100. 'Ctrl+C', 'color', u'Choose line color')
  101. color2 = action('&Fill Color', self.chooseColor2,
  102. 'Ctrl+Shift+C', 'color', u'Choose fill color')
  103. label = action('&New Item', self.newLabel,
  104. 'Ctrl+N', 'new', u'Add new label', enabled=False)
  105. copy = action('&Copy', self.copySelectedShape,
  106. 'Ctrl+C', 'copy', u'Copy', enabled=False)
  107. delete = action('&Delete', self.deleteSelectedShape,
  108. ['Ctrl+D', 'Delete'], 'delete', u'Delete', enabled=False)
  109. hide = action('&Hide labels', self.hideLabelsToggle,
  110. 'Ctrl+H', 'hide', u'Hide background labels when drawing',
  111. checkable=True)
  112. zoom = QWidgetAction(self)
  113. zoom.setDefaultWidget(self.zoomWidget)
  114. zoomIn = action('Zoom &In', partial(self.addZoom, 10),
  115. 'Ctrl++', 'zoom-in', u'Increase zoom level')
  116. zoomOut = action('&Zoom Out', partial(self.addZoom, -10),
  117. 'Ctrl+-', 'zoom-out', u'Decrease zoom level')
  118. zoomOrg = action('&Original size', partial(self.setZoom, 100),
  119. 'Ctrl+=', 'zoom', u'Zoom to original size')
  120. fitWindow = action('&Fit Window', self.setFitWindow,
  121. 'Ctrl+F', 'fit-window', u'Zoom follows window size',
  122. checkable=True)
  123. fitWidth = action('Fit &Width', self.setFitWidth,
  124. 'Ctrl+W', 'fit-width', u'Zoom follows window width',
  125. checkable=True)
  126. self.zoomMode = self.MANUAL_ZOOM
  127. self.scalers = {
  128. self.FIT_WINDOW: self.scaleFitWindow,
  129. self.FIT_WIDTH: self.scaleFitWidth,
  130. }
  131. # Custom context menu for the canvas widget:
  132. addActions(self.canvas.menus[0], (label, copy, delete))
  133. addActions(self.canvas.menus[1], (
  134. action('&Copy here', self.copyShape),
  135. action('&Move here', self.moveShape)))
  136. labels = self.dock.toggleViewAction()
  137. labels.setShortcut('Ctrl+L')
  138. # Store actions for further handling.
  139. self.actions = struct(save=save, open=open,
  140. lineColor=color1, fillColor=color2,
  141. label=label, delete=delete, zoom=zoom, copy=copy,
  142. zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
  143. fitWindow=fitWindow, fitWidth=fitWidth)
  144. save.setEnabled(False)
  145. self.menus = struct(
  146. file=self.menu('&File'),
  147. edit=self.menu('&Image'),
  148. view=self.menu('&View'))
  149. addActions(self.menus.file, (open, save, quit))
  150. addActions(self.menus.edit, (label, color1, color2))
  151. addActions(self.menus.view, (
  152. labels, None,
  153. zoomIn, zoomOut, zoomOrg, None,
  154. fitWindow, fitWidth))
  155. self.tools = self.toolbar('Tools')
  156. addActions(self.tools, (
  157. open, save, None,
  158. label, delete, hide, None,
  159. zoomIn, zoom, zoomOut, fitWindow, fitWidth))
  160. self.statusBar().showMessage('%s started.' % __appname__)
  161. self.statusBar().show()
  162. # Application state.
  163. self.image = QImage()
  164. self.filename = filename
  165. self.recent_files = []
  166. self.lineColor = None
  167. self.fillColor = None
  168. self.zoom_level = 100
  169. self.fit_window = False
  170. # XXX: Could be completely declarative.
  171. # Restore application settings.
  172. types = {
  173. 'filename': QString,
  174. 'recent-files': QStringList,
  175. 'window/size': QSize,
  176. 'window/position': QPoint,
  177. 'window/geometry': QByteArray,
  178. # Docks and toolbars:
  179. 'window/state': QByteArray,
  180. }
  181. self.settings = settings = Settings(types)
  182. self.recent_files = settings['recent-files']
  183. size = settings.get('window/size', QSize(600, 500))
  184. position = settings.get('window/position', QPoint(0, 0))
  185. self.resize(size)
  186. self.move(position)
  187. # or simply:
  188. #self.restoreGeometry(settings['window/geometry']
  189. self.restoreState(settings['window/state'])
  190. self.lineColor = QColor(settings.get('line/color', Shape.line_color))
  191. self.fillColor = QColor(settings.get('fill/color', Shape.fill_color))
  192. Shape.line_color = self.lineColor
  193. Shape.fill_color = self.fillColor
  194. # The file menu has default dynamically generated entries.
  195. self.updateFileMenu()
  196. # Since loading the file may take some time, make sure it runs in the background.
  197. self.queueEvent(partial(self.loadFile, self.filename))
  198. # Callbacks:
  199. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  200. ## Support Functions ##
  201. def setDirty(self):
  202. self.dirty = True
  203. self.actions.save.setEnabled(True)
  204. def setClean(self):
  205. self.dirty = False
  206. self.actions.save.setEnabled(False)
  207. self.actions.label.setEnabled(True)
  208. def queueEvent(self, function):
  209. QTimer.singleShot(0, function)
  210. def status(self, message, delay=5000):
  211. self.statusBar().showMessage(message, delay)
  212. ## Callbacks ##
  213. # React to canvas signals.
  214. def shapeSelectionChanged(self, selected=False):
  215. self.actions.delete.setEnabled(selected)
  216. self.actions.copy.setEnabled(selected)
  217. def addLabel(self, shape):
  218. item = QListWidgetItem(shape.label)
  219. item.setFlags(item.flags() | Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
  220. item.setCheckState(Qt.Checked)
  221. self.labels[item] = shape
  222. self.items[shape] = item
  223. self.labelList.addItem(item)
  224. def remLabel(self, shape):
  225. item = self.items.get(shape, None)
  226. self.labelList.takeItem(self.labelList.row(item))
  227. def loadLabels(self, shapes):
  228. s = []
  229. for label, points in shapes:
  230. shape = Shape(label=label)
  231. shape.fill = True
  232. for x, y in points:
  233. shape.addPoint(QPointF(x, y))
  234. s.append(shape)
  235. self.addLabel(shape)
  236. self.canvas.loadShapes(s)
  237. def saveLabels(self, filename):
  238. lf = LabelFile()
  239. shapes = [(unicode(shape.label), [(p.x(), p.y()) for p in shape.points])\
  240. for shape in self.canvas.shapes]
  241. try:
  242. lf.save(filename, shapes, unicode(self.filename), self.imageData)
  243. return True
  244. except LabelFileError, e:
  245. self.errorMessage(u'Error saving label data',
  246. u'<b>%s</b>' % e)
  247. return False
  248. def copySelectedShape(self):
  249. self.addLabel(self.canvas.copySelectedShape())
  250. #fix copy and delete
  251. self.shapeSelectionChanged(True)
  252. def highlightLabel(self, item):
  253. if self.highlighted:
  254. self.highlighted.fill_color = Shape.fill_color
  255. shape = self.labels[item]
  256. shape.fill_color = inverted(Shape.fill_color)
  257. self.highlighted = shape
  258. self.canvas.repaint()
  259. def labelItemChanged(self, item):
  260. shape = self.labels[item]
  261. label = unicode(item.text())
  262. if label != shape.label:
  263. shape.label = unicode(item.text())
  264. self.setDirty()
  265. else: # User probably changed item visibility
  266. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  267. ## Callback functions:
  268. def newShape(self, position):
  269. """Pop-up and give focus to the label editor.
  270. position MUST be in global coordinates.
  271. """
  272. action = self.label.popUp(position)
  273. if action == self.label.OK:
  274. self.addLabel(self.canvas.setLastLabel(self.label.text()))
  275. self.setDirty()
  276. # Enable appropriate actions.
  277. self.actions.label.setEnabled(True)
  278. elif action == self.label.UNDO:
  279. self.canvas.undoLastLine()
  280. elif action == self.label.DELETE:
  281. self.canvas.deleteLastShape()
  282. else:
  283. assert False, "unknown label action"
  284. def scrollRequest(self, delta, orientation):
  285. units = - delta / (8 * 15)
  286. bar = self.scrollBars[orientation]
  287. bar.setValue(bar.value() + bar.singleStep() * units)
  288. def setZoom(self, value):
  289. self.actions.fitWidth.setChecked(False)
  290. self.actions.fitWindow.setChecked(False)
  291. self.zoomMode = self.MANUAL_ZOOM
  292. self.zoomWidget.setValue(value)
  293. def addZoom(self, increment=10):
  294. self.setZoom(self.zoomWidget.value() + increment)
  295. def zoomRequest(self, delta):
  296. units = delta / (8 * 15)
  297. scale = 10
  298. self.addZoom(scale * units)
  299. def setFitWindow(self, value=True):
  300. if value:
  301. self.actions.fitWidth.setChecked(False)
  302. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  303. self.adjustScale()
  304. def setFitWidth(self, value=True):
  305. if value:
  306. self.actions.fitWindow.setChecked(False)
  307. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  308. self.adjustScale()
  309. def hideLabelsToggle(self, value):
  310. self.canvas.hideBackroundShapes(value)
  311. def loadFile(self, filename=None):
  312. """Load the specified file, or the last opened file if None."""
  313. if filename is None:
  314. filename = self.settings['filename']
  315. filename = unicode(filename)
  316. if QFile.exists(filename):
  317. if LabelFile.isLabelFile(filename):
  318. try:
  319. self.labelFile = LabelFile(filename)
  320. except LabelFileError, e:
  321. self.errorMessage(u'Error opening file',
  322. (u"<p><b>%s</b></p>"
  323. u"<p>Make sure <i>%s</i> is a valid label file.")\
  324. % (e, filename))
  325. self.status("Error reading %s" % filename)
  326. return False
  327. self.imageData = self.labelFile.imageData
  328. else:
  329. # Load image:
  330. # read data first and store for saving into label file.
  331. self.imageData = read(filename, None)
  332. self.labelFile = None
  333. image = QImage.fromData(self.imageData)
  334. if image.isNull():
  335. self.errorMessage(u'Error opening file',
  336. u"<p>Make sure <i>%s</i> is a valid image file." % filename)
  337. self.status("Error reading %s" % filename)
  338. return False
  339. self.status("Loaded %s" % os.path.basename(unicode(filename)))
  340. self.image = image
  341. self.filename = filename
  342. self.labels = {}
  343. self.labelList.clear()
  344. self.canvas.loadPixmap(QPixmap.fromImage(image))
  345. if self.labelFile:
  346. self.loadLabels(self.labelFile.shapes)
  347. self.setClean()
  348. return True
  349. return False
  350. def resizeEvent(self, event):
  351. if self.canvas and not self.image.isNull()\
  352. and self.zoomMode != self.MANUAL_ZOOM:
  353. self.adjustScale()
  354. super(MainWindow, self).resizeEvent(event)
  355. def paintCanvas(self):
  356. assert not self.image.isNull(), "cannot paint null image"
  357. self.canvas.scale = 0.01 * self.zoomWidget.value()
  358. self.canvas.adjustSize()
  359. self.canvas.repaint()
  360. def adjustScale(self):
  361. self.zoomWidget.setValue(int(100 * self.scalers[self.zoomMode]()))
  362. def scaleFitWindow(self):
  363. """Figure out the size of the pixmap in order to fit the main widget."""
  364. e = 2.0 # So that no scrollbars are generated.
  365. w1 = self.centralWidget().width() - e
  366. h1 = self.centralWidget().height() - e
  367. a1 = w1/ h1
  368. # Calculate a new scale value based on the pixmap's aspect ratio.
  369. w2 = self.canvas.pixmap.width() - 0.0
  370. h2 = self.canvas.pixmap.height() - 0.0
  371. a2 = w2 / h2
  372. return w1 / w2 if a2 >= a1 else h1 / h2
  373. def scaleFitWidth(self):
  374. # The epsilon does not seem to work too well here.
  375. w = self.centralWidget().width() - 2.0
  376. return w / self.canvas.pixmap.width()
  377. def closeEvent(self, event):
  378. if not self.mayContinue():
  379. event.ignore()
  380. s = self.settings
  381. s['filename'] = self.filename if self.filename else QString()
  382. s['window/size'] = self.size()
  383. s['window/position'] = self.pos()
  384. s['window/state'] = self.saveState()
  385. s['line/color'] = self.lineColor
  386. s['fill/color'] = self.fillColor
  387. # ask the use for where to save the labels
  388. #s['window/geometry'] = self.saveGeometry()
  389. def updateFileMenu(self):
  390. """Populate menu with recent files."""
  391. ## User Dialogs ##
  392. def openFile(self, _value=False):
  393. if not self.mayContinue():
  394. return
  395. path = os.path.dirname(unicode(self.filename))\
  396. if self.filename else '.'
  397. formats = ['*.%s' % unicode(fmt).lower()\
  398. for fmt in QImageReader.supportedImageFormats()]
  399. filters = 'Image files (%s)\nLabel files (*%s)'\
  400. % (' '.join(formats), LabelFile.suffix)
  401. filename = unicode(QFileDialog.getOpenFileName(self,
  402. '%s - Choose Image', path, filters))
  403. if filename:
  404. self.loadFile(filename)
  405. def saveFile(self, _value=False):
  406. assert not self.image.isNull(), "cannot save empty image"
  407. assert self.labels, "cannot save empty labels"
  408. formats = ['*%s' % LabelFile.suffix]
  409. filename = unicode(QFileDialog.getSaveFileName(self,
  410. '%s - Choose File', self.currentPath(),
  411. 'Label files (%s)' % ''.join(formats)))
  412. if filename:
  413. if self.saveLabels(filename):
  414. self.setClean()
  415. # Message Dialogs. #
  416. def mayContinue(self):
  417. return not (self.dirty and not self.discardChangesDialog())
  418. def discardChangesDialog(self):
  419. yes, no = QMessageBox.Yes, QMessageBox.No
  420. msg = u'You have unsaved changes, proceed anyway?'
  421. return yes == QMessageBox.warning(self, u'Attention', msg, yes|no)
  422. def errorMessage(self, title, message):
  423. return QMessageBox.critical(self, title,
  424. '<p><b>%s</b></p>%s' % (title, message))
  425. def currentPath(self):
  426. return os.path.dirname(unicode(self.filename)) if self.filename else '.'
  427. def chooseColor1(self):
  428. color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
  429. default=DEFAULT_LINE_COLOR)
  430. if color:
  431. self.lineColor = color
  432. # Change the color for all shape lines:
  433. Shape.line_color = self.lineColor
  434. self.canvas.repaint()
  435. def chooseColor2(self):
  436. color = self.colorDialog.getColor(self.fillColor, u'Choose fill color',
  437. default=DEFAULT_FILL_COLOR)
  438. if color:
  439. self.fillColor = color
  440. Shape.fill_color = self.fillColor
  441. self.canvas.repaint()
  442. def newLabel(self):
  443. self.canvas.deSelectShape()
  444. self.canvas.setEditing()
  445. self.actions.label.setEnabled(False)
  446. def deleteSelectedShape(self):
  447. self.remLabel(self.canvas.deleteSelected())
  448. self.setDirty()
  449. def copyShape(self):
  450. self.canvas.endMove(copy=True)
  451. self.addLabel(self.canvas.selectedShape)
  452. self.setDirty()
  453. def moveShape(self):
  454. self.canvas.endMove(copy=False)
  455. self.setDirty()
  456. class LabelDelegate(QItemDelegate):
  457. def __init__(self, parent=None):
  458. super(LabelDelegate, self).__init__(parent)
  459. self.validator = labelValidator()
  460. # FIXME: Validation and trimming are completely broken if the
  461. # user navigates away from the editor with something like TAB.
  462. def createEditor(self, parent, option, index):
  463. """Make sure the user cannot enter empty labels.
  464. Also remove trailing whitespace."""
  465. edit = super(LabelDelegate, self).createEditor(parent, option, index)
  466. if isinstance(edit, QLineEdit):
  467. edit.setValidator(self.validator)
  468. def strip():
  469. edit.setText(edit.text().trimmed())
  470. edit.editingFinished.connect(strip)
  471. return edit
  472. class Settings(object):
  473. """Convenience dict-like wrapper around QSettings."""
  474. def __init__(self, types=None):
  475. self.data = QSettings()
  476. self.types = defaultdict(lambda: QVariant, types if types else {})
  477. def __setitem__(self, key, value):
  478. t = self.types[key]
  479. self.data.setValue(key,
  480. t(value) if not isinstance(value, t) else value)
  481. def __getitem__(self, key):
  482. return self._cast(key, self.data.value(key))
  483. def get(self, key, default=None):
  484. return self._cast(key, self.data.value(key, default))
  485. def _cast(self, key, value):
  486. # XXX: Very nasty way of converting types to QVariant methods :P
  487. t = self.types[key]
  488. if t != QVariant:
  489. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  490. return method(value)
  491. return value
  492. def inverted(color):
  493. return QColor(*[255 - v for v in color.getRgb()])
  494. def read(filename, default=None):
  495. try:
  496. with open(filename, 'rb') as f:
  497. return f.read()
  498. except:
  499. return default
  500. def main(argv):
  501. """Standard boilerplate Qt application code."""
  502. app = QApplication(argv)
  503. app.setApplicationName(__appname__)
  504. win = MainWindow(argv[1] if len(argv) == 2 else None)
  505. win.show()
  506. return app.exec_()
  507. if __name__ == '__main__':
  508. sys.exit(main(sys.argv))