labelFile.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. if data['imageData'] is not None:
  39. imageData = b64decode(data['imageData'])
  40. else:
  41. # relative path from label file to relative path from cwd
  42. imagePath = os.path.join(os.path.dirname(filename),
  43. data['imagePath'])
  44. with open(imagePath, 'rb') as f:
  45. imageData = f.read()
  46. lineColor = data['lineColor']
  47. fillColor = data['fillColor']
  48. shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
  49. for s in data['shapes'])
  50. # Only replace data after everything is loaded.
  51. self.shapes = shapes
  52. self.imagePath = data['imagePath']
  53. self.imageData = imageData
  54. self.lineColor = lineColor
  55. self.fillColor = fillColor
  56. except Exception as e:
  57. raise LabelFileError(e)
  58. def save(self, filename, shapes, imagePath, imageData=None,
  59. lineColor=None, fillColor=None):
  60. if imageData is not None:
  61. imageData = b64encode(imageData).decode('utf-8')
  62. data = dict(
  63. shapes=shapes,
  64. lineColor=lineColor,
  65. fillColor=fillColor,
  66. imagePath=imagePath,
  67. imageData=imageData,
  68. )
  69. try:
  70. with open(filename, 'wb' if PY2 else 'w') as f:
  71. json.dump(data, 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