x2imagenet.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import cv2
  17. import json
  18. import os
  19. import os.path as osp
  20. import shutil
  21. import numpy as np
  22. from .base import MyEncoder, is_pic, get_encoding
  23. class EasyData2ImageNet(object):
  24. """将使用EasyData标注的分类数据集转换为COCO数据集。
  25. """
  26. def __init__(self):
  27. pass
  28. def convert(self, image_dir, json_dir, dataset_save_dir):
  29. """转换。
  30. Args:
  31. image_dir (str): 图像文件存放的路径。
  32. json_dir (str): 与每张图像对应的json文件的存放路径。
  33. dataset_save_dir (str): 转换后数据集存放路径。
  34. """
  35. assert osp.exists(image_dir), "The image folder does not exist!"
  36. assert osp.exists(json_dir), "The json folder does not exist!"
  37. assert osp.exists(dataset_save_dir), "The save folder does not exist!"
  38. assert len(os.listdir(dataset_save_dir)) == 0, "The save folder must be empty!"
  39. for img_name in os.listdir(image_dir):
  40. img_name_part = osp.splitext(img_name)[0]
  41. json_file = osp.join(json_dir, img_name_part + ".json")
  42. if not osp.exists(json_file):
  43. continue
  44. with open(json_file, mode="r", \
  45. encoding=get_encoding(json_file)) as j:
  46. json_info = json.load(j)
  47. for output in json_info['labels']:
  48. cls_name = output['name']
  49. new_image_dir = osp.join(dataset_save_dir, cls_name)
  50. if not osp.exists(new_image_dir):
  51. os.makedirs(new_image_dir)
  52. if is_pic(img_name):
  53. shutil.copyfile(
  54. osp.join(image_dir, img_name),
  55. osp.join(new_image_dir, img_name))