check_dataset.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. import os.path as osp
  17. from collections import Counter, defaultdict
  18. from pathlib import Path
  19. from PIL import Image, ImageOps
  20. from .....utils.deps import function_requires_deps
  21. from .....utils.errors import DatasetFileNotFoundError
  22. from .....utils.logging import info
  23. from .utils.visualizer import draw_bbox, draw_mask
  24. @function_requires_deps("pycocotools")
  25. def check(dataset_dir, output, sample_num=10):
  26. """check dataset"""
  27. from pycocotools.coco import COCO
  28. info(dataset_dir)
  29. dataset_dir = osp.abspath(dataset_dir)
  30. if not osp.exists(dataset_dir) or not osp.isdir(dataset_dir):
  31. raise DatasetFileNotFoundError(file_path=dataset_dir)
  32. sample_cnts = dict()
  33. sample_paths = defaultdict(list)
  34. defaultdict(Counter)
  35. tags = ["instance_train", "instance_val"]
  36. for _, tag in enumerate(tags):
  37. file_list = osp.join(dataset_dir, f"annotations/{tag}.json")
  38. if not osp.exists(file_list):
  39. if tag in ("instance_train", "instance_val"):
  40. # train and val file lists must exist
  41. raise DatasetFileNotFoundError(
  42. file_path=file_list,
  43. solution=f"Ensure that both `instance_train.json` and `instance_val.json` exist in \
  44. {dataset_dir}/annotations",
  45. )
  46. else:
  47. continue
  48. else:
  49. with open(file_list, "r", encoding="utf-8") as f:
  50. jsondata = json.load(f)
  51. datanno = jsondata["annotations"]
  52. sample_cnts[tag] = len(datanno)
  53. coco = COCO(file_list)
  54. num_class = len(coco.getCatIds())
  55. vis_save_dir = osp.join(output, "demo_img")
  56. image_info = jsondata["images"]
  57. sample_num = min(sample_num, len(image_info))
  58. if sample_num < 10:
  59. info("Only {} images in {}.json".format(len(image_info), tag))
  60. for i in range(sample_num):
  61. file_name = image_info[i]["file_name"]
  62. img_id = image_info[i]["id"]
  63. img_path = osp.join(dataset_dir, "images", file_name)
  64. if not osp.exists(img_path):
  65. raise DatasetFileNotFoundError(file_path=img_path)
  66. img = Image.open(img_path)
  67. img = ImageOps.exif_transpose(img)
  68. vis_im = draw_bbox(img, coco, img_id)
  69. vis_im = draw_mask(vis_im, coco, img_id)
  70. vis_path = osp.join(vis_save_dir, file_name)
  71. Path(vis_path).parent.mkdir(parents=True, exist_ok=True)
  72. vis_im.save(vis_path)
  73. sample_path = osp.join(
  74. "check_dataset", os.path.relpath(vis_path, output)
  75. )
  76. sample_paths[tag].append(sample_path)
  77. attrs = {}
  78. attrs["num_classes"] = num_class
  79. attrs["train_samples"] = sample_cnts["instance_train"]
  80. attrs["train_sample_paths"] = sample_paths["instance_train"]
  81. attrs["val_samples"] = sample_cnts["instance_val"]
  82. attrs["val_sample_paths"] = sample_paths["instance_val"]
  83. return attrs