labelFile.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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') as f:
  36. data = json.load(f)
  37. imagePath = data['imagePath']
  38. if six.PY3:
  39. imageData = b64decode(data['imageData']).decode('utf-8')
  40. elif six.PY2:
  41. imageData = b64decode(data['imageData'])
  42. else:
  43. raise RuntimeError('Unsupported Python version.')
  44. lineColor = data['lineColor']
  45. fillColor = data['fillColor']
  46. shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
  47. for s in data['shapes'])
  48. # Only replace data after everything is loaded.
  49. self.shapes = shapes
  50. self.imagePath = imagePath
  51. self.imageData = imageData
  52. self.lineColor = lineColor
  53. self.fillColor = fillColor
  54. except Exception as e:
  55. raise LabelFileError(e)
  56. def save(self, filename, shapes, imagePath, imageData,
  57. lineColor=None, fillColor=None):
  58. try:
  59. with open(filename, 'wb') as f:
  60. if six.PY3:
  61. imageData = b64encode(imageData.encode('utf-8'))
  62. elif six.PY2:
  63. imageData = b64encode(imageData)
  64. else:
  65. raise RuntimeError('Unsupported Python version.')
  66. json.dump(dict(
  67. shapes=shapes,
  68. lineColor=lineColor, fillColor=fillColor,
  69. imagePath=imagePath,
  70. imageData=imageData),
  71. f, ensure_ascii=True, indent=2)
  72. except Exception as e:
  73. raise LabelFileError(e)
  74. @staticmethod
  75. def isLabelFile(filename):
  76. return os.path.splitext(filename)[1].lower() == LabelFile.suffix