app.py 35 KB

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