label_file.py 5.7 KB

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