labelFile.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import base64
  2. import json
  3. import os.path
  4. import sys
  5. PY2 = sys.version_info[0] == 2
  6. class LabelFileError(Exception):
  7. pass
  8. class LabelFile(object):
  9. suffix = '.json'
  10. def __init__(self, filename=None):
  11. self.shapes = ()
  12. self.imagePath = None
  13. self.imageData = None
  14. if filename is not None:
  15. self.load(filename)
  16. self.filename = filename
  17. def load(self, filename):
  18. keys = [
  19. 'imageData',
  20. 'imagePath',
  21. 'lineColor',
  22. 'fillColor',
  23. 'shapes', # polygonal annotations
  24. 'flags', # image level flags
  25. ]
  26. try:
  27. with open(filename, 'rb' if PY2 else 'r') as f:
  28. data = json.load(f)
  29. if data['imageData'] is not None:
  30. imageData = base64.b64decode(data['imageData'])
  31. else:
  32. # relative path from label file to relative path from cwd
  33. imagePath = os.path.join(os.path.dirname(filename),
  34. data['imagePath'])
  35. with open(imagePath, 'rb') as f:
  36. imageData = f.read()
  37. flags = data.get('flags')
  38. imagePath = data['imagePath']
  39. lineColor = data['lineColor']
  40. fillColor = data['fillColor']
  41. shapes = (
  42. (s['label'], s['points'], s['line_color'], s['fill_color'])
  43. for s in data['shapes']
  44. )
  45. except Exception as e:
  46. raise LabelFileError(e)
  47. otherData = {}
  48. for key, value in data.items():
  49. if key not in keys:
  50. otherData[key] = value
  51. # Only replace data after everything is loaded.
  52. self.flags = flags
  53. self.shapes = shapes
  54. self.imagePath = imagePath
  55. self.imageData = imageData
  56. self.lineColor = lineColor
  57. self.fillColor = fillColor
  58. self.filename = filename
  59. self.otherData = otherData
  60. def save(self, filename, shapes, imagePath, imageData=None,
  61. lineColor=None, fillColor=None, otherData=None,
  62. flags=None):
  63. if imageData is not None:
  64. imageData = base64.b64encode(imageData).decode('utf-8')
  65. if otherData is None:
  66. otherData = {}
  67. if flags is None:
  68. flags = []
  69. data = dict(
  70. flags=flags,
  71. shapes=shapes,
  72. lineColor=lineColor,
  73. fillColor=fillColor,
  74. imagePath=imagePath,
  75. imageData=imageData,
  76. )
  77. for key, value in otherData.items():
  78. data[key] = value
  79. try:
  80. with open(filename, 'wb' if PY2 else 'w') as f:
  81. json.dump(data, f, ensure_ascii=False, indent=2)
  82. self.filename = filename
  83. except Exception as e:
  84. raise LabelFileError(e)
  85. @staticmethod
  86. def isLabelFile(filename):
  87. return os.path.splitext(filename)[1].lower() == LabelFile.suffix