labelFile.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import json
  2. import os.path
  3. from base64 import b64encode, b64decode
  4. class LabelFileError(Exception):
  5. pass
  6. class LabelFile(object):
  7. suffix = '.lif'
  8. def __init__(self, filename=None):
  9. self.shapes = ()
  10. self.imagePath = None
  11. self.imageData = None
  12. if filename is not None:
  13. self.load(filename)
  14. def load(self, filename):
  15. try:
  16. with open(filename, 'rb') as f:
  17. data = json.load(f)
  18. imagePath = data['imagePath']
  19. imageData = b64decode(data['imageData'])
  20. shapes = ((s['label'], s['points']) for s in data['shapes'])
  21. # Only replace data after everything is loaded.
  22. self.shapes = shapes
  23. self.imagePath = imagePath
  24. self.imageData = imageData
  25. except Exception, e:
  26. raise LabelFileError(e)
  27. def save(self, filename, shapes, imagePath, imageData):
  28. try:
  29. with open(filename, 'wb') as f:
  30. json.dump(dict(
  31. shapes=[dict(label=l, points=p) for (l, p) in shapes],
  32. imagePath=imagePath,
  33. imageData=b64encode(imageData)),
  34. f, ensure_ascii=True, indent=2)
  35. except Exception, e:
  36. raise LabelFileError(e)
  37. @staticmethod
  38. def isLabelFile(filename):
  39. return os.path.splitext(filename)[1].lower() == LabelFile.suffix