ego_to_json_5.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. def split_train_val():
  2. tmp_dir = os.path.join(ROOT_DIR, "tmp")
  3. os.makedirs(os.path.join(ROOT_DIR, "train"))
  4. train_dir = os.path.join(ROOT_DIR, "train")
  5. os.makedirs(os.path.join(train_dir, "images"))
  6. os.makedirs(os.path.join(ROOT_DIR, "val"))
  7. val_dir = os.path.join(ROOT_DIR, "val")
  8. os.makedirs(os.path.join(val_dir, "images"))
  9. # Opening JSON file
  10. with open(os.path.join(tmp_dir, 'annotations.json')) as json_file:
  11. data = json.load(json_file)
  12. # 0.1765 is 15% van 100% omdat test al 20 % is (niet helemaal)
  13. val_keys = random.sample(list(data), round(len(data) * 0.1765))
  14. validation = {k: v for k, v in data.items() if k in val_keys}
  15. train = {k: v for k, v in data.items() if k not in val_keys}
  16. with open(os.path.join(val_dir, SAVE_FILE), 'w') as output_json_file:
  17. json.dump(validation, output_json_file)
  18. with open(os.path.join(train_dir, SAVE_FILE), 'w') as output_json_file:
  19. json.dump(train, output_json_file)
  20. for key, _ in validation.items():
  21. shutil.move(os.path.join(tmp_dir, "images", key), os.path.join(val_dir, "images", key))
  22. for key, _ in train.items():
  23. shutil.move(os.path.join(tmp_dir, "images", key), os.path.join(train_dir, "images"))
  24. shutil.rmtree(tmp_dir)