imagenet_split.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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 os.path as osp
  15. import random
  16. from .utils import list_files, is_pic
  17. def split_imagenet_dataset(dataset_dir, val_percent, test_percent, save_dir):
  18. all_files = list_files(dataset_dir)
  19. label_list = list()
  20. train_image_anno_list = list()
  21. val_image_anno_list = list()
  22. test_image_anno_list = list()
  23. for file in all_files:
  24. if not is_pic(file):
  25. continue
  26. label, image_name = osp.split(file)
  27. if label not in label_list:
  28. label_list.append(label)
  29. label_list = sorted(label_list)
  30. for i in range(len(label_list)):
  31. image_list = list_files(osp.join(dataset_dir, label_list[i]))
  32. image_anno_list = list()
  33. for img in image_list:
  34. image_anno_list.append([osp.join(label_list[i], img), i])
  35. random.shuffle(image_anno_list)
  36. image_num = len(image_anno_list)
  37. val_num = int(image_num * val_percent)
  38. test_num = int(image_num * test_percent)
  39. train_num = image_num - val_num - test_num
  40. train_image_anno_list += image_anno_list[:train_num]
  41. val_image_anno_list += image_anno_list[train_num:train_num + val_num]
  42. test_image_anno_list += image_anno_list[train_num + val_num:]
  43. with open(
  44. osp.join(save_dir, 'train_list.txt'), mode='w',
  45. encoding='utf-8') as f:
  46. for x in train_image_anno_list:
  47. file, label = x
  48. f.write('{} {}\n'.format(file, label))
  49. with open(
  50. osp.join(save_dir, 'val_list.txt'), mode='w',
  51. encoding='utf-8') as f:
  52. for x in val_image_anno_list:
  53. file, label = x
  54. f.write('{} {}\n'.format(file, label))
  55. if len(test_image_anno_list):
  56. with open(
  57. osp.join(save_dir, 'test_list.txt'), mode='w',
  58. encoding='utf-8') as f:
  59. for x in test_image_anno_list:
  60. file, label = x
  61. f.write('{} {}\n'.format(file, label))
  62. with open(
  63. osp.join(save_dir, 'labels.txt'), mode='w', encoding='utf-8') as f:
  64. for l in sorted(label_list):
  65. f.write('{}\n'.format(l))
  66. return len(train_image_anno_list), len(val_image_anno_list), len(
  67. test_image_anno_list)