labelFile.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  3. #
  4. # This file is part of Labelme.
  5. #
  6. # Labelme is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Labelme is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import json
  20. import os.path
  21. from base64 import b64encode, b64decode
  22. class LabelFileError(Exception):
  23. pass
  24. class LabelFile(object):
  25. suffix = '.json'
  26. def __init__(self, filename=None):
  27. self.shapes = ()
  28. self.imagePath = None
  29. self.imageData = None
  30. if filename is not None:
  31. self.load(filename)
  32. def load(self, filename):
  33. try:
  34. with open(filename, 'rb') as f:
  35. data = json.load(f)
  36. imagePath = data['imagePath']
  37. imageData = b64decode(data['imageData'])
  38. lineColor = data['lineColor']
  39. fillColor = data['fillColor']
  40. shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
  41. for s in data['shapes'])
  42. # Only replace data after everything is loaded.
  43. self.shapes = shapes
  44. self.imagePath = imagePath
  45. self.imageData = imageData
  46. self.lineColor = lineColor
  47. self.fillColor = fillColor
  48. except Exception as e:
  49. raise LabelFileError(e)
  50. def save(self, filename, shapes, imagePath, imageData,
  51. lineColor=None, fillColor=None):
  52. try:
  53. with open(filename, 'wb') as f:
  54. json.dump(dict(
  55. shapes=shapes,
  56. lineColor=lineColor, fillColor=fillColor,
  57. imagePath=imagePath,
  58. imageData=b64encode(imageData)),
  59. f, ensure_ascii=True, indent=2)
  60. except Exception as e:
  61. raise LabelFileError(e)
  62. @staticmethod
  63. def isLabelFile(filename):
  64. return os.path.splitext(filename)[1].lower() == LabelFile.suffix