label_file.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import base64
  2. import io
  3. import json
  4. import os.path
  5. import PIL.Image
  6. from labelme._version import __version__
  7. from labelme.logger import logger
  8. from labelme import PY2
  9. from labelme import utils
  10. class LabelFileError(Exception):
  11. pass
  12. class LabelFile(object):
  13. suffix = '.json'
  14. def __init__(self, filename=None):
  15. self.shapes = ()
  16. self.imagePath = None
  17. self.imageData = None
  18. if filename is not None:
  19. self.load(filename)
  20. self.filename = filename
  21. @staticmethod
  22. def load_image_file(filename):
  23. try:
  24. image_pil = PIL.Image.open(filename)
  25. except IOError:
  26. return
  27. # apply orientation to image according to exif
  28. image_pil = utils.apply_exif_orientation(image_pil)
  29. with io.BytesIO() as f:
  30. image_pil.save(f, format='PNG')
  31. f.seek(0)
  32. return f.read()
  33. def load(self, filename):
  34. keys = [
  35. 'imageData',
  36. 'imagePath',
  37. 'lineColor',
  38. 'fillColor',
  39. 'shapes', # polygonal annotations
  40. 'flags', # image level flags
  41. 'imageHeight',
  42. 'imageWidth',
  43. ]
  44. try:
  45. with open(filename, 'rb' if PY2 else 'r') as f:
  46. data = json.load(f)
  47. if data['imageData'] is not None:
  48. imageData = base64.b64decode(data['imageData'])
  49. else:
  50. # relative path from label file to relative path from cwd
  51. imagePath = os.path.join(
  52. os.path.dirname(filename), data['imagePath']
  53. )
  54. imageData = self.load_image_file(imagePath)
  55. flags = data.get('flags')
  56. imagePath = data['imagePath']
  57. self._check_image_height_and_width(
  58. base64.b64encode(imageData).decode('utf-8'),
  59. data.get('imageHeight'),
  60. data.get('imageWidth'),
  61. )
  62. lineColor = data['lineColor']
  63. fillColor = data['fillColor']
  64. shapes = (
  65. (
  66. s['label'],
  67. s['points'],
  68. s['line_color'],
  69. s['fill_color'],
  70. s.get('shape_type', 'polygon'),
  71. )
  72. for s in data['shapes']
  73. )
  74. except Exception as e:
  75. raise LabelFileError(e)
  76. otherData = {}
  77. for key, value in data.items():
  78. if key not in keys:
  79. otherData[key] = value
  80. # Only replace data after everything is loaded.
  81. self.flags = flags
  82. self.shapes = shapes
  83. self.imagePath = imagePath
  84. self.imageData = imageData
  85. self.lineColor = lineColor
  86. self.fillColor = fillColor
  87. self.filename = filename
  88. self.otherData = otherData
  89. @staticmethod
  90. def _check_image_height_and_width(imageData, imageHeight, imageWidth):
  91. img_arr = utils.img_b64_to_arr(imageData)
  92. if imageHeight is not None and img_arr.shape[0] != imageHeight:
  93. logger.error(
  94. 'imageHeight does not match with imageData or imagePath, '
  95. 'so getting imageHeight from actual image.'
  96. )
  97. imageHeight = img_arr.shape[0]
  98. if imageWidth is not None and img_arr.shape[1] != imageWidth:
  99. logger.error(
  100. 'imageWidth does not match with imageData or imagePath, '
  101. 'so getting imageWidth from actual image.'
  102. )
  103. imageWidth = img_arr.shape[1]
  104. return imageHeight, imageWidth
  105. def save(
  106. self,
  107. filename,
  108. shapes,
  109. imagePath,
  110. imageHeight,
  111. imageWidth,
  112. imageData=None,
  113. lineColor=None,
  114. fillColor=None,
  115. otherData=None,
  116. flags=None,
  117. ):
  118. if imageData is not None:
  119. imageData = base64.b64encode(imageData).decode('utf-8')
  120. imageHeight, imageWidth = self._check_image_height_and_width(
  121. imageData, imageHeight, imageWidth
  122. )
  123. if otherData is None:
  124. otherData = {}
  125. if flags is None:
  126. flags = {}
  127. data = dict(
  128. version=__version__,
  129. flags=flags,
  130. shapes=shapes,
  131. lineColor=lineColor,
  132. fillColor=fillColor,
  133. imagePath=imagePath,
  134. imageData=imageData,
  135. imageHeight=imageHeight,
  136. imageWidth=imageWidth,
  137. )
  138. for key, value in otherData.items():
  139. data[key] = value
  140. try:
  141. with open(filename, 'wb' if PY2 else 'w') as f:
  142. json.dump(data, f, ensure_ascii=False, indent=2)
  143. self.filename = filename
  144. except Exception as e:
  145. raise LabelFileError(e)
  146. @staticmethod
  147. def is_label_file(filename):
  148. return os.path.splitext(filename)[1].lower() == LabelFile.suffix