app.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. #!/usr/bin/env python
  2. # -*- coding: utf8 -*-
  3. #
  4. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  5. #
  6. # This file is part of Labelme.
  7. #
  8. # Labelme is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # Labelme is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. import argparse
  22. import os.path
  23. import re
  24. import sys
  25. import subprocess
  26. from functools import partial
  27. from collections import defaultdict
  28. try:
  29. from PyQt5.QtGui import *
  30. from PyQt5.QtCore import *
  31. from PyQt5.QtWidgets import *
  32. PYQT5 = True
  33. except ImportError:
  34. from PyQt4.QtGui import *
  35. from PyQt4.QtCore import *
  36. PYQT5 = False
  37. from labelme import resources
  38. from labelme.lib import struct, newAction, newIcon, addActions, fmtShortcut
  39. from labelme.shape import Shape, DEFAULT_LINE_COLOR, DEFAULT_FILL_COLOR
  40. from labelme.canvas import Canvas
  41. from labelme.zoomWidget import ZoomWidget
  42. from labelme.labelDialog import LabelDialog
  43. from labelme.colorDialog import ColorDialog
  44. from labelme.labelFile import LabelFile, LabelFileError
  45. from labelme.toolBar import ToolBar
  46. __appname__ = 'labelme'
  47. # FIXME
  48. # - [medium] Set max zoom value to something big enough for FitWidth/Window
  49. # TODO:
  50. # - [high] Automatically add file suffix when saving.
  51. # - [high] Add polygon movement with arrow keys
  52. # - [high] Deselect shape when clicking and already selected(?)
  53. # - [high] Sanitize shortcuts between beginner/advanced mode.
  54. # - [medium] Zoom should keep the image centered.
  55. # - [medium] Add undo button for vertex addition.
  56. # - [low,maybe] Open images with drag & drop.
  57. # - [low,maybe] Preview images on file dialogs.
  58. # - [low,maybe] Sortable label list.
  59. # - Zoom is too "steppy".
  60. ### Utility functions and classes.
  61. class WindowMixin(object):
  62. def menu(self, title, actions=None):
  63. menu = self.menuBar().addMenu(title)
  64. if actions:
  65. addActions(menu, actions)
  66. return menu
  67. def toolbar(self, title, actions=None):
  68. toolbar = ToolBar(title)
  69. toolbar.setObjectName('%sToolBar' % title)
  70. #toolbar.setOrientation(Qt.Vertical)
  71. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  72. if actions:
  73. addActions(toolbar, actions)
  74. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  75. return toolbar
  76. class MainWindow(QMainWindow, WindowMixin):
  77. FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = 0, 1, 2
  78. def __init__(self, filename=None, output=None, store_data=True):
  79. super(MainWindow, self).__init__()
  80. self.setWindowTitle(__appname__)
  81. # Whether we need to save or not.
  82. self.dirty = False
  83. self._noSelectionSlot = False
  84. self._beginner = True
  85. self.screencastViewer = "firefox"
  86. self.screencast = "screencast.ogv"
  87. # Main widgets and related state.
  88. self.labelDialog = LabelDialog(parent=self)
  89. self.labelList = QListWidget()
  90. self.itemsToShapes = []
  91. self.labelList.itemActivated.connect(self.labelSelectionChanged)
  92. self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
  93. self.labelList.itemDoubleClicked.connect(self.editLabel)
  94. # Connect to itemChanged to detect checkbox changes.
  95. self.labelList.itemChanged.connect(self.labelItemChanged)
  96. listLayout = QVBoxLayout()
  97. listLayout.setContentsMargins(0, 0, 0, 0)
  98. listLayout.addWidget(self.labelList)
  99. self.editButton = QToolButton()
  100. self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
  101. self.labelListContainer = QWidget()
  102. self.labelListContainer.setLayout(listLayout)
  103. listLayout.addWidget(self.editButton)#, 0, Qt.AlignCenter)
  104. listLayout.addWidget(self.labelList)
  105. self.dock = QDockWidget('Polygon Labels', self)
  106. self.dock.setObjectName('Labels')
  107. self.dock.setWidget(self.labelListContainer)
  108. self.zoomWidget = ZoomWidget()
  109. self.colorDialog = ColorDialog(parent=self)
  110. self.canvas = Canvas()
  111. self.canvas.zoomRequest.connect(self.zoomRequest)
  112. scroll = QScrollArea()
  113. scroll.setWidget(self.canvas)
  114. scroll.setWidgetResizable(True)
  115. self.scrollBars = {
  116. Qt.Vertical: scroll.verticalScrollBar(),
  117. Qt.Horizontal: scroll.horizontalScrollBar()
  118. }
  119. self.canvas.scrollRequest.connect(self.scrollRequest)
  120. self.canvas.newShape.connect(self.newShape)
  121. self.canvas.shapeMoved.connect(self.setDirty)
  122. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  123. self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)
  124. self.setCentralWidget(scroll)
  125. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  126. self.dockFeatures = QDockWidget.DockWidgetClosable\
  127. | QDockWidget.DockWidgetFloatable
  128. self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)
  129. # Actions
  130. action = partial(newAction, self)
  131. quit = action('&Quit', self.close,
  132. 'Ctrl+Q', 'quit', 'Quit application')
  133. open = action('&Open', self.openFile,
  134. 'Ctrl+O', 'open', 'Open image or label file')
  135. save = action('&Save', self.saveFile,
  136. 'Ctrl+S', 'save', 'Save labels to file', enabled=False)
  137. saveAs = action('&Save As', self.saveFileAs,
  138. 'Ctrl+Shift+S', 'save-as', 'Save labels to a different file',
  139. enabled=False)
  140. close = action('&Close', self.closeFile,
  141. 'Ctrl+W', 'close', 'Close current file')
  142. color1 = action('Polygon &Line Color', self.chooseColor1,
  143. 'Ctrl+L', 'color_line', 'Choose polygon line color')
  144. color2 = action('Polygon &Fill Color', self.chooseColor2,
  145. 'Ctrl+Shift+L', 'color', 'Choose polygon fill color')
  146. createMode = action('Create\nPolygo&ns', self.setCreateMode,
  147. 'Ctrl+N', 'new', 'Start drawing polygons', enabled=False)
  148. editMode = action('&Edit\nPolygons', self.setEditMode,
  149. 'Ctrl+J', 'edit', 'Move and edit polygons', enabled=False)
  150. create = action('Create\nPolygo&n', self.createShape,
  151. 'Ctrl+N', 'new', 'Draw a new polygon', enabled=False)
  152. delete = action('Delete\nPolygon', self.deleteSelectedShape,
  153. 'Delete', 'delete', 'Delete', enabled=False)
  154. copy = action('&Duplicate\nPolygon', self.copySelectedShape,
  155. 'Ctrl+D', 'copy', 'Create a duplicate of the selected polygon',
  156. enabled=False)
  157. advancedMode = action('&Advanced Mode', self.toggleAdvancedMode,
  158. 'Ctrl+Shift+A', 'expert', 'Switch to advanced mode',
  159. checkable=True)
  160. hideAll = action('&Hide\nPolygons', partial(self.togglePolygons, False),
  161. 'Ctrl+H', 'hide', 'Hide all polygons',
  162. enabled=False)
  163. showAll = action('&Show\nPolygons', partial(self.togglePolygons, True),
  164. 'Ctrl+A', 'hide', 'Show all polygons',
  165. enabled=False)
  166. help = action('&Tutorial', self.tutorial, 'Ctrl+T', 'help',
  167. 'Show screencast of introductory tutorial')
  168. zoom = QWidgetAction(self)
  169. zoom.setDefaultWidget(self.zoomWidget)
  170. self.zoomWidget.setWhatsThis(
  171. "Zoom in or out of the image. Also accessible with"\
  172. " %s and %s from the canvas." % (fmtShortcut("Ctrl+[-+]"),
  173. fmtShortcut("Ctrl+Wheel")))
  174. self.zoomWidget.setEnabled(False)
  175. zoomIn = action('Zoom &In', partial(self.addZoom, 10),
  176. 'Ctrl++', 'zoom-in', 'Increase zoom level', enabled=False)
  177. zoomOut = action('&Zoom Out', partial(self.addZoom, -10),
  178. 'Ctrl+-', 'zoom-out', 'Decrease zoom level', enabled=False)
  179. zoomOrg = action('&Original size', partial(self.setZoom, 100),
  180. 'Ctrl+=', 'zoom', 'Zoom to original size', enabled=False)
  181. fitWindow = action('&Fit Window', self.setFitWindow,
  182. 'Ctrl+F', 'fit-window', 'Zoom follows window size',
  183. checkable=True, enabled=False)
  184. fitWidth = action('Fit &Width', self.setFitWidth,
  185. 'Ctrl+Shift+F', 'fit-width', 'Zoom follows window width',
  186. checkable=True, enabled=False)
  187. # Group zoom controls into a list for easier toggling.
  188. zoomActions = (self.zoomWidget, zoomIn, zoomOut, zoomOrg, fitWindow, fitWidth)
  189. self.zoomMode = self.MANUAL_ZOOM
  190. self.scalers = {
  191. self.FIT_WINDOW: self.scaleFitWindow,
  192. self.FIT_WIDTH: self.scaleFitWidth,
  193. # Set to one to scale to 100% when loading files.
  194. self.MANUAL_ZOOM: lambda: 1,
  195. }
  196. edit = action('&Edit Label', self.editLabel,
  197. 'Ctrl+E', 'edit', 'Modify the label of the selected polygon',
  198. enabled=False)
  199. self.editButton.setDefaultAction(edit)
  200. shapeLineColor = action('Shape &Line Color', self.chshapeLineColor,
  201. icon='color_line', tip='Change the line color for this specific shape',
  202. enabled=False)
  203. shapeFillColor = action('Shape &Fill Color', self.chshapeFillColor,
  204. icon='color', tip='Change the fill color for this specific shape',
  205. enabled=False)
  206. labels = self.dock.toggleViewAction()
  207. labels.setText('Show/Hide Label Panel')
  208. labels.setShortcut('Ctrl+Shift+L')
  209. # Lavel list context menu.
  210. labelMenu = QMenu()
  211. addActions(labelMenu, (edit, delete))
  212. self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
  213. self.labelList.customContextMenuRequested.connect(self.popLabelListMenu)
  214. # Store actions for further handling.
  215. self.actions = struct(save=save, saveAs=saveAs, open=open, close=close,
  216. lineColor=color1, fillColor=color2,
  217. create=create, delete=delete, edit=edit, copy=copy,
  218. createMode=createMode, editMode=editMode, advancedMode=advancedMode,
  219. shapeLineColor=shapeLineColor, shapeFillColor=shapeFillColor,
  220. zoom=zoom, zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
  221. fitWindow=fitWindow, fitWidth=fitWidth,
  222. zoomActions=zoomActions,
  223. fileMenuActions=(open,save,saveAs,close,quit),
  224. beginner=(), advanced=(),
  225. editMenu=(edit, copy, delete, None, color1, color2),
  226. beginnerContext=(create, edit, copy, delete),
  227. advancedContext=(createMode, editMode, edit, copy,
  228. delete, shapeLineColor, shapeFillColor),
  229. onLoadActive=(close, create, createMode, editMode),
  230. onShapesPresent=(saveAs, hideAll, showAll))
  231. self.menus = struct(
  232. file=self.menu('&File'),
  233. edit=self.menu('&Edit'),
  234. view=self.menu('&View'),
  235. help=self.menu('&Help'),
  236. recentFiles=QMenu('Open &Recent'),
  237. labelList=labelMenu)
  238. addActions(self.menus.file,
  239. (open, self.menus.recentFiles, save, saveAs, close, None, quit))
  240. addActions(self.menus.help, (help,))
  241. addActions(self.menus.view, (
  242. labels, advancedMode, None,
  243. hideAll, showAll, None,
  244. zoomIn, zoomOut, zoomOrg, None,
  245. fitWindow, fitWidth))
  246. self.menus.file.aboutToShow.connect(self.updateFileMenu)
  247. # Custom context menu for the canvas widget:
  248. addActions(self.canvas.menus[0], self.actions.beginnerContext)
  249. addActions(self.canvas.menus[1], (
  250. action('&Copy here', self.copyShape),
  251. action('&Move here', self.moveShape)))
  252. self.tools = self.toolbar('Tools')
  253. self.actions.beginner = (
  254. open, save, None, create, copy, delete, None,
  255. zoomIn, zoom, zoomOut, fitWindow, fitWidth)
  256. self.actions.advanced = (
  257. open, save, None,
  258. createMode, editMode, None,
  259. hideAll, showAll)
  260. self.statusBar().showMessage('%s started.' % __appname__)
  261. self.statusBar().show()
  262. # Application state.
  263. self.image = QImage()
  264. self.imagePath = None
  265. self.filename = filename
  266. self.labeling_once = output is not None
  267. self.output = output
  268. self._store_data = store_data
  269. self.recentFiles = []
  270. self.maxRecent = 7
  271. self.lineColor = None
  272. self.fillColor = None
  273. self.zoom_level = 100
  274. self.fit_window = False
  275. # XXX: Could be completely declarative.
  276. # Restore application settings.
  277. self.settings = {}
  278. self.recentFiles = self.settings.get('recentFiles', [])
  279. size = self.settings.get('window/size', QSize(600, 500))
  280. position = self.settings.get('window/position', QPoint(0, 0))
  281. self.resize(size)
  282. self.move(position)
  283. # or simply:
  284. #self.restoreGeometry(settings['window/geometry']
  285. self.restoreState(self.settings.get('window/state', QByteArray()))
  286. self.lineColor = QColor(self.settings.get('line/color', Shape.line_color))
  287. self.fillColor = QColor(self.settings.get('fill/color', Shape.fill_color))
  288. Shape.line_color = self.lineColor
  289. Shape.fill_color = self.fillColor
  290. if self.settings.get('advanced', QVariant()):
  291. self.actions.advancedMode.setChecked(True)
  292. self.toggleAdvancedMode()
  293. # Populate the File menu dynamically.
  294. self.updateFileMenu()
  295. # Since loading the file may take some time, make sure it runs in the background.
  296. self.queueEvent(partial(self.loadFile, self.filename))
  297. # Callbacks:
  298. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  299. self.populateModeActions()
  300. #self.firstStart = True
  301. #if self.firstStart:
  302. # QWhatsThis.enterWhatsThisMode()
  303. ## Support Functions ##
  304. def noShapes(self):
  305. return not self.itemsToShapes
  306. def toggleAdvancedMode(self, value=True):
  307. self._beginner = not value
  308. self.canvas.setEditing(True)
  309. self.populateModeActions()
  310. self.editButton.setVisible(not value)
  311. if value:
  312. self.actions.createMode.setEnabled(True)
  313. self.actions.editMode.setEnabled(False)
  314. self.dock.setFeatures(self.dock.features() | self.dockFeatures)
  315. else:
  316. self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)
  317. def populateModeActions(self):
  318. if self.beginner():
  319. tool, menu = self.actions.beginner, self.actions.beginnerContext
  320. else:
  321. tool, menu = self.actions.advanced, self.actions.advancedContext
  322. self.tools.clear()
  323. addActions(self.tools, tool)
  324. self.canvas.menus[0].clear()
  325. addActions(self.canvas.menus[0], menu)
  326. self.menus.edit.clear()
  327. actions = (self.actions.create,) if self.beginner()\
  328. else (self.actions.createMode, self.actions.editMode)
  329. addActions(self.menus.edit, actions + self.actions.editMenu)
  330. def setBeginner(self):
  331. self.tools.clear()
  332. addActions(self.tools, self.actions.beginner)
  333. def setAdvanced(self):
  334. self.tools.clear()
  335. addActions(self.tools, self.actions.advanced)
  336. def setDirty(self):
  337. self.dirty = True
  338. self.actions.save.setEnabled(True)
  339. def setClean(self):
  340. self.dirty = False
  341. self.actions.save.setEnabled(False)
  342. self.actions.create.setEnabled(True)
  343. def toggleActions(self, value=True):
  344. """Enable/Disable widgets which depend on an opened image."""
  345. for z in self.actions.zoomActions:
  346. z.setEnabled(value)
  347. for action in self.actions.onLoadActive:
  348. action.setEnabled(value)
  349. def queueEvent(self, function):
  350. QTimer.singleShot(0, function)
  351. def status(self, message, delay=5000):
  352. self.statusBar().showMessage(message, delay)
  353. def resetState(self):
  354. self.itemsToShapes = []
  355. self.labelList.clear()
  356. self.filename = None
  357. self.imageData = None
  358. self.labelFile = None
  359. self.canvas.resetState()
  360. def currentItem(self):
  361. items = self.labelList.selectedItems()
  362. if items:
  363. return items[0]
  364. return None
  365. def addRecentFile(self, filename):
  366. if filename in self.recentFiles:
  367. self.recentFiles.remove(filename)
  368. elif len(self.recentFiles) >= self.maxRecent:
  369. self.recentFiles.pop()
  370. self.recentFiles.insert(0, filename)
  371. def beginner(self):
  372. return self._beginner
  373. def advanced(self):
  374. return not self.beginner()
  375. ## Callbacks ##
  376. def tutorial(self):
  377. subprocess.Popen([self.screencastViewer, self.screencast])
  378. def createShape(self):
  379. assert self.beginner()
  380. self.canvas.setEditing(False)
  381. self.actions.create.setEnabled(False)
  382. def toggleDrawingSensitive(self, drawing=True):
  383. """In the middle of drawing, toggling between modes should be disabled."""
  384. self.actions.editMode.setEnabled(not drawing)
  385. if not drawing and self.beginner():
  386. # Cancel creation.
  387. self.canvas.setEditing(True)
  388. self.canvas.restoreCursor()
  389. self.actions.create.setEnabled(True)
  390. def toggleDrawMode(self, edit=True):
  391. self.canvas.setEditing(edit)
  392. self.actions.createMode.setEnabled(edit)
  393. self.actions.editMode.setEnabled(not edit)
  394. def setCreateMode(self):
  395. assert self.advanced()
  396. self.toggleDrawMode(False)
  397. def setEditMode(self):
  398. assert self.advanced()
  399. self.toggleDrawMode(True)
  400. def updateFileMenu(self):
  401. current = self.filename
  402. def exists(filename):
  403. return os.path.exists(str(filename))
  404. menu = self.menus.recentFiles
  405. menu.clear()
  406. files = [f for f in self.recentFiles if f != current and exists(f)]
  407. for i, f in enumerate(files):
  408. icon = newIcon('labels')
  409. action = QAction(
  410. icon, '&%d %s' % (i+1, QFileInfo(f).fileName()), self)
  411. action.triggered.connect(partial(self.loadRecent, f))
  412. menu.addAction(action)
  413. def popLabelListMenu(self, point):
  414. self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
  415. def editLabel(self, item=None):
  416. if not self.canvas.editing():
  417. return
  418. item = item if item else self.currentItem()
  419. text = self.labelDialog.popUp(item.text())
  420. if text is not None:
  421. item.setText(text)
  422. self.setDirty()
  423. # React to canvas signals.
  424. def shapeSelectionChanged(self, selected=False):
  425. if self._noSelectionSlot:
  426. self._noSelectionSlot = False
  427. else:
  428. shape = self.canvas.selectedShape
  429. if shape:
  430. for item, shape_ in self.itemsToShapes:
  431. if shape_ == shape:
  432. break
  433. item.setSelected(True)
  434. else:
  435. self.labelList.clearSelection()
  436. self.actions.delete.setEnabled(selected)
  437. self.actions.copy.setEnabled(selected)
  438. self.actions.edit.setEnabled(selected)
  439. self.actions.shapeLineColor.setEnabled(selected)
  440. self.actions.shapeFillColor.setEnabled(selected)
  441. def addLabel(self, shape):
  442. item = QListWidgetItem(shape.label)
  443. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  444. item.setCheckState(Qt.Checked)
  445. self.itemsToShapes.append((item, shape))
  446. self.labelList.addItem(item)
  447. for action in self.actions.onShapesPresent:
  448. action.setEnabled(True)
  449. def remLabel(self, shape):
  450. for index, (item, shape_) in enumerate(self.itemsToShapes):
  451. if shape_ == shape:
  452. break
  453. self.itemsToShapes.pop(index)
  454. self.labelList.takeItem(self.labelList.row(item))
  455. def loadLabels(self, shapes):
  456. s = []
  457. for label, points, line_color, fill_color in shapes:
  458. shape = Shape(label=label)
  459. for x, y in points:
  460. shape.addPoint(QPointF(x, y))
  461. shape.close()
  462. s.append(shape)
  463. self.addLabel(shape)
  464. if line_color:
  465. shape.line_color = QColor(*line_color)
  466. if fill_color:
  467. shape.fill_color = QColor(*fill_color)
  468. self.canvas.loadShapes(s)
  469. def saveLabels(self, filename):
  470. lf = LabelFile()
  471. def format_shape(s):
  472. return dict(label=str(s.label),
  473. line_color=s.line_color.getRgb()\
  474. if s.line_color != self.lineColor else None,
  475. fill_color=s.fill_color.getRgb()\
  476. if s.fill_color != self.fillColor else None,
  477. points=[(p.x(), p.y()) for p in s.points])
  478. shapes = [format_shape(shape) for shape in self.canvas.shapes]
  479. try:
  480. imagePath = os.path.relpath(
  481. self.imagePath, os.path.dirname(filename))
  482. imageData = self.imageData if self._store_data else None
  483. lf.save(filename, shapes, imagePath, imageData,
  484. self.lineColor.getRgb(), self.fillColor.getRgb())
  485. self.labelFile = lf
  486. self.filename = filename
  487. return True
  488. except LabelFileError as e:
  489. self.errorMessage('Error saving label data',
  490. '<b>%s</b>' % e)
  491. return False
  492. def copySelectedShape(self):
  493. self.addLabel(self.canvas.copySelectedShape())
  494. #fix copy and delete
  495. self.shapeSelectionChanged(True)
  496. def labelSelectionChanged(self):
  497. item = self.currentItem()
  498. if item and self.canvas.editing():
  499. self._noSelectionSlot = True
  500. for item_, shape in self.itemsToShapes:
  501. if item_ == item:
  502. break
  503. self.canvas.selectShape(shape)
  504. def labelItemChanged(self, item):
  505. for item_, shape in self.itemsToShapes:
  506. if item_ == item:
  507. break
  508. label = str(item.text())
  509. if label != shape.label:
  510. shape.label = str(item.text())
  511. self.setDirty()
  512. else: # User probably changed item visibility
  513. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  514. ## Callback functions:
  515. def newShape(self):
  516. """Pop-up and give focus to the label editor.
  517. position MUST be in global coordinates.
  518. """
  519. text = self.labelDialog.popUp()
  520. if text is not None:
  521. self.addLabel(self.canvas.setLastLabel(text))
  522. if self.beginner(): # Switch to edit mode.
  523. self.canvas.setEditing(True)
  524. self.actions.create.setEnabled(True)
  525. else:
  526. self.actions.editMode.setEnabled(True)
  527. self.setDirty()
  528. else:
  529. self.canvas.undoLastLine()
  530. def scrollRequest(self, delta, orientation):
  531. units = - delta * 0.1 # natural scroll
  532. bar = self.scrollBars[orientation]
  533. bar.setValue(bar.value() + bar.singleStep() * units)
  534. def setZoom(self, value):
  535. self.actions.fitWidth.setChecked(False)
  536. self.actions.fitWindow.setChecked(False)
  537. self.zoomMode = self.MANUAL_ZOOM
  538. self.zoomWidget.setValue(value)
  539. def addZoom(self, increment=10):
  540. self.setZoom(self.zoomWidget.value() + increment)
  541. def zoomRequest(self, delta):
  542. units = delta * 0.1
  543. self.addZoom(units)
  544. def setFitWindow(self, value=True):
  545. if value:
  546. self.actions.fitWidth.setChecked(False)
  547. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  548. self.adjustScale()
  549. def setFitWidth(self, value=True):
  550. if value:
  551. self.actions.fitWindow.setChecked(False)
  552. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  553. self.adjustScale()
  554. def togglePolygons(self, value):
  555. for item, shape in self.itemsToShapes:
  556. item.setCheckState(Qt.Checked if value else Qt.Unchecked)
  557. def loadFile(self, filename=None):
  558. """Load the specified file, or the last opened file if None."""
  559. self.resetState()
  560. self.canvas.setEnabled(False)
  561. if filename is None:
  562. filename = self.settings.get('filename', '')
  563. filename = str(filename)
  564. if QFile.exists(filename):
  565. if LabelFile.isLabelFile(filename):
  566. try:
  567. self.labelFile = LabelFile(filename)
  568. # FIXME: PyQt4 installed via Anaconda fails to load JPEG
  569. # and JSON encoded images.
  570. # https://github.com/ContinuumIO/anaconda-issues/issues/131
  571. if QImage.fromData(self.labelFile.imageData).isNull():
  572. raise LabelFileError(
  573. 'Failed loading image data from label file.\n'
  574. 'Maybe this is a known issue of PyQt4 built on'
  575. ' Anaconda, and may be fixed by installing PyQt5.')
  576. except LabelFileError as e:
  577. self.errorMessage('Error opening file',
  578. ("<p><b>%s</b></p>"
  579. "<p>Make sure <i>%s</i> is a valid label file.")\
  580. % (e, filename))
  581. self.status("Error reading %s" % filename)
  582. return False
  583. self.imageData = self.labelFile.imageData
  584. self.imagePath = os.path.join(os.path.dirname(filename),
  585. self.labelFile.imagePath)
  586. self.lineColor = QColor(*self.labelFile.lineColor)
  587. self.fillColor = QColor(*self.labelFile.fillColor)
  588. else:
  589. # Load image:
  590. # read data first and store for saving into label file.
  591. self.imageData = read(filename, None)
  592. if self.imageData is not None:
  593. # the filename is image not JSON
  594. self.imagePath = filename
  595. self.labelFile = None
  596. image = QImage.fromData(self.imageData)
  597. if image.isNull():
  598. formats = ['*.{}'.format(fmt.data().decode())
  599. for fmt in QImageReader.supportedImageFormats()]
  600. self.errorMessage(
  601. 'Error opening file',
  602. '<p>Make sure <i>{0}</i> is a valid image file.<br/>'
  603. 'Supported image formats: {1}</p>'
  604. .format(filename, ','.join(formats)))
  605. self.status("Error reading %s" % filename)
  606. return False
  607. self.status("Loaded %s" % os.path.basename(str(filename)))
  608. self.image = image
  609. self.filename = filename
  610. self.canvas.loadPixmap(QPixmap.fromImage(image))
  611. if self.labelFile:
  612. self.loadLabels(self.labelFile.shapes)
  613. self.setClean()
  614. self.canvas.setEnabled(True)
  615. self.adjustScale(initial=True)
  616. self.paintCanvas()
  617. self.addRecentFile(self.filename)
  618. self.toggleActions(True)
  619. return True
  620. return False
  621. def resizeEvent(self, event):
  622. if self.canvas and not self.image.isNull()\
  623. and self.zoomMode != self.MANUAL_ZOOM:
  624. self.adjustScale()
  625. super(MainWindow, self).resizeEvent(event)
  626. def paintCanvas(self):
  627. assert not self.image.isNull(), "cannot paint null image"
  628. self.canvas.scale = 0.01 * self.zoomWidget.value()
  629. self.canvas.adjustSize()
  630. self.canvas.update()
  631. def adjustScale(self, initial=False):
  632. value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
  633. self.zoomWidget.setValue(int(100 * value))
  634. def scaleFitWindow(self):
  635. """Figure out the size of the pixmap in order to fit the main widget."""
  636. e = 2.0 # So that no scrollbars are generated.
  637. w1 = self.centralWidget().width() - e
  638. h1 = self.centralWidget().height() - e
  639. a1 = w1/ h1
  640. # Calculate a new scale value based on the pixmap's aspect ratio.
  641. w2 = self.canvas.pixmap.width() - 0.0
  642. h2 = self.canvas.pixmap.height() - 0.0
  643. a2 = w2 / h2
  644. return w1 / w2 if a2 >= a1 else h1 / h2
  645. def scaleFitWidth(self):
  646. # The epsilon does not seem to work too well here.
  647. w = self.centralWidget().width() - 2.0
  648. return w / self.canvas.pixmap.width()
  649. def closeEvent(self, event):
  650. if not self.mayContinue():
  651. event.ignore()
  652. s = self.settings
  653. s['filename'] = self.filename if self.filename else ''
  654. s['window/size'] = self.size()
  655. s['window/position'] = self.pos()
  656. s['window/state'] = self.saveState()
  657. s['line/color'] = self.lineColor
  658. s['fill/color'] = self.fillColor
  659. s['recentFiles'] = self.recentFiles
  660. s['advanced'] = not self._beginner
  661. # ask the use for where to save the labels
  662. #s['window/geometry'] = self.saveGeometry()
  663. ## User Dialogs ##
  664. def loadRecent(self, filename):
  665. if self.mayContinue():
  666. self.loadFile(filename)
  667. def openFile(self, _value=False):
  668. if not self.mayContinue():
  669. return
  670. path = os.path.dirname(str(self.filename))\
  671. if self.filename else '.'
  672. formats = ['*.{}'.format(fmt.data().decode())
  673. for fmt in QImageReader.supportedImageFormats()]
  674. filters = "Image & Label files (%s)" % \
  675. ' '.join(formats + ['*%s' % LabelFile.suffix])
  676. filename = QFileDialog.getOpenFileName(self,
  677. '%s - Choose Image or Label file' % __appname__, path, filters)
  678. if PYQT5:
  679. filename, _ = filename
  680. filename = str(filename)
  681. if filename:
  682. self.loadFile(filename)
  683. def saveFile(self, _value=False):
  684. assert not self.image.isNull(), "cannot save empty image"
  685. if self.hasLabels():
  686. if self.labelFile:
  687. self._saveFile(self.filename)
  688. elif self.output:
  689. self._saveFile(self.output)
  690. else:
  691. self._saveFile(self.saveFileDialog())
  692. def saveFileAs(self, _value=False):
  693. assert not self.image.isNull(), "cannot save empty image"
  694. if self.hasLabels():
  695. self._saveFile(self.saveFileDialog())
  696. def saveFileDialog(self):
  697. caption = '%s - Choose File' % __appname__
  698. filters = 'Label files (*%s)' % LabelFile.suffix
  699. dlg = QFileDialog(self, caption, self.currentPath(), filters)
  700. dlg.setDefaultSuffix(LabelFile.suffix[1:])
  701. dlg.setAcceptMode(QFileDialog.AcceptSave)
  702. dlg.setOption(QFileDialog.DontConfirmOverwrite, False)
  703. dlg.setOption(QFileDialog.DontUseNativeDialog, False)
  704. basename = os.path.splitext(self.filename)[0]
  705. default_labelfile_name = os.path.join(self.currentPath(),
  706. basename + LabelFile.suffix)
  707. filename = dlg.getSaveFileName(
  708. self, 'Choose File', default_labelfile_name,
  709. 'Label files (*%s)' % LabelFile.suffix)
  710. if PYQT5:
  711. filename, _ = filename
  712. filename = str(filename)
  713. return filename
  714. def _saveFile(self, filename):
  715. if filename and self.saveLabels(filename):
  716. self.addRecentFile(filename)
  717. self.setClean()
  718. if self.labeling_once:
  719. self.close()
  720. def closeFile(self, _value=False):
  721. if not self.mayContinue():
  722. return
  723. self.resetState()
  724. self.setClean()
  725. self.toggleActions(False)
  726. self.canvas.setEnabled(False)
  727. self.actions.saveAs.setEnabled(False)
  728. # Message Dialogs. #
  729. def hasLabels(self):
  730. if not self.itemsToShapes:
  731. self.errorMessage('No objects labeled',
  732. 'You must label at least one object to save the file.')
  733. return False
  734. return True
  735. def mayContinue(self):
  736. return not (self.dirty and not self.discardChangesDialog())
  737. def discardChangesDialog(self):
  738. yes, no = QMessageBox.Yes, QMessageBox.No
  739. msg = 'You have unsaved changes, proceed anyway?'
  740. return yes == QMessageBox.warning(self, 'Attention', msg, yes|no)
  741. def errorMessage(self, title, message):
  742. return QMessageBox.critical(self, title,
  743. '<p><b>%s</b></p>%s' % (title, message))
  744. def currentPath(self):
  745. return os.path.dirname(str(self.filename)) if self.filename else '.'
  746. def chooseColor1(self):
  747. color = self.colorDialog.getColor(self.lineColor, 'Choose line color',
  748. default=DEFAULT_LINE_COLOR)
  749. if color:
  750. self.lineColor = color
  751. # Change the color for all shape lines:
  752. Shape.line_color = self.lineColor
  753. self.canvas.update()
  754. self.setDirty()
  755. def chooseColor2(self):
  756. color = self.colorDialog.getColor(self.fillColor, 'Choose fill color',
  757. default=DEFAULT_FILL_COLOR)
  758. if color:
  759. self.fillColor = color
  760. Shape.fill_color = self.fillColor
  761. self.canvas.update()
  762. self.setDirty()
  763. def deleteSelectedShape(self):
  764. yes, no = QMessageBox.Yes, QMessageBox.No
  765. msg = 'You are about to permanently delete this polygon, proceed anyway?'
  766. if yes == QMessageBox.warning(self, 'Attention', msg, yes|no):
  767. self.remLabel(self.canvas.deleteSelected())
  768. self.setDirty()
  769. if self.noShapes():
  770. for action in self.actions.onShapesPresent:
  771. action.setEnabled(False)
  772. def chshapeLineColor(self):
  773. color = self.colorDialog.getColor(self.lineColor, 'Choose line color',
  774. default=DEFAULT_LINE_COLOR)
  775. if color:
  776. self.canvas.selectedShape.line_color = color
  777. self.canvas.update()
  778. self.setDirty()
  779. def chshapeFillColor(self):
  780. color = self.colorDialog.getColor(self.fillColor, 'Choose fill color',
  781. default=DEFAULT_FILL_COLOR)
  782. if color:
  783. self.canvas.selectedShape.fill_color = color
  784. self.canvas.update()
  785. self.setDirty()
  786. def copyShape(self):
  787. self.canvas.endMove(copy=True)
  788. self.addLabel(self.canvas.selectedShape)
  789. self.setDirty()
  790. def moveShape(self):
  791. self.canvas.endMove(copy=False)
  792. self.setDirty()
  793. class Settings(object):
  794. """Convenience dict-like wrapper around QSettings."""
  795. def __init__(self, types=None):
  796. self.data = QSettings()
  797. self.types = defaultdict(lambda: QVariant, types if types else {})
  798. def __setitem__(self, key, value):
  799. t = self.types[key]
  800. self.data.setValue(key,
  801. t(value) if not isinstance(value, t) else value)
  802. def __getitem__(self, key):
  803. return self._cast(key, self.data.value(key))
  804. def get(self, key, default=None):
  805. return self._cast(key, self.data.value(key, default))
  806. def _cast(self, key, value):
  807. # XXX: Very nasty way of converting types to QVariant methods :P
  808. t = self.types[key]
  809. if t != QVariant:
  810. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  811. return method(value)
  812. return value
  813. def inverted(color):
  814. return QColor(*[255 - v for v in color.getRgb()])
  815. def read(filename, default=None):
  816. try:
  817. with open(filename, 'rb') as f:
  818. return f.read()
  819. except:
  820. return default
  821. def main():
  822. """Standard boilerplate Qt application code."""
  823. parser = argparse.ArgumentParser()
  824. parser.add_argument('filename', nargs='?', help='image or label filename')
  825. parser.add_argument('--output', '-O', '-o', help='output label name')
  826. parser.add_argument('--nodata', dest='store_data', action='store_false',
  827. help='Stop storing image data to JSON file.')
  828. args = parser.parse_args()
  829. app = QApplication(sys.argv)
  830. app.setApplicationName(__appname__)
  831. app.setWindowIcon(newIcon("app"))
  832. win = MainWindow(args.filename, args.output, args.store_data)
  833. win.show()
  834. win.raise_()
  835. sys.exit(app.exec_())