x2imagenet.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 X2ImageNet(object):
  24. def __init__(self):
  25. pass
  26. def convert(self, image_dir, json_dir, dataset_save_dir):
  27. """转换。
  28. Args:
  29. image_dir (str): 图像文件存放的路径。
  30. json_dir (str): 与每张图像对应的json文件的存放路径。
  31. dataset_save_dir (str): 转换后数据集存放路径。
  32. """
  33. assert osp.exists(image_dir), "The image folder does not exist!"
  34. assert osp.exists(json_dir), "The json folder does not exist!"
  35. if not osp.exists(dataset_save_dir):
  36. os.makedirs(dataset_save_dir)
  37. assert len(os.listdir(dataset_save_dir)) == 0, "The save folder must be empty!"
  38. for img_name in os.listdir(image_dir):
  39. img_name_part = osp.splitext(img_name)[0]
  40. json_file = osp.join(json_dir, img_name_part + ".json")
  41. if not osp.exists(json_file):
  42. continue
  43. with open(json_file, mode="r", \
  44. encoding=get_encoding(json_file)) as j:
  45. json_info = self.get_json_info(j)
  46. for output in json_info:
  47. cls_name = output['name']
  48. new_image_dir = osp.join(dataset_save_dir, cls_name)
  49. if not osp.exists(new_image_dir):
  50. os.makedirs(new_image_dir)
  51. if is_pic(img_name):
  52. shutil.copyfile(
  53. osp.join(image_dir, img_name),
  54. osp.join(new_image_dir, img_name))
  55. class EasyData2ImageNet(X2ImageNet):
  56. """将使用EasyData标注的分类数据集转换为ImageNet数据集。
  57. """
  58. def __init__(self):
  59. super(EasyData2ImageNet, self).__init__()
  60. def get_json_info(self, json_file):
  61. json_info = json.load(json_file)
  62. json_info = json_info['labels']
  63. return json_info
  64. class JingLing2ImageNet(X2ImageNet):
  65. """将使用标注精灵标注的分类数据集转换为ImageNet数据集。
  66. """
  67. def __init__(self):
  68. super(X2ImageNet, self).__init__()
  69. def get_json_info(self, json_file):
  70. json_info = json.load(json_file)
  71. json_info = json_info['outputs']['object']
  72. return json_info