labelFile.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. from base64 import b64encode, b64decode
  20. import json
  21. import os.path
  22. import six
  23. class LabelFileError(Exception):
  24. pass
  25. class LabelFile(object):
  26. suffix = '.json'
  27. def __init__(self, filename=None):
  28. self.shapes = ()
  29. self.imagePath = None
  30. self.imageData = None
  31. if filename is not None:
  32. self.load(filename)
  33. def load(self, filename):
  34. try:
  35. with open(filename, 'rb' if six.PY2 else 'r') as f:
  36. data = json.load(f)
  37. imagePath = data['imagePath']
  38. imageData = b64decode(data['imageData'])
  39. lineColor = data['lineColor']
  40. fillColor = data['fillColor']
  41. shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
  42. for s in data['shapes'])
  43. # Only replace data after everything is loaded.
  44. self.shapes = shapes
  45. self.imagePath = imagePath
  46. self.imageData = imageData
  47. self.lineColor = lineColor
  48. self.fillColor = fillColor
  49. except Exception as e:
  50. raise LabelFileError(e)
  51. def save(self, filename, shapes, imagePath, imageData,
  52. lineColor=None, fillColor=None):
  53. data = dict(
  54. shapes=shapes,
  55. lineColor=lineColor,
  56. fillColor=fillColor,
  57. imagePath=imagePath,
  58. imageData=b64encode(imageData).decode('utf-8'),
  59. )
  60. try:
  61. with open(filename, 'wb' if six.PY2 else 'w') as f:
  62. json.dump(data, f, ensure_ascii=True, indent=2)
  63. except Exception as e:
  64. raise LabelFileError(e)
  65. @staticmethod
  66. def isLabelFile(filename):
  67. return os.path.splitext(filename)[1].lower() == LabelFile.suffix