labelme.py 15 KB

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