labelme.py 18 KB

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