labelFile.py 2.5 KB

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