spatula_s13_yolo_detection / rename_files.py
Carey8175's picture
Upload 7 files
7ca05ba verified
"""
将文件按照特定的规则重命名
规则:
{order}_{label_num}_{labels}.jpg
{order}_{label_num}_{labels}.txt
"""
import os
import json
from collections import defaultdict
labels_path = './labels'
images_path = './images'
dataset_label_info = defaultdict(int)
for i in range(61):
dataset_label_info[str(i)] = 0
# find all the txt files in the folder
def find_txt_files():
return os.listdir(labels_path)
# generate the new name for the file
def generate_new_name(old_name, order):
"""
generate the new name(without extension) according to the label info
:param old_name: the label file name
:param order: the unique order
:return:
"""
global dataset_label_info
# read the file
with open(f'{labels_path}/{old_name}', 'r') as f:
labels = f.readlines()
# default dict to store the label info, default value is 0
label_info = defaultdict(int)
label_num = 0
for label in labels:
label = label.strip().split(' ')
label_class = label[0]
if label_class == '46':
pass
label_info[label_class] += 1
dataset_label_info[label_class] += 1
label_num += 1
# label_class_all = ''.join([f'{k}' for k, v in label_info.items()])
new_name = f'{order}_{label_num}'
return new_name
def main():
txt_files = find_txt_files()
# rename all the txt files to init to avoid the conflict
for i, txt_file in enumerate(txt_files):
new_name = f'init_{i}'
os.rename(f'{labels_path}/{txt_file}', f'{labels_path}/{new_name}.txt')
if os.path.exists(f'{images_path}/{txt_file.replace(".txt", ".jpg")}'):
os.rename(f'{images_path}/{txt_file.replace(".txt", ".jpg")}', f'{images_path}/{new_name}.jpg')
elif os.path.exists(f'{images_path}/{txt_file.replace(".txt", ".png")}'):
os.rename(f'{images_path}/{txt_file.replace(".txt", ".png")}', f'{images_path}/{new_name}.jpg')
elif os.path.exists(f'{images_path}/{txt_file.replace(".txt", ".jpeg")}'):
os.rename(f'{images_path}/{txt_file.replace(".txt", ".jpeg")}', f'{images_path}/{new_name}.jpg')
else:
raise FileNotFoundError(f'No image file found for {txt_file}')
txt_files = find_txt_files()
for i, txt_file in enumerate(txt_files):
new_name = generate_new_name(txt_file, i)
print(f'{txt_file} -> {new_name}')
os.rename(f'{labels_path}/{txt_file}', f'{labels_path}/{new_name}.txt')
os.rename(f'{images_path}/{txt_file.replace(".txt", ".jpg")}', f'{images_path}/{new_name}.jpg')
# save the dataset label info
with open('dataset_label_info.json', 'w') as f:
json.dump(dataset_label_info, f)
if __name__ == '__main__':
main()