label_file.py 5.3 KB

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