label_file.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. (
  43. s['label'],
  44. s['points'],
  45. s['line_color'],
  46. s['fill_color'],
  47. s.get('shape_type'),
  48. )
  49. for s in data['shapes']
  50. )
  51. except Exception as e:
  52. raise LabelFileError(e)
  53. otherData = {}
  54. for key, value in data.items():
  55. if key not in keys:
  56. otherData[key] = value
  57. # Only replace data after everything is loaded.
  58. self.flags = flags
  59. self.shapes = shapes
  60. self.imagePath = imagePath
  61. self.imageData = imageData
  62. self.lineColor = lineColor
  63. self.fillColor = fillColor
  64. self.filename = filename
  65. self.otherData = otherData
  66. def save(self, filename, shapes, imagePath, imageData=None,
  67. lineColor=None, fillColor=None, otherData=None,
  68. flags=None):
  69. if imageData is not None:
  70. imageData = base64.b64encode(imageData).decode('utf-8')
  71. if otherData is None:
  72. otherData = {}
  73. if flags is None:
  74. flags = []
  75. data = dict(
  76. flags=flags,
  77. shapes=shapes,
  78. lineColor=lineColor,
  79. fillColor=fillColor,
  80. imagePath=imagePath,
  81. imageData=imageData,
  82. )
  83. for key, value in otherData.items():
  84. data[key] = value
  85. try:
  86. with open(filename, 'wb' if PY2 else 'w') as f:
  87. json.dump(data, f, ensure_ascii=False, indent=2)
  88. self.filename = filename
  89. except Exception as e:
  90. raise LabelFileError(e)
  91. @staticmethod
  92. def isLabelFile(filename):
  93. return os.path.splitext(filename)[1].lower() == LabelFile.suffix