labelme.py 13 KB

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