labelFile.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. lineColor = data['lineColor']
  21. fillColor = data['fillColor']
  22. shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
  23. for s in data['shapes'])
  24. # Only replace data after everything is loaded.
  25. self.shapes = shapes
  26. self.imagePath = imagePath
  27. self.imageData = imageData
  28. self.lineColor = lineColor
  29. self.fillColor = fillColor
  30. except Exception, e:
  31. raise LabelFileError(e)
  32. def save(self, filename, shapes, imagePath, imageData,
  33. lineColor=None, fillColor=None):
  34. try:
  35. with open(filename, 'wb') as f:
  36. json.dump(dict(
  37. shapes=shapes,
  38. lineColor=lineColor, fillColor=fillColor,
  39. imagePath=imagePath,
  40. imageData=b64encode(imageData)),
  41. f, ensure_ascii=True, indent=2)
  42. except Exception, e:
  43. raise LabelFileError(e)
  44. @staticmethod
  45. def isLabelFile(filename):
  46. return os.path.splitext(filename)[1].lower() == LabelFile.suffix