label_file.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import base64
  2. import io
  3. import json
  4. import os.path as osp
  5. import PIL.Image
  6. from labelme 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. 'version',
  46. 'imageData',
  47. 'imagePath',
  48. 'lineColor',
  49. 'fillColor',
  50. 'shapes', # polygonal annotations
  51. 'flags', # image level flags
  52. 'imageHeight',
  53. 'imageWidth',
  54. ]
  55. try:
  56. with open(filename, 'rb' if PY2 else 'r') as f:
  57. data = json.load(f)
  58. if data['imageData'] is not None:
  59. imageData = base64.b64decode(data['imageData'])
  60. if PY2 and QT4:
  61. imageData = utils.img_data_to_png_data(imageData)
  62. else:
  63. # relative path from label file to relative path from cwd
  64. imagePath = osp.join(osp.dirname(filename), data['imagePath'])
  65. imageData = self.load_image_file(imagePath)
  66. flags = data.get('flags') or {}
  67. imagePath = data['imagePath']
  68. self._check_image_height_and_width(
  69. base64.b64encode(imageData).decode('utf-8'),
  70. data.get('imageHeight'),
  71. data.get('imageWidth'),
  72. )
  73. lineColor = data['lineColor']
  74. fillColor = data['fillColor']
  75. shapes = [
  76. dict(
  77. label=s['label'],
  78. points=s['points'],
  79. line_color=s['line_color'],
  80. fill_color=s['fill_color'],
  81. shape_type=s.get('shape_type', 'polygon'),
  82. flags=s.get('flags', {}),
  83. )
  84. for s in data['shapes']
  85. ]
  86. except Exception as e:
  87. raise LabelFileError(e)
  88. otherData = {}
  89. for key, value in data.items():
  90. if key not in keys:
  91. otherData[key] = value
  92. # Only replace data after everything is loaded.
  93. self.flags = flags
  94. self.shapes = shapes
  95. self.imagePath = imagePath
  96. self.imageData = imageData
  97. self.lineColor = lineColor
  98. self.fillColor = fillColor
  99. self.filename = filename
  100. self.otherData = otherData
  101. @staticmethod
  102. def _check_image_height_and_width(imageData, imageHeight, imageWidth):
  103. img_arr = utils.img_b64_to_arr(imageData)
  104. if imageHeight is not None and img_arr.shape[0] != imageHeight:
  105. logger.error(
  106. 'imageHeight does not match with imageData or imagePath, '
  107. 'so getting imageHeight from actual image.'
  108. )
  109. imageHeight = img_arr.shape[0]
  110. if imageWidth is not None and img_arr.shape[1] != imageWidth:
  111. logger.error(
  112. 'imageWidth does not match with imageData or imagePath, '
  113. 'so getting imageWidth from actual image.'
  114. )
  115. imageWidth = img_arr.shape[1]
  116. return imageHeight, imageWidth
  117. def save(
  118. self,
  119. filename,
  120. shapes,
  121. imagePath,
  122. imageHeight,
  123. imageWidth,
  124. imageData=None,
  125. lineColor=None,
  126. fillColor=None,
  127. otherData=None,
  128. flags=None,
  129. ):
  130. if imageData is not None:
  131. imageData = base64.b64encode(imageData).decode('utf-8')
  132. imageHeight, imageWidth = self._check_image_height_and_width(
  133. imageData, imageHeight, imageWidth
  134. )
  135. if otherData is None:
  136. otherData = {}
  137. if flags is None:
  138. flags = {}
  139. data = dict(
  140. version=__version__,
  141. flags=flags,
  142. shapes=shapes,
  143. lineColor=lineColor,
  144. fillColor=fillColor,
  145. imagePath=imagePath,
  146. imageData=imageData,
  147. imageHeight=imageHeight,
  148. imageWidth=imageWidth,
  149. )
  150. for key, value in otherData.items():
  151. assert key not in data
  152. data[key] = value
  153. try:
  154. with open(filename, 'wb' if PY2 else 'w') as f:
  155. json.dump(data, f, ensure_ascii=False, indent=2)
  156. self.filename = filename
  157. except Exception as e:
  158. raise LabelFileError(e)
  159. @staticmethod
  160. def is_label_file(filename):
  161. return osp.splitext(filename)[1].lower() == LabelFile.suffix