label_file.py 6.2 KB

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