import os import re import shutil import json # from type import List def get_list_train_test(camera_setting): # print(camera_setting) list_numbers = [] temp_dict = { 'train': {}, 'test': {}, 'confuse': {} } for images_name in os.listdir(os.path.join(camera_setting)): images_name = os.path.join(camera_setting, images_name) if os.path.isdir(images_name): return False images_id = images_name.split(".")[0].split("\\")[-1] try: numbers = re.findall(r'\d+', images_id)[0] except: print(images_id) list_numbers.append(numbers) set_numbers = set() for number in list_numbers: set_numbers.add(number) # print(set_numbers) for image_number in set_numbers: temp_list_train = [] temp_list_test = [] for images_name in os.listdir(os.path.join(camera_setting)): if image_number in images_name: # print(image_number) # print(images_name) if images_name.endswith(".jpg"): temp_list_test.append(images_name) else: temp_list_train.append(images_name) if len(temp_list_train) == 0: temp_dict['confuse'][image_number] = temp_list_test elif len(temp_list_test) == 0: temp_dict['confuse'][image_number] = temp_list_train else: temp_dict['train'][image_number] = temp_list_train temp_dict['test'][image_number] = temp_list_test return temp_dict def check_folder(camera_setting): list_folder = [] for item in os.listdir(camera_setting): if os.path.isdir(os.path.join(camera_setting, item)): list_folder.append(os.path.join(camera_setting, item)) for folder in list_folder: files = os.listdir(folder) for fname in files: # copying the files to the # destination directory shutil.copy2(os.path.join(folder,fname), os.path.join(folder,"..")) return list_folder def main(data_path): map_image = dict() map_image['train'] = {} map_image['test'] = {} map_image['confuse'] = {} map_image['false'] = [] for fold_number in os.listdir(data_path): if "." in fold_number: continue # print(fold_number) for address in os.listdir(os.path.join(data_path, fold_number)): address = os.path.join(data_path, fold_number, address) for camera_setting in os.listdir(address): camera_setting = os.path.join(address, camera_setting) # print(check_folder(camera_setting=camera_setting)) temp_dict = get_list_train_test(camera_setting=camera_setting) if temp_dict == False: map_image['false'].append(camera_setting) else: map_image['train'][camera_setting] = temp_dict['train'] map_image['test'][camera_setting] = temp_dict['test'] map_image['confuse'][camera_setting] = temp_dict['confuse'] with open("metadata.json", 'w') as fout: json_dumps_str = json.dumps(map_image, indent=4) print(json_dumps_str, file=fout) if __name__ == "__main__": data_path = "data_temp" main(data_path)