label_file.py 5.4 KB

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