labelFile.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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):
  9. self.shapes = ()
  10. self.imagePath = None
  11. self.imageData = None
  12. def load(self, filename):
  13. try:
  14. with open(filename, 'rb') as f:
  15. data = json.load(f)
  16. imagePath = data['imagePath']
  17. imageData = b64decode(data['imageData'])
  18. shapes = ((s['label'], s['points']) for s in data['shapes'])
  19. # Only replace data after everything is loaded.
  20. self.shapes = shapes
  21. self.imagePath = imagePath
  22. self.imageData = imageData
  23. except Exception, e:
  24. raise LabelFileError(e)
  25. def save(self, filename, shapes, imagePath, imageData):
  26. try:
  27. with open(filename, 'wb') as f:
  28. json.dump(dict(
  29. shapes=[dict(label=l, points=p) for (l, p) in shapes],
  30. imagePath=imagePath,
  31. imageData=b64encode(imageData)),
  32. f, ensure_ascii=True, indent=2)
  33. except Exception, e:
  34. raise LabelFileError(e)
  35. @staticmethod
  36. def isLabelFile(filename):
  37. return os.path.splitext(filename)[1].lower() == LabelFile.suffix