app.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. import functools
  2. import os
  3. import os.path as osp
  4. import re
  5. import webbrowser
  6. from qtpy import QtCore
  7. from qtpy.QtCore import Qt
  8. from qtpy import QtGui
  9. from qtpy import QtWidgets
  10. from labelme import __appname__
  11. from labelme import PY2
  12. from labelme import QT5
  13. from . import utils
  14. from labelme.config import get_config
  15. from labelme.label_file import LabelFile
  16. from labelme.label_file import LabelFileError
  17. from labelme.logger import logger
  18. from labelme.shape import DEFAULT_FILL_COLOR
  19. from labelme.shape import DEFAULT_LINE_COLOR
  20. from labelme.shape import Shape
  21. from labelme.widgets import Canvas
  22. from labelme.widgets import ColorDialog
  23. from labelme.widgets import EscapableQListWidget
  24. from labelme.widgets import LabelDialog
  25. from labelme.widgets import LabelQListWidget
  26. from labelme.widgets import ToolBar
  27. from labelme.widgets import ZoomWidget
  28. # FIXME
  29. # - [medium] Set max zoom value to something big enough for FitWidth/Window
  30. # TODO(unknown):
  31. # - [high] Add polygon movement with arrow keys
  32. # - [high] Deselect shape when clicking and already selected(?)
  33. # - [low,maybe] Open images with drag & drop.
  34. # - [low,maybe] Preview images on file dialogs.
  35. # - Zoom is too "steppy".
  36. class MainWindow(QtWidgets.QMainWindow):
  37. FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = 0, 1, 2
  38. def __init__(
  39. self,
  40. config=None,
  41. filename=None,
  42. output=None,
  43. output_file=None,
  44. output_dir=None,
  45. ):
  46. if output is not None:
  47. logger.warning(
  48. 'argument output is deprecated, use output_file instead'
  49. )
  50. if output_file is None:
  51. output_file = output
  52. # see labelme/config/default_config.yaml for valid configuration
  53. if config is None:
  54. config = get_config()
  55. self._config = config
  56. super(MainWindow, self).__init__()
  57. self.setWindowTitle(__appname__)
  58. # Whether we need to save or not.
  59. self.dirty = False
  60. self._noSelectionSlot = False
  61. # Main widgets and related state.
  62. self.labelDialog = LabelDialog(
  63. parent=self,
  64. labels=self._config['labels'],
  65. sort_labels=self._config['sort_labels'],
  66. show_text_field=self._config['show_label_text_field'],
  67. completion=self._config['label_completion'],
  68. fit_to_content=self._config['fit_to_content'],
  69. flags=self._config['label_flags']
  70. )
  71. self.labelList = LabelQListWidget()
  72. self.lastOpenDir = None
  73. self.flag_dock = self.flag_widget = None
  74. self.flag_dock = QtWidgets.QDockWidget(self.tr('Flags'), self)
  75. self.flag_dock.setObjectName('Flags')
  76. self.flag_widget = QtWidgets.QListWidget()
  77. if config['flags']:
  78. self.loadFlags({k: False for k in config['flags']})
  79. self.flag_dock.setWidget(self.flag_widget)
  80. self.flag_widget.itemChanged.connect(self.setDirty)
  81. self.labelList.itemActivated.connect(self.labelSelectionChanged)
  82. self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
  83. self.labelList.itemDoubleClicked.connect(self.editLabel)
  84. # Connect to itemChanged to detect checkbox changes.
  85. self.labelList.itemChanged.connect(self.labelItemChanged)
  86. self.labelList.setDragDropMode(
  87. QtWidgets.QAbstractItemView.InternalMove)
  88. self.labelList.setParent(self)
  89. self.shape_dock = QtWidgets.QDockWidget(
  90. self.tr('Polygon Labels'),
  91. self
  92. )
  93. self.shape_dock.setObjectName('Labels')
  94. self.shape_dock.setWidget(self.labelList)
  95. self.uniqLabelList = EscapableQListWidget()
  96. self.uniqLabelList.setToolTip(self.tr(
  97. "Select label to start annotating for it. "
  98. "Press 'Esc' to deselect."))
  99. if self._config['labels']:
  100. self.uniqLabelList.addItems(self._config['labels'])
  101. self.uniqLabelList.sortItems()
  102. self.label_dock = QtWidgets.QDockWidget(self.tr(u'Label List'), self)
  103. self.label_dock.setObjectName(u'Label List')
  104. self.label_dock.setWidget(self.uniqLabelList)
  105. self.fileSearch = QtWidgets.QLineEdit()
  106. self.fileSearch.setPlaceholderText(self.tr('Search Filename'))
  107. self.fileSearch.textChanged.connect(self.fileSearchChanged)
  108. self.fileListWidget = QtWidgets.QListWidget()
  109. self.fileListWidget.itemSelectionChanged.connect(
  110. self.fileSelectionChanged
  111. )
  112. fileListLayout = QtWidgets.QVBoxLayout()
  113. fileListLayout.setContentsMargins(0, 0, 0, 0)
  114. fileListLayout.setSpacing(0)
  115. fileListLayout.addWidget(self.fileSearch)
  116. fileListLayout.addWidget(self.fileListWidget)
  117. self.file_dock = QtWidgets.QDockWidget(self.tr(u'File List'), self)
  118. self.file_dock.setObjectName(u'Files')
  119. fileListWidget = QtWidgets.QWidget()
  120. fileListWidget.setLayout(fileListLayout)
  121. self.file_dock.setWidget(fileListWidget)
  122. self.zoomWidget = ZoomWidget()
  123. self.colorDialog = ColorDialog(parent=self)
  124. self.canvas = self.labelList.canvas = Canvas(
  125. epsilon=self._config['epsilon'],
  126. )
  127. self.canvas.zoomRequest.connect(self.zoomRequest)
  128. scrollArea = QtWidgets.QScrollArea()
  129. scrollArea.setWidget(self.canvas)
  130. scrollArea.setWidgetResizable(True)
  131. self.scrollBars = {
  132. Qt.Vertical: scrollArea.verticalScrollBar(),
  133. Qt.Horizontal: scrollArea.horizontalScrollBar(),
  134. }
  135. self.canvas.scrollRequest.connect(self.scrollRequest)
  136. self.canvas.newShape.connect(self.newShape)
  137. self.canvas.shapeMoved.connect(self.setDirty)
  138. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  139. self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)
  140. self.setCentralWidget(scrollArea)
  141. features = QtWidgets.QDockWidget.DockWidgetFeatures()
  142. for dock in ['flag_dock', 'label_dock', 'shape_dock', 'file_dock']:
  143. if self._config[dock]['closable']:
  144. features = features | QtWidgets.QDockWidget.DockWidgetClosable
  145. if self._config[dock]['floatable']:
  146. features = features | QtWidgets.QDockWidget.DockWidgetFloatable
  147. if self._config[dock]['movable']:
  148. features = features | QtWidgets.QDockWidget.DockWidgetMovable
  149. getattr(self, dock).setFeatures(features)
  150. if self._config[dock]['show'] is False:
  151. getattr(self, dock).setVisible(False)
  152. self.addDockWidget(Qt.RightDockWidgetArea, self.flag_dock)
  153. self.addDockWidget(Qt.RightDockWidgetArea, self.label_dock)
  154. self.addDockWidget(Qt.RightDockWidgetArea, self.shape_dock)
  155. self.addDockWidget(Qt.RightDockWidgetArea, self.file_dock)
  156. # Actions
  157. action = functools.partial(utils.newAction, self)
  158. shortcuts = self._config['shortcuts']
  159. quit = action(self.tr('&Quit'), self.close, shortcuts['quit'], 'quit',
  160. self.tr('Quit application'))
  161. open_ = action(self.tr('&Open'),
  162. self.openFile,
  163. shortcuts['open'],
  164. 'open',
  165. self.tr('Open image or label file'))
  166. opendir = action(self.tr('&Open Dir'), self.openDirDialog,
  167. shortcuts['open_dir'], 'open', self.tr(u'Open Dir'))
  168. openNextImg = action(
  169. self.tr('&Next Image'),
  170. self.openNextImg,
  171. shortcuts['open_next'],
  172. 'next',
  173. self.tr(u'Open next (hold Ctl+Shift to copy labels)'),
  174. enabled=False,
  175. )
  176. openPrevImg = action(
  177. self.tr('&Prev Image'),
  178. self.openPrevImg,
  179. shortcuts['open_prev'],
  180. 'prev',
  181. self.tr(u'Open prev (hold Ctl+Shift to copy labels)'),
  182. enabled=False,
  183. )
  184. save = action(self.tr('&Save'),
  185. self.saveFile, shortcuts['save'], 'save',
  186. self.tr('Save labels to file'), enabled=False)
  187. saveAs = action(self.tr('&Save As'), self.saveFileAs,
  188. shortcuts['save_as'],
  189. 'save-as', self.tr('Save labels to a different file'),
  190. enabled=False)
  191. deleteFile = action(
  192. self.tr('&Delete File'),
  193. self.deleteFile,
  194. shortcuts['delete_file'],
  195. 'delete',
  196. self.tr('Delete current label file'),
  197. enabled=False)
  198. changeOutputDir = action(
  199. self.tr('&Change Output Dir'),
  200. slot=self.changeOutputDirDialog,
  201. shortcut=shortcuts['save_to'],
  202. icon='open',
  203. tip=self.tr(u'Change where annotations are loaded/saved')
  204. )
  205. saveAuto = action(
  206. text=self.tr('Save &Automatically'),
  207. slot=lambda x: self.actions.saveAuto.setChecked(x),
  208. icon='save',
  209. tip=self.tr('Save automatically'),
  210. checkable=True,
  211. enabled=True,
  212. )
  213. saveAuto.setChecked(self._config['auto_save'])
  214. saveWithImageData = action(
  215. text='Save With Image Data',
  216. slot=self.enableSaveImageWithData,
  217. tip='Save image data in label file',
  218. checkable=True,
  219. checked=self._config['store_data'],
  220. )
  221. close = action('&Close', self.closeFile, shortcuts['close'], 'close',
  222. 'Close current file')
  223. color1 = action('Polygon &Line Color', self.chooseColor1,
  224. shortcuts['edit_line_color'], 'color-line',
  225. 'Choose polygon line color')
  226. color2 = action('Polygon &Fill Color', self.chooseColor2,
  227. shortcuts['edit_fill_color'], 'color',
  228. self.tr('Choose polygon fill color'))
  229. toggle_keep_prev_mode = action(
  230. self.tr('Keep Previous Annotation'),
  231. self.toggleKeepPrevMode,
  232. shortcuts['toggle_keep_prev_mode'], None,
  233. self.tr('Toggle "keep pevious annotation" mode'),
  234. checkable=True)
  235. toggle_keep_prev_mode.setChecked(self._config['keep_prev'])
  236. createMode = action(
  237. self.tr('Create Polygons'),
  238. lambda: self.toggleDrawMode(False, createMode='polygon'),
  239. shortcuts['create_polygon'],
  240. 'objects',
  241. self.tr('Start drawing polygons'),
  242. enabled=False,
  243. )
  244. createRectangleMode = action(
  245. self.tr('Create Rectangle'),
  246. lambda: self.toggleDrawMode(False, createMode='rectangle'),
  247. shortcuts['create_rectangle'],
  248. 'objects',
  249. self.tr('Start drawing rectangles'),
  250. enabled=False,
  251. )
  252. createCircleMode = action(
  253. self.tr('Create Circle'),
  254. lambda: self.toggleDrawMode(False, createMode='circle'),
  255. shortcuts['create_circle'],
  256. 'objects',
  257. self.tr('Start drawing circles'),
  258. enabled=False,
  259. )
  260. createLineMode = action(
  261. self.tr('Create Line'),
  262. lambda: self.toggleDrawMode(False, createMode='line'),
  263. shortcuts['create_line'],
  264. 'objects',
  265. self.tr('Start drawing lines'),
  266. enabled=False,
  267. )
  268. createPointMode = action(
  269. self.tr('Create Point'),
  270. lambda: self.toggleDrawMode(False, createMode='point'),
  271. shortcuts['create_point'],
  272. 'objects',
  273. self.tr('Start drawing points'),
  274. enabled=False,
  275. )
  276. createLineStripMode = action(
  277. self.tr('Create LineStrip'),
  278. lambda: self.toggleDrawMode(False, createMode='linestrip'),
  279. shortcuts['create_linestrip'],
  280. 'objects',
  281. self.tr('Start drawing linestrip. Ctrl+LeftClick ends creation.'),
  282. enabled=False,
  283. )
  284. editMode = action(self.tr('Edit Polygons'), self.setEditMode,
  285. shortcuts['edit_polygon'], 'edit',
  286. self.tr('Move and edit the selected polygons'),
  287. enabled=False)
  288. delete = action(self.tr('Delete Polygons'), self.deleteSelectedShape,
  289. shortcuts['delete_polygon'], 'cancel',
  290. self.tr('Delete the selected polygons'), enabled=False)
  291. copy = action(self.tr('Duplicate Polygons'), self.copySelectedShape,
  292. shortcuts['duplicate_polygon'], 'copy',
  293. self.tr('Create a duplicate of the selected polygons'),
  294. enabled=False)
  295. undoLastPoint = action(self.tr('Undo last point'),
  296. self.canvas.undoLastPoint,
  297. shortcuts['undo_last_point'], 'undo',
  298. self.tr('Undo last drawn point'), enabled=False)
  299. addPointToEdge = action(
  300. self.tr('Add Point to Edge'),
  301. self.canvas.addPointToEdge,
  302. None,
  303. 'edit',
  304. self.tr('Add point to the nearest edge'),
  305. enabled=False,
  306. )
  307. removePoint = action(
  308. text='Remove Selected Point',
  309. slot=self.canvas.removeSelectedPoint,
  310. icon='edit',
  311. tip='Remove selected point from polygon',
  312. enabled=False,
  313. )
  314. undo = action(self.tr('Undo'), self.undoShapeEdit,
  315. shortcuts['undo'], 'undo',
  316. self.tr('Undo last add and edit of shape'),
  317. enabled=False)
  318. hideAll = action(self.tr('&Hide\nPolygons'),
  319. functools.partial(self.togglePolygons, False),
  320. icon='eye', tip=self.tr('Hide all polygons'),
  321. enabled=False)
  322. showAll = action(self.tr('&Show\nPolygons'),
  323. functools.partial(self.togglePolygons, True),
  324. icon='eye', tip=self.tr('Show all polygons'),
  325. enabled=False)
  326. help = action(self.tr('&Tutorial'), self.tutorial, icon='help',
  327. tip=self.tr('Show tutorial page'))
  328. zoom = QtWidgets.QWidgetAction(self)
  329. zoom.setDefaultWidget(self.zoomWidget)
  330. self.zoomWidget.setWhatsThis(
  331. self.tr(
  332. 'Zoom in or out of the image. Also accessible with '
  333. '{} and {} from the canvas.'
  334. ).format(
  335. utils.fmtShortcut(
  336. '{},{}'.format(
  337. shortcuts['zoom_in'], shortcuts['zoom_out']
  338. )
  339. ),
  340. utils.fmtShortcut(self.tr("Ctrl+Wheel")),
  341. )
  342. )
  343. self.zoomWidget.setEnabled(False)
  344. zoomIn = action(self.tr('Zoom &In'),
  345. functools.partial(self.addZoom, 1.1),
  346. shortcuts['zoom_in'], 'zoom-in',
  347. self.tr('Increase zoom level'), enabled=False)
  348. zoomOut = action(self.tr('&Zoom Out'),
  349. functools.partial(self.addZoom, 0.9),
  350. shortcuts['zoom_out'], 'zoom-out',
  351. self.tr('Decrease zoom level'), enabled=False)
  352. zoomOrg = action(self.tr('&Original size'),
  353. functools.partial(self.setZoom, 100),
  354. shortcuts['zoom_to_original'], 'zoom',
  355. self.tr('Zoom to original size'), enabled=False)
  356. fitWindow = action(self.tr('&Fit Window'), self.setFitWindow,
  357. shortcuts['fit_window'], 'fit-window',
  358. self.tr('Zoom follows window size'), checkable=True,
  359. enabled=False)
  360. fitWidth = action(self.tr('Fit &Width'), self.setFitWidth,
  361. shortcuts['fit_width'], 'fit-width',
  362. self.tr('Zoom follows window width'),
  363. checkable=True, enabled=False)
  364. # Group zoom controls into a list for easier toggling.
  365. zoomActions = (self.zoomWidget, zoomIn, zoomOut, zoomOrg,
  366. fitWindow, fitWidth)
  367. self.zoomMode = self.FIT_WINDOW
  368. fitWindow.setChecked(Qt.Checked)
  369. self.scalers = {
  370. self.FIT_WINDOW: self.scaleFitWindow,
  371. self.FIT_WIDTH: self.scaleFitWidth,
  372. # Set to one to scale to 100% when loading files.
  373. self.MANUAL_ZOOM: lambda: 1,
  374. }
  375. edit = action(self.tr('&Edit Label'), self.editLabel,
  376. shortcuts['edit_label'], 'edit',
  377. self.tr('Modify the label of the selected polygon'),
  378. enabled=False)
  379. shapeLineColor = action(
  380. self.tr('Shape &Line Color'), self.chshapeLineColor,
  381. icon='color-line',
  382. tip=self.tr('Change the line color for this specific shape'),
  383. enabled=False
  384. )
  385. shapeFillColor = action(
  386. self.tr('Shape &Fill Color'), self.chshapeFillColor, icon='color',
  387. tip=self.tr('Change the fill color for this specific shape'),
  388. enabled=False
  389. )
  390. fill_drawing = action(
  391. self.tr('Fill Drawing Polygon'),
  392. lambda x: self.canvas.setFillDrawing(x),
  393. None,
  394. 'color',
  395. self.tr('Fill polygon while drawing'),
  396. checkable=True,
  397. enabled=True,
  398. )
  399. fill_drawing.setChecked(True)
  400. # Lavel list context menu.
  401. labelMenu = QtWidgets.QMenu()
  402. utils.addActions(labelMenu, (edit, delete))
  403. self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
  404. self.labelList.customContextMenuRequested.connect(
  405. self.popLabelListMenu)
  406. # Store actions for further handling.
  407. self.actions = utils.struct(
  408. saveAuto=saveAuto,
  409. saveWithImageData=saveWithImageData,
  410. changeOutputDir=changeOutputDir,
  411. save=save, saveAs=saveAs, open=open_, close=close,
  412. deleteFile=deleteFile,
  413. lineColor=color1, fillColor=color2,
  414. toggleKeepPrevMode=toggle_keep_prev_mode,
  415. delete=delete, edit=edit, copy=copy,
  416. undoLastPoint=undoLastPoint, undo=undo,
  417. addPointToEdge=addPointToEdge, removePoint=removePoint,
  418. createMode=createMode, editMode=editMode,
  419. createRectangleMode=createRectangleMode,
  420. createCircleMode=createCircleMode,
  421. createLineMode=createLineMode,
  422. createPointMode=createPointMode,
  423. createLineStripMode=createLineStripMode,
  424. shapeLineColor=shapeLineColor, shapeFillColor=shapeFillColor,
  425. zoom=zoom, zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
  426. fitWindow=fitWindow, fitWidth=fitWidth,
  427. zoomActions=zoomActions,
  428. openNextImg=openNextImg, openPrevImg=openPrevImg,
  429. fileMenuActions=(open_, opendir, save, saveAs, close, quit),
  430. tool=(),
  431. # XXX: need to add some actions here to activate the shortcut
  432. editMenu=(
  433. edit,
  434. copy,
  435. delete,
  436. None,
  437. undo,
  438. undoLastPoint,
  439. None,
  440. addPointToEdge,
  441. None,
  442. color1,
  443. color2,
  444. None,
  445. toggle_keep_prev_mode,
  446. ),
  447. # menu shown at right click
  448. menu=(
  449. createMode,
  450. createRectangleMode,
  451. createCircleMode,
  452. createLineMode,
  453. createPointMode,
  454. createLineStripMode,
  455. editMode,
  456. edit,
  457. copy,
  458. delete,
  459. shapeLineColor,
  460. shapeFillColor,
  461. undo,
  462. undoLastPoint,
  463. addPointToEdge,
  464. removePoint,
  465. ),
  466. onLoadActive=(
  467. close,
  468. createMode,
  469. createRectangleMode,
  470. createCircleMode,
  471. createLineMode,
  472. createPointMode,
  473. createLineStripMode,
  474. editMode,
  475. ),
  476. onShapesPresent=(saveAs, hideAll, showAll),
  477. )
  478. self.canvas.edgeSelected.connect(self.canvasShapeEdgeSelected)
  479. self.canvas.vertexSelected.connect(self.actions.removePoint.setEnabled)
  480. self.menus = utils.struct(
  481. file=self.menu(self.tr('&File')),
  482. edit=self.menu(self.tr('&Edit')),
  483. view=self.menu(self.tr('&View')),
  484. help=self.menu(self.tr('&Help')),
  485. recentFiles=QtWidgets.QMenu(self.tr('Open &Recent')),
  486. labelList=labelMenu,
  487. )
  488. utils.addActions(
  489. self.menus.file,
  490. (
  491. open_,
  492. openNextImg,
  493. openPrevImg,
  494. opendir,
  495. self.menus.recentFiles,
  496. save,
  497. saveAs,
  498. saveAuto,
  499. changeOutputDir,
  500. saveWithImageData,
  501. close,
  502. deleteFile,
  503. None,
  504. quit,
  505. ),
  506. )
  507. utils.addActions(self.menus.help, (help,))
  508. utils.addActions(
  509. self.menus.view,
  510. (
  511. self.flag_dock.toggleViewAction(),
  512. self.label_dock.toggleViewAction(),
  513. self.shape_dock.toggleViewAction(),
  514. self.file_dock.toggleViewAction(),
  515. None,
  516. fill_drawing,
  517. None,
  518. hideAll,
  519. showAll,
  520. None,
  521. zoomIn,
  522. zoomOut,
  523. zoomOrg,
  524. None,
  525. fitWindow,
  526. fitWidth,
  527. None,
  528. ),
  529. )
  530. self.menus.file.aboutToShow.connect(self.updateFileMenu)
  531. # Custom context menu for the canvas widget:
  532. utils.addActions(self.canvas.menus[0], self.actions.menu)
  533. utils.addActions(
  534. self.canvas.menus[1],
  535. (
  536. action('&Copy here', self.copyShape),
  537. action('&Move here', self.moveShape),
  538. ),
  539. )
  540. self.tools = self.toolbar('Tools')
  541. # Menu buttons on Left
  542. self.actions.tool = (
  543. open_,
  544. opendir,
  545. openNextImg,
  546. openPrevImg,
  547. save,
  548. deleteFile,
  549. None,
  550. createMode,
  551. editMode,
  552. copy,
  553. delete,
  554. undo,
  555. None,
  556. zoomIn,
  557. zoom,
  558. zoomOut,
  559. fitWindow,
  560. fitWidth,
  561. )
  562. self.statusBar().showMessage(self.tr('%s started.') % __appname__)
  563. self.statusBar().show()
  564. if output_file is not None and self._config['auto_save']:
  565. logger.warn(
  566. 'If `auto_save` argument is True, `output_file` argument '
  567. 'is ignored and output filename is automatically '
  568. 'set as IMAGE_BASENAME.json.'
  569. )
  570. self.output_file = output_file
  571. self.output_dir = output_dir
  572. # Application state.
  573. self.image = QtGui.QImage()
  574. self.imagePath = None
  575. self.recentFiles = []
  576. self.maxRecent = 7
  577. self.lineColor = None
  578. self.fillColor = None
  579. self.otherData = None
  580. self.zoom_level = 100
  581. self.fit_window = False
  582. if filename is not None and osp.isdir(filename):
  583. self.importDirImages(filename, load=False)
  584. else:
  585. self.filename = filename
  586. if config['file_search']:
  587. self.fileSearch.setText(config['file_search'])
  588. self.fileSearchChanged()
  589. # XXX: Could be completely declarative.
  590. # Restore application settings.
  591. self.settings = QtCore.QSettings('labelme', 'labelme')
  592. # FIXME: QSettings.value can return None on PyQt4
  593. self.recentFiles = self.settings.value('recentFiles', []) or []
  594. size = self.settings.value('window/size', QtCore.QSize(600, 500))
  595. position = self.settings.value('window/position', QtCore.QPoint(0, 0))
  596. self.resize(size)
  597. self.move(position)
  598. # or simply:
  599. # self.restoreGeometry(settings['window/geometry']
  600. self.restoreState(
  601. self.settings.value('window/state', QtCore.QByteArray()))
  602. self.lineColor = QtGui.QColor(
  603. self.settings.value('line/color', Shape.line_color))
  604. self.fillColor = QtGui.QColor(
  605. self.settings.value('fill/color', Shape.fill_color))
  606. Shape.line_color = self.lineColor
  607. Shape.fill_color = self.fillColor
  608. # Populate the File menu dynamically.
  609. self.updateFileMenu()
  610. # Since loading the file may take some time,
  611. # make sure it runs in the background.
  612. if self.filename is not None:
  613. self.queueEvent(functools.partial(self.loadFile, self.filename))
  614. # Callbacks:
  615. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  616. self.populateModeActions()
  617. # self.firstStart = True
  618. # if self.firstStart:
  619. # QWhatsThis.enterWhatsThisMode()
  620. def menu(self, title, actions=None):
  621. menu = self.menuBar().addMenu(title)
  622. if actions:
  623. utils.addActions(menu, actions)
  624. return menu
  625. def toolbar(self, title, actions=None):
  626. toolbar = ToolBar(title)
  627. toolbar.setObjectName('%sToolBar' % title)
  628. # toolbar.setOrientation(Qt.Vertical)
  629. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  630. if actions:
  631. utils.addActions(toolbar, actions)
  632. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  633. return toolbar
  634. # Support Functions
  635. def noShapes(self):
  636. return not self.labelList.itemsToShapes
  637. def populateModeActions(self):
  638. tool, menu = self.actions.tool, self.actions.menu
  639. self.tools.clear()
  640. utils.addActions(self.tools, tool)
  641. self.canvas.menus[0].clear()
  642. utils.addActions(self.canvas.menus[0], menu)
  643. self.menus.edit.clear()
  644. actions = (
  645. self.actions.createMode,
  646. self.actions.createRectangleMode,
  647. self.actions.createCircleMode,
  648. self.actions.createLineMode,
  649. self.actions.createPointMode,
  650. self.actions.createLineStripMode,
  651. self.actions.editMode,
  652. )
  653. utils.addActions(self.menus.edit, actions + self.actions.editMenu)
  654. def setDirty(self):
  655. if self._config['auto_save'] or self.actions.saveAuto.isChecked():
  656. label_file = osp.splitext(self.imagePath)[0] + '.json'
  657. if self.output_dir:
  658. label_file_without_path = osp.basename(label_file)
  659. label_file = osp.join(self.output_dir, label_file_without_path)
  660. self.saveLabels(label_file)
  661. return
  662. self.dirty = True
  663. self.actions.save.setEnabled(True)
  664. self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
  665. title = __appname__
  666. if self.filename is not None:
  667. title = '{} - {}*'.format(title, self.filename)
  668. self.setWindowTitle(title)
  669. def setClean(self):
  670. self.dirty = False
  671. self.actions.save.setEnabled(False)
  672. self.actions.createMode.setEnabled(True)
  673. self.actions.createRectangleMode.setEnabled(True)
  674. self.actions.createCircleMode.setEnabled(True)
  675. self.actions.createLineMode.setEnabled(True)
  676. self.actions.createPointMode.setEnabled(True)
  677. self.actions.createLineStripMode.setEnabled(True)
  678. title = __appname__
  679. if self.filename is not None:
  680. title = '{} - {}'.format(title, self.filename)
  681. self.setWindowTitle(title)
  682. if self.hasLabelFile():
  683. self.actions.deleteFile.setEnabled(True)
  684. else:
  685. self.actions.deleteFile.setEnabled(False)
  686. def toggleActions(self, value=True):
  687. """Enable/Disable widgets which depend on an opened image."""
  688. for z in self.actions.zoomActions:
  689. z.setEnabled(value)
  690. for action in self.actions.onLoadActive:
  691. action.setEnabled(value)
  692. def canvasShapeEdgeSelected(self, selected, shape):
  693. self.actions.addPointToEdge.setEnabled(
  694. selected and shape and shape.canAddPoint()
  695. )
  696. def queueEvent(self, function):
  697. QtCore.QTimer.singleShot(0, function)
  698. def status(self, message, delay=5000):
  699. self.statusBar().showMessage(message, delay)
  700. def resetState(self):
  701. self.labelList.clear()
  702. self.filename = None
  703. self.imagePath = None
  704. self.imageData = None
  705. self.labelFile = None
  706. self.otherData = None
  707. self.canvas.resetState()
  708. def currentItem(self):
  709. items = self.labelList.selectedItems()
  710. if items:
  711. return items[0]
  712. return None
  713. def addRecentFile(self, filename):
  714. if filename in self.recentFiles:
  715. self.recentFiles.remove(filename)
  716. elif len(self.recentFiles) >= self.maxRecent:
  717. self.recentFiles.pop()
  718. self.recentFiles.insert(0, filename)
  719. # Callbacks
  720. def undoShapeEdit(self):
  721. self.canvas.restoreShape()
  722. self.labelList.clear()
  723. self.loadShapes(self.canvas.shapes)
  724. self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
  725. def tutorial(self):
  726. url = 'https://github.com/wkentaro/labelme/tree/master/examples/tutorial' # NOQA
  727. webbrowser.open(url)
  728. def toggleDrawingSensitive(self, drawing=True):
  729. """Toggle drawing sensitive.
  730. In the middle of drawing, toggling between modes should be disabled.
  731. """
  732. self.actions.editMode.setEnabled(not drawing)
  733. self.actions.undoLastPoint.setEnabled(drawing)
  734. self.actions.undo.setEnabled(not drawing)
  735. self.actions.delete.setEnabled(not drawing)
  736. def toggleDrawMode(self, edit=True, createMode='polygon'):
  737. self.canvas.setEditing(edit)
  738. self.canvas.createMode = createMode
  739. if edit:
  740. self.actions.createMode.setEnabled(True)
  741. self.actions.createRectangleMode.setEnabled(True)
  742. self.actions.createCircleMode.setEnabled(True)
  743. self.actions.createLineMode.setEnabled(True)
  744. self.actions.createPointMode.setEnabled(True)
  745. self.actions.createLineStripMode.setEnabled(True)
  746. else:
  747. if createMode == 'polygon':
  748. self.actions.createMode.setEnabled(False)
  749. self.actions.createRectangleMode.setEnabled(True)
  750. self.actions.createCircleMode.setEnabled(True)
  751. self.actions.createLineMode.setEnabled(True)
  752. self.actions.createPointMode.setEnabled(True)
  753. self.actions.createLineStripMode.setEnabled(True)
  754. elif createMode == 'rectangle':
  755. self.actions.createMode.setEnabled(True)
  756. self.actions.createRectangleMode.setEnabled(False)
  757. self.actions.createCircleMode.setEnabled(True)
  758. self.actions.createLineMode.setEnabled(True)
  759. self.actions.createPointMode.setEnabled(True)
  760. self.actions.createLineStripMode.setEnabled(True)
  761. elif createMode == 'line':
  762. self.actions.createMode.setEnabled(True)
  763. self.actions.createRectangleMode.setEnabled(True)
  764. self.actions.createCircleMode.setEnabled(True)
  765. self.actions.createLineMode.setEnabled(False)
  766. self.actions.createPointMode.setEnabled(True)
  767. self.actions.createLineStripMode.setEnabled(True)
  768. elif createMode == 'point':
  769. self.actions.createMode.setEnabled(True)
  770. self.actions.createRectangleMode.setEnabled(True)
  771. self.actions.createCircleMode.setEnabled(True)
  772. self.actions.createLineMode.setEnabled(True)
  773. self.actions.createPointMode.setEnabled(False)
  774. self.actions.createLineStripMode.setEnabled(True)
  775. elif createMode == "circle":
  776. self.actions.createMode.setEnabled(True)
  777. self.actions.createRectangleMode.setEnabled(True)
  778. self.actions.createCircleMode.setEnabled(False)
  779. self.actions.createLineMode.setEnabled(True)
  780. self.actions.createPointMode.setEnabled(True)
  781. self.actions.createLineStripMode.setEnabled(True)
  782. elif createMode == "linestrip":
  783. self.actions.createMode.setEnabled(True)
  784. self.actions.createRectangleMode.setEnabled(True)
  785. self.actions.createCircleMode.setEnabled(True)
  786. self.actions.createLineMode.setEnabled(True)
  787. self.actions.createPointMode.setEnabled(True)
  788. self.actions.createLineStripMode.setEnabled(False)
  789. else:
  790. raise ValueError('Unsupported createMode: %s' % createMode)
  791. self.actions.editMode.setEnabled(not edit)
  792. def setEditMode(self):
  793. self.toggleDrawMode(True)
  794. def updateFileMenu(self):
  795. current = self.filename
  796. def exists(filename):
  797. return osp.exists(str(filename))
  798. menu = self.menus.recentFiles
  799. menu.clear()
  800. files = [f for f in self.recentFiles if f != current and exists(f)]
  801. for i, f in enumerate(files):
  802. icon = utils.newIcon('labels')
  803. action = QtWidgets.QAction(
  804. icon, '&%d %s' % (i + 1, QtCore.QFileInfo(f).fileName()), self)
  805. action.triggered.connect(functools.partial(self.loadRecent, f))
  806. menu.addAction(action)
  807. def popLabelListMenu(self, point):
  808. self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
  809. def validateLabel(self, label):
  810. # no validation
  811. if self._config['validate_label'] is None:
  812. return True
  813. for i in range(self.uniqLabelList.count()):
  814. label_i = self.uniqLabelList.item(i).text()
  815. if self._config['validate_label'] in ['exact', 'instance']:
  816. if label_i == label:
  817. return True
  818. if self._config['validate_label'] == 'instance':
  819. m = re.match(r'^{}-[0-9]*$'.format(label_i), label)
  820. if m:
  821. return True
  822. return False
  823. def editLabel(self, item=False):
  824. if item and not isinstance(item, QtWidgets.QListWidgetItem):
  825. raise TypeError('unsupported type of item: {}'.format(type(item)))
  826. if not self.canvas.editing():
  827. return
  828. if not item:
  829. item = self.currentItem()
  830. if item is None:
  831. return
  832. shape = self.labelList.get_shape_from_item(item)
  833. if shape is None:
  834. return
  835. text, flags = self.labelDialog.popUp(shape.label, flags=shape.flags)
  836. if text is None:
  837. return
  838. if not self.validateLabel(text):
  839. self.errorMessage(
  840. self.tr('Invalid label'),
  841. self.tr(
  842. "Invalid label '{}' with validation type '{}'"
  843. ).format(text, self._config['validate_label'])
  844. )
  845. return
  846. shape.label = text
  847. shape.flags = flags
  848. item.setText(text)
  849. self.setDirty()
  850. if not self.uniqLabelList.findItems(text, Qt.MatchExactly):
  851. self.uniqLabelList.addItem(text)
  852. self.uniqLabelList.sortItems()
  853. def fileSearchChanged(self):
  854. self.importDirImages(
  855. self.lastOpenDir,
  856. pattern=self.fileSearch.text(),
  857. load=False,
  858. )
  859. def fileSelectionChanged(self):
  860. items = self.fileListWidget.selectedItems()
  861. if not items:
  862. return
  863. item = items[0]
  864. if not self.mayContinue():
  865. return
  866. currIndex = self.imageList.index(str(item.text()))
  867. if currIndex < len(self.imageList):
  868. filename = self.imageList[currIndex]
  869. if filename:
  870. self.loadFile(filename)
  871. # React to canvas signals.
  872. def shapeSelectionChanged(self, selected_shapes):
  873. self._noSelectionSlot = True
  874. for shape in self.canvas.selectedShapes:
  875. shape.selected = False
  876. self.labelList.clearSelection()
  877. self.canvas.selectedShapes = selected_shapes
  878. for shape in self.canvas.selectedShapes:
  879. shape.selected = True
  880. item = self.labelList.get_item_from_shape(shape)
  881. item.setSelected(True)
  882. self._noSelectionSlot = False
  883. n_selected = len(selected_shapes)
  884. self.actions.delete.setEnabled(n_selected)
  885. self.actions.copy.setEnabled(n_selected)
  886. self.actions.edit.setEnabled(n_selected == 1)
  887. self.actions.shapeLineColor.setEnabled(n_selected)
  888. self.actions.shapeFillColor.setEnabled(n_selected)
  889. def addLabel(self, shape):
  890. item = QtWidgets.QListWidgetItem(shape.label)
  891. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  892. item.setCheckState(Qt.Checked)
  893. self.labelList.itemsToShapes.append((item, shape))
  894. self.labelList.addItem(item)
  895. if not self.uniqLabelList.findItems(shape.label, Qt.MatchExactly):
  896. self.uniqLabelList.addItem(shape.label)
  897. self.uniqLabelList.sortItems()
  898. self.labelDialog.addLabelHistory(item.text())
  899. for action in self.actions.onShapesPresent:
  900. action.setEnabled(True)
  901. def remLabels(self, shapes):
  902. for shape in shapes:
  903. item = self.labelList.get_item_from_shape(shape)
  904. self.labelList.takeItem(self.labelList.row(item))
  905. def loadShapes(self, shapes, replace=True):
  906. self._noSelectionSlot = True
  907. for shape in shapes:
  908. self.addLabel(shape)
  909. self.labelList.clearSelection()
  910. self._noSelectionSlot = False
  911. self.canvas.loadShapes(shapes, replace=replace)
  912. def loadLabels(self, shapes):
  913. s = []
  914. for label, points, line_color, fill_color, shape_type, flags in shapes:
  915. shape = Shape(label=label, shape_type=shape_type)
  916. for x, y in points:
  917. shape.addPoint(QtCore.QPointF(x, y))
  918. shape.close()
  919. if line_color:
  920. shape.line_color = QtGui.QColor(*line_color)
  921. if fill_color:
  922. shape.fill_color = QtGui.QColor(*fill_color)
  923. default_flags = {}
  924. if self._config['label_flags']:
  925. for pattern, keys in self._config['label_flags'].items():
  926. if re.match(pattern, label):
  927. for key in keys:
  928. default_flags[key] = False
  929. shape.flags = default_flags
  930. shape.flags.update(flags)
  931. s.append(shape)
  932. self.loadShapes(s)
  933. def loadFlags(self, flags):
  934. self.flag_widget.clear()
  935. for key, flag in flags.items():
  936. item = QtWidgets.QListWidgetItem(key)
  937. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  938. item.setCheckState(Qt.Checked if flag else Qt.Unchecked)
  939. self.flag_widget.addItem(item)
  940. def saveLabels(self, filename):
  941. lf = LabelFile()
  942. def format_shape(s):
  943. return dict(
  944. label=s.label.encode('utf-8') if PY2 else s.label,
  945. line_color=s.line_color.getRgb()
  946. if s.line_color != self.lineColor else None,
  947. fill_color=s.fill_color.getRgb()
  948. if s.fill_color != self.fillColor else None,
  949. points=[(p.x(), p.y()) for p in s.points],
  950. shape_type=s.shape_type,
  951. flags=s.flags
  952. )
  953. shapes = [format_shape(shape) for shape in self.labelList.shapes]
  954. flags = {}
  955. for i in range(self.flag_widget.count()):
  956. item = self.flag_widget.item(i)
  957. key = item.text()
  958. flag = item.checkState() == Qt.Checked
  959. flags[key] = flag
  960. try:
  961. imagePath = osp.relpath(
  962. self.imagePath, osp.dirname(filename))
  963. imageData = self.imageData if self._config['store_data'] else None
  964. if osp.dirname(filename) and not osp.exists(osp.dirname(filename)):
  965. os.makedirs(osp.dirname(filename))
  966. lf.save(
  967. filename=filename,
  968. shapes=shapes,
  969. imagePath=imagePath,
  970. imageData=imageData,
  971. imageHeight=self.image.height(),
  972. imageWidth=self.image.width(),
  973. lineColor=self.lineColor.getRgb(),
  974. fillColor=self.fillColor.getRgb(),
  975. otherData=self.otherData,
  976. flags=flags,
  977. )
  978. self.labelFile = lf
  979. items = self.fileListWidget.findItems(
  980. self.imagePath, Qt.MatchExactly
  981. )
  982. if len(items) > 0:
  983. if len(items) != 1:
  984. raise RuntimeError('There are duplicate files.')
  985. items[0].setCheckState(Qt.Checked)
  986. # disable allows next and previous image to proceed
  987. # self.filename = filename
  988. return True
  989. except LabelFileError as e:
  990. self.errorMessage(
  991. self.tr('Error saving label data'),
  992. self.tr('<b>%s</b>') % e
  993. )
  994. return False
  995. def copySelectedShape(self):
  996. added_shapes = self.canvas.copySelectedShapes()
  997. self.labelList.clearSelection()
  998. for shape in added_shapes:
  999. self.addLabel(shape)
  1000. self.setDirty()
  1001. def labelSelectionChanged(self):
  1002. if self._noSelectionSlot:
  1003. return
  1004. if self.canvas.editing():
  1005. selected_shapes = []
  1006. for item in self.labelList.selectedItems():
  1007. shape = self.labelList.get_shape_from_item(item)
  1008. selected_shapes.append(shape)
  1009. if selected_shapes:
  1010. self.canvas.selectShapes(selected_shapes)
  1011. def labelItemChanged(self, item):
  1012. shape = self.labelList.get_shape_from_item(item)
  1013. label = str(item.text())
  1014. if label != shape.label:
  1015. shape.label = str(item.text())
  1016. self.setDirty()
  1017. else: # User probably changed item visibility
  1018. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  1019. # Callback functions:
  1020. def newShape(self):
  1021. """Pop-up and give focus to the label editor.
  1022. position MUST be in global coordinates.
  1023. """
  1024. items = self.uniqLabelList.selectedItems()
  1025. text = None
  1026. flags = {}
  1027. if items:
  1028. text = items[0].text()
  1029. if self._config['display_label_popup'] or not text:
  1030. # instance label auto increment
  1031. if self._config['instance_label_auto_increment']:
  1032. previous_label = self.labelDialog.edit.text()
  1033. split = previous_label.split('-')
  1034. if len(split) > 1 and split[-1].isdigit():
  1035. split[-1] = str(int(split[-1]) + 1)
  1036. instance_text = '-'.join(split)
  1037. else:
  1038. instance_text = previous_label
  1039. if instance_text != '':
  1040. text = instance_text
  1041. text, flags = self.labelDialog.popUp(text)
  1042. if text is None:
  1043. self.labelDialog.edit.setText(previous_label)
  1044. if text and not self.validateLabel(text):
  1045. self.errorMessage(
  1046. self.tr('Invalid label'),
  1047. self.tr(
  1048. "Invalid label '{}' with validation type '{}'"
  1049. ).format(text, self._config['validate_label'])
  1050. )
  1051. text = ''
  1052. if text:
  1053. self.labelList.clearSelection()
  1054. self.addLabel(self.canvas.setLastLabel(text, flags))
  1055. self.actions.editMode.setEnabled(True)
  1056. self.actions.undoLastPoint.setEnabled(False)
  1057. self.actions.undo.setEnabled(True)
  1058. self.setDirty()
  1059. else:
  1060. self.canvas.undoLastLine()
  1061. self.canvas.shapesBackups.pop()
  1062. def scrollRequest(self, delta, orientation):
  1063. units = - delta * 0.1 # natural scroll
  1064. bar = self.scrollBars[orientation]
  1065. bar.setValue(bar.value() + bar.singleStep() * units)
  1066. def setZoom(self, value):
  1067. self.actions.fitWidth.setChecked(False)
  1068. self.actions.fitWindow.setChecked(False)
  1069. self.zoomMode = self.MANUAL_ZOOM
  1070. self.zoomWidget.setValue(value)
  1071. def addZoom(self, increment=1.1):
  1072. self.setZoom(self.zoomWidget.value() * increment)
  1073. def zoomRequest(self, delta, pos):
  1074. canvas_width_old = self.canvas.width()
  1075. units = 1.1
  1076. if delta < 0:
  1077. units = 0.9
  1078. self.addZoom(units)
  1079. canvas_width_new = self.canvas.width()
  1080. if canvas_width_old != canvas_width_new:
  1081. canvas_scale_factor = canvas_width_new / canvas_width_old
  1082. x_shift = round(pos.x() * canvas_scale_factor) - pos.x()
  1083. y_shift = round(pos.y() * canvas_scale_factor) - pos.y()
  1084. self.scrollBars[Qt.Horizontal].setValue(
  1085. self.scrollBars[Qt.Horizontal].value() + x_shift)
  1086. self.scrollBars[Qt.Vertical].setValue(
  1087. self.scrollBars[Qt.Vertical].value() + y_shift)
  1088. def setFitWindow(self, value=True):
  1089. if value:
  1090. self.actions.fitWidth.setChecked(False)
  1091. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  1092. self.adjustScale()
  1093. def setFitWidth(self, value=True):
  1094. if value:
  1095. self.actions.fitWindow.setChecked(False)
  1096. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  1097. self.adjustScale()
  1098. def togglePolygons(self, value):
  1099. for item, shape in self.labelList.itemsToShapes:
  1100. item.setCheckState(Qt.Checked if value else Qt.Unchecked)
  1101. def loadFile(self, filename=None):
  1102. """Load the specified file, or the last opened file if None."""
  1103. # changing fileListWidget loads file
  1104. if (filename in self.imageList and
  1105. self.fileListWidget.currentRow() !=
  1106. self.imageList.index(filename)):
  1107. self.fileListWidget.setCurrentRow(self.imageList.index(filename))
  1108. self.fileListWidget.repaint()
  1109. return
  1110. self.resetState()
  1111. self.canvas.setEnabled(False)
  1112. if filename is None:
  1113. filename = self.settings.value('filename', '')
  1114. filename = str(filename)
  1115. if not QtCore.QFile.exists(filename):
  1116. self.errorMessage(
  1117. self.tr('Error opening file'),
  1118. self.tr('No such file: <b>%s</b>') % filename
  1119. )
  1120. return False
  1121. # assumes same name, but json extension
  1122. self.status(self.tr("Loading %s...") % osp.basename(str(filename)))
  1123. label_file = osp.splitext(filename)[0] + '.json'
  1124. if self.output_dir:
  1125. label_file_without_path = osp.basename(label_file)
  1126. label_file = osp.join(self.output_dir, label_file_without_path)
  1127. if QtCore.QFile.exists(label_file) and \
  1128. LabelFile.is_label_file(label_file):
  1129. try:
  1130. self.labelFile = LabelFile(label_file)
  1131. except LabelFileError as e:
  1132. self.errorMessage(
  1133. self.tr('Error opening file'),
  1134. self.tr(
  1135. "<p><b>%s</b></p>"
  1136. "<p>Make sure <i>%s</i> is a valid label file."
  1137. ) % (e, label_file)
  1138. )
  1139. self.status(self.tr("Error reading %s") % label_file)
  1140. return False
  1141. self.imageData = self.labelFile.imageData
  1142. self.imagePath = osp.join(
  1143. osp.dirname(label_file),
  1144. self.labelFile.imagePath,
  1145. )
  1146. if self.labelFile.lineColor is not None:
  1147. self.lineColor = QtGui.QColor(*self.labelFile.lineColor)
  1148. if self.labelFile.fillColor is not None:
  1149. self.fillColor = QtGui.QColor(*self.labelFile.fillColor)
  1150. self.otherData = self.labelFile.otherData
  1151. else:
  1152. self.imageData = LabelFile.load_image_file(filename)
  1153. if self.imageData:
  1154. self.imagePath = filename
  1155. self.labelFile = None
  1156. image = QtGui.QImage.fromData(self.imageData)
  1157. if image.isNull():
  1158. formats = ['*.{}'.format(fmt.data().decode())
  1159. for fmt in QtGui.QImageReader.supportedImageFormats()]
  1160. self.errorMessage(
  1161. self.tr('Error opening file'),
  1162. self.tr(
  1163. '<p>Make sure <i>{0}</i> is a valid image file.<br/>'
  1164. 'Supported image formats: {1}</p>'
  1165. ).format(filename, ','.join(formats))
  1166. )
  1167. self.status(self.tr("Error reading %s") % filename)
  1168. return False
  1169. self.image = image
  1170. self.filename = filename
  1171. if self._config['keep_prev']:
  1172. prev_shapes = self.canvas.shapes
  1173. self.canvas.loadPixmap(QtGui.QPixmap.fromImage(image))
  1174. if self._config['flags']:
  1175. self.loadFlags({k: False for k in self._config['flags']})
  1176. if self.labelFile:
  1177. self.loadLabels(self.labelFile.shapes)
  1178. if self.labelFile.flags is not None:
  1179. self.loadFlags(self.labelFile.flags)
  1180. if self._config['keep_prev'] and not self.labelList.shapes:
  1181. self.loadShapes(prev_shapes, replace=False)
  1182. self.setClean()
  1183. self.canvas.setEnabled(True)
  1184. self.adjustScale(initial=True)
  1185. self.paintCanvas()
  1186. self.addRecentFile(self.filename)
  1187. self.toggleActions(True)
  1188. self.status(self.tr("Loaded %s") % osp.basename(str(filename)))
  1189. return True
  1190. def resizeEvent(self, event):
  1191. if self.canvas and not self.image.isNull()\
  1192. and self.zoomMode != self.MANUAL_ZOOM:
  1193. self.adjustScale()
  1194. super(MainWindow, self).resizeEvent(event)
  1195. def paintCanvas(self):
  1196. assert not self.image.isNull(), "cannot paint null image"
  1197. self.canvas.scale = 0.01 * self.zoomWidget.value()
  1198. self.canvas.adjustSize()
  1199. self.canvas.update()
  1200. def adjustScale(self, initial=False):
  1201. value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
  1202. self.zoomWidget.setValue(int(100 * value))
  1203. def scaleFitWindow(self):
  1204. """Figure out the size of the pixmap to fit the main widget."""
  1205. e = 2.0 # So that no scrollbars are generated.
  1206. w1 = self.centralWidget().width() - e
  1207. h1 = self.centralWidget().height() - e
  1208. a1 = w1 / h1
  1209. # Calculate a new scale value based on the pixmap's aspect ratio.
  1210. w2 = self.canvas.pixmap.width() - 0.0
  1211. h2 = self.canvas.pixmap.height() - 0.0
  1212. a2 = w2 / h2
  1213. return w1 / w2 if a2 >= a1 else h1 / h2
  1214. def scaleFitWidth(self):
  1215. # The epsilon does not seem to work too well here.
  1216. w = self.centralWidget().width() - 2.0
  1217. return w / self.canvas.pixmap.width()
  1218. def enableSaveImageWithData(self, enabled):
  1219. self._config['store_data'] = enabled
  1220. self.actions.saveWithImageData.setChecked(enabled)
  1221. def closeEvent(self, event):
  1222. if not self.mayContinue():
  1223. event.ignore()
  1224. self.settings.setValue(
  1225. 'filename', self.filename if self.filename else '')
  1226. self.settings.setValue('window/size', self.size())
  1227. self.settings.setValue('window/position', self.pos())
  1228. self.settings.setValue('window/state', self.saveState())
  1229. self.settings.setValue('line/color', self.lineColor)
  1230. self.settings.setValue('fill/color', self.fillColor)
  1231. self.settings.setValue('recentFiles', self.recentFiles)
  1232. # ask the use for where to save the labels
  1233. # self.settings.setValue('window/geometry', self.saveGeometry())
  1234. # User Dialogs #
  1235. def loadRecent(self, filename):
  1236. if self.mayContinue():
  1237. self.loadFile(filename)
  1238. def openPrevImg(self, _value=False):
  1239. keep_prev = self._config['keep_prev']
  1240. if QtGui.QGuiApplication.keyboardModifiers() == \
  1241. (QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier):
  1242. self._config['keep_prev'] = True
  1243. if not self.mayContinue():
  1244. return
  1245. if len(self.imageList) <= 0:
  1246. return
  1247. if self.filename is None:
  1248. return
  1249. currIndex = self.imageList.index(self.filename)
  1250. if currIndex - 1 >= 0:
  1251. filename = self.imageList[currIndex - 1]
  1252. if filename:
  1253. self.loadFile(filename)
  1254. self._config['keep_prev'] = keep_prev
  1255. def openNextImg(self, _value=False, load=True):
  1256. keep_prev = self._config['keep_prev']
  1257. if QtGui.QGuiApplication.keyboardModifiers() == \
  1258. (QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier):
  1259. self._config['keep_prev'] = True
  1260. if not self.mayContinue():
  1261. return
  1262. if len(self.imageList) <= 0:
  1263. return
  1264. filename = None
  1265. if self.filename is None:
  1266. filename = self.imageList[0]
  1267. else:
  1268. currIndex = self.imageList.index(self.filename)
  1269. if currIndex + 1 < len(self.imageList):
  1270. filename = self.imageList[currIndex + 1]
  1271. else:
  1272. filename = self.imageList[-1]
  1273. self.filename = filename
  1274. if self.filename and load:
  1275. self.loadFile(self.filename)
  1276. self._config['keep_prev'] = keep_prev
  1277. def openFile(self, _value=False):
  1278. if not self.mayContinue():
  1279. return
  1280. path = osp.dirname(str(self.filename)) if self.filename else '.'
  1281. formats = ['*.{}'.format(fmt.data().decode())
  1282. for fmt in QtGui.QImageReader.supportedImageFormats()]
  1283. filters = self.tr("Image & Label files (%s)") % ' '.join(
  1284. formats + ['*%s' % LabelFile.suffix])
  1285. filename = QtWidgets.QFileDialog.getOpenFileName(
  1286. self, self.tr('%s - Choose Image or Label file') % __appname__,
  1287. path, filters)
  1288. if QT5:
  1289. filename, _ = filename
  1290. filename = str(filename)
  1291. if filename:
  1292. self.loadFile(filename)
  1293. def changeOutputDirDialog(self, _value=False):
  1294. default_output_dir = self.output_dir
  1295. if default_output_dir is None and self.filename:
  1296. default_output_dir = osp.dirname(self.filename)
  1297. if default_output_dir is None:
  1298. default_output_dir = self.currentPath()
  1299. output_dir = QtWidgets.QFileDialog.getExistingDirectory(
  1300. self,
  1301. self.tr('%s - Save/Load Annotations in Directory') % __appname__,
  1302. default_output_dir,
  1303. QtWidgets.QFileDialog.ShowDirsOnly |
  1304. QtWidgets.QFileDialog.DontResolveSymlinks,
  1305. )
  1306. output_dir = str(output_dir)
  1307. if not output_dir:
  1308. return
  1309. self.output_dir = output_dir
  1310. self.statusBar().showMessage(
  1311. self.tr('%s . Annotations will be saved/loaded in %s') %
  1312. ('Change Annotations Dir', self.output_dir))
  1313. self.statusBar().show()
  1314. current_filename = self.filename
  1315. self.importDirImages(self.lastOpenDir, load=False)
  1316. if current_filename in self.imageList:
  1317. # retain currently selected file
  1318. self.fileListWidget.setCurrentRow(
  1319. self.imageList.index(current_filename))
  1320. self.fileListWidget.repaint()
  1321. def saveFile(self, _value=False):
  1322. assert not self.image.isNull(), "cannot save empty image"
  1323. if self._config['flags'] or self.hasLabels():
  1324. if self.labelFile:
  1325. # DL20180323 - overwrite when in directory
  1326. self._saveFile(self.labelFile.filename)
  1327. elif self.output_file:
  1328. self._saveFile(self.output_file)
  1329. self.close()
  1330. else:
  1331. self._saveFile(self.saveFileDialog())
  1332. def saveFileAs(self, _value=False):
  1333. assert not self.image.isNull(), "cannot save empty image"
  1334. if self.hasLabels():
  1335. self._saveFile(self.saveFileDialog())
  1336. def saveFileDialog(self):
  1337. caption = self.tr('%s - Choose File') % __appname__
  1338. filters = self.tr('Label files (*%s)') % LabelFile.suffix
  1339. if self.output_dir:
  1340. dlg = QtWidgets.QFileDialog(
  1341. self, caption, self.output_dir, filters
  1342. )
  1343. else:
  1344. dlg = QtWidgets.QFileDialog(
  1345. self, caption, self.currentPath(), filters
  1346. )
  1347. dlg.setDefaultSuffix(LabelFile.suffix[1:])
  1348. dlg.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
  1349. dlg.setOption(QtWidgets.QFileDialog.DontConfirmOverwrite, False)
  1350. dlg.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, False)
  1351. basename = osp.basename(osp.splitext(self.filename)[0])
  1352. if self.output_dir:
  1353. default_labelfile_name = osp.join(
  1354. self.output_dir, basename + LabelFile.suffix
  1355. )
  1356. else:
  1357. default_labelfile_name = osp.join(
  1358. self.currentPath(), basename + LabelFile.suffix
  1359. )
  1360. filename = dlg.getSaveFileName(
  1361. self, self.tr('Choose File'), default_labelfile_name,
  1362. self.tr('Label files (*%s)') % LabelFile.suffix)
  1363. if QT5:
  1364. filename, _ = filename
  1365. filename = str(filename)
  1366. return filename
  1367. def _saveFile(self, filename):
  1368. if filename and self.saveLabels(filename):
  1369. self.addRecentFile(filename)
  1370. self.setClean()
  1371. def closeFile(self, _value=False):
  1372. if not self.mayContinue():
  1373. return
  1374. self.resetState()
  1375. self.setClean()
  1376. self.toggleActions(False)
  1377. self.canvas.setEnabled(False)
  1378. self.actions.saveAs.setEnabled(False)
  1379. def getLabelFile(self):
  1380. if self.filename.lower().endswith('.json'):
  1381. label_file = self.filename
  1382. else:
  1383. label_file = osp.splitext(self.filename)[0] + '.json'
  1384. return label_file
  1385. def deleteFile(self):
  1386. mb = QtWidgets.QMessageBox
  1387. msg = self.tr('You are about to permanently delete this label file, '
  1388. 'proceed anyway?')
  1389. answer = mb.warning(self, self.tr('Attention'), msg, mb.Yes | mb.No)
  1390. if answer != mb.Yes:
  1391. return
  1392. label_file = self.getLabelFile()
  1393. if osp.exists(label_file):
  1394. os.remove(label_file)
  1395. logger.info('Label file is removed: {}'.format(label_file))
  1396. item = self.fileListWidget.currentItem()
  1397. item.setCheckState(Qt.Unchecked)
  1398. self.resetState()
  1399. # Message Dialogs. #
  1400. def hasLabels(self):
  1401. if not self.labelList.itemsToShapes:
  1402. self.errorMessage(
  1403. 'No objects labeled',
  1404. 'You must label at least one object to save the file.')
  1405. return False
  1406. return True
  1407. def hasLabelFile(self):
  1408. if self.filename is None:
  1409. return False
  1410. label_file = self.getLabelFile()
  1411. return osp.exists(label_file)
  1412. def mayContinue(self):
  1413. if not self.dirty:
  1414. return True
  1415. mb = QtWidgets.QMessageBox
  1416. msg = self.tr('Save annotations to "{}" before closing?').format(
  1417. self.filename)
  1418. answer = mb.question(self,
  1419. self.tr('Save annotations?'),
  1420. msg,
  1421. mb.Save | mb.Discard | mb.Cancel,
  1422. mb.Save)
  1423. if answer == mb.Discard:
  1424. return True
  1425. elif answer == mb.Save:
  1426. self.saveFile()
  1427. return True
  1428. else: # answer == mb.Cancel
  1429. return False
  1430. def errorMessage(self, title, message):
  1431. return QtWidgets.QMessageBox.critical(
  1432. self, title, '<p><b>%s</b></p>%s' % (title, message))
  1433. def currentPath(self):
  1434. return osp.dirname(str(self.filename)) if self.filename else '.'
  1435. def chooseColor1(self):
  1436. color = self.colorDialog.getColor(
  1437. self.lineColor,
  1438. self.tr('Choose line color'),
  1439. default=DEFAULT_LINE_COLOR
  1440. )
  1441. if color:
  1442. self.lineColor = color
  1443. # Change the color for all shape lines:
  1444. Shape.line_color = self.lineColor
  1445. self.canvas.update()
  1446. self.setDirty()
  1447. def chooseColor2(self):
  1448. color = self.colorDialog.getColor(
  1449. self.fillColor,
  1450. self.tr('Choose fill color'),
  1451. default=DEFAULT_FILL_COLOR
  1452. )
  1453. if color:
  1454. self.fillColor = color
  1455. Shape.fill_color = self.fillColor
  1456. self.canvas.update()
  1457. self.setDirty()
  1458. def toggleKeepPrevMode(self):
  1459. self._config['keep_prev'] = not self._config['keep_prev']
  1460. def deleteSelectedShape(self):
  1461. yes, no = QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
  1462. msg = self.tr(
  1463. 'You are about to permanently delete {} polygons, '
  1464. 'proceed anyway?'
  1465. ).format(len(self.canvas.selectedShapes))
  1466. if yes == QtWidgets.QMessageBox.warning(
  1467. self, self.tr('Attention'), msg,
  1468. yes | no):
  1469. self.remLabels(self.canvas.deleteSelected())
  1470. self.setDirty()
  1471. if self.noShapes():
  1472. for action in self.actions.onShapesPresent:
  1473. action.setEnabled(False)
  1474. def chshapeLineColor(self):
  1475. color = self.colorDialog.getColor(
  1476. self.lineColor,
  1477. self.tr('Choose line color'),
  1478. default=DEFAULT_LINE_COLOR
  1479. )
  1480. if color:
  1481. for shape in self.canvas.selectedShapes:
  1482. shape.line_color = color
  1483. self.canvas.update()
  1484. self.setDirty()
  1485. def chshapeFillColor(self):
  1486. color = self.colorDialog.getColor(
  1487. self.fillColor,
  1488. self.tr('Choose fill color'),
  1489. default=DEFAULT_FILL_COLOR
  1490. )
  1491. if color:
  1492. for shape in self.canvas.selectedShapes:
  1493. shape.fill_color = color
  1494. self.canvas.update()
  1495. self.setDirty()
  1496. def copyShape(self):
  1497. self.canvas.endMove(copy=True)
  1498. self.labelList.clearSelection()
  1499. for shape in self.canvas.selectedShapes:
  1500. self.addLabel(shape)
  1501. self.setDirty()
  1502. def moveShape(self):
  1503. self.canvas.endMove(copy=False)
  1504. self.setDirty()
  1505. def openDirDialog(self, _value=False, dirpath=None):
  1506. if not self.mayContinue():
  1507. return
  1508. defaultOpenDirPath = dirpath if dirpath else '.'
  1509. if self.lastOpenDir and osp.exists(self.lastOpenDir):
  1510. defaultOpenDirPath = self.lastOpenDir
  1511. else:
  1512. defaultOpenDirPath = osp.dirname(self.filename) \
  1513. if self.filename else '.'
  1514. targetDirPath = str(QtWidgets.QFileDialog.getExistingDirectory(
  1515. self,
  1516. self.tr('%s - Open Directory') % __appname__,
  1517. defaultOpenDirPath,
  1518. QtWidgets.QFileDialog.ShowDirsOnly |
  1519. QtWidgets.QFileDialog.DontResolveSymlinks))
  1520. self.importDirImages(targetDirPath)
  1521. @property
  1522. def imageList(self):
  1523. lst = []
  1524. for i in range(self.fileListWidget.count()):
  1525. item = self.fileListWidget.item(i)
  1526. lst.append(item.text())
  1527. return lst
  1528. def importDirImages(self, dirpath, pattern=None, load=True):
  1529. self.actions.openNextImg.setEnabled(True)
  1530. self.actions.openPrevImg.setEnabled(True)
  1531. if not self.mayContinue() or not dirpath:
  1532. return
  1533. self.lastOpenDir = dirpath
  1534. self.filename = None
  1535. self.fileListWidget.clear()
  1536. for filename in self.scanAllImages(dirpath):
  1537. if pattern and pattern not in filename:
  1538. continue
  1539. label_file = osp.splitext(filename)[0] + '.json'
  1540. if self.output_dir:
  1541. label_file_without_path = osp.basename(label_file)
  1542. label_file = osp.join(self.output_dir, label_file_without_path)
  1543. item = QtWidgets.QListWidgetItem(filename)
  1544. item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
  1545. if QtCore.QFile.exists(label_file) and \
  1546. LabelFile.is_label_file(label_file):
  1547. item.setCheckState(Qt.Checked)
  1548. else:
  1549. item.setCheckState(Qt.Unchecked)
  1550. self.fileListWidget.addItem(item)
  1551. self.openNextImg(load=load)
  1552. def scanAllImages(self, folderPath):
  1553. extensions = ['.%s' % fmt.data().decode("ascii").lower()
  1554. for fmt in QtGui.QImageReader.supportedImageFormats()]
  1555. images = []
  1556. for root, dirs, files in os.walk(folderPath):
  1557. for file in files:
  1558. if file.lower().endswith(tuple(extensions)):
  1559. relativePath = osp.join(root, file)
  1560. images.append(relativePath)
  1561. images.sort(key=lambda x: x.lower())
  1562. return images