修改yolo格式的labels类别、删除yolo格式的labels类别
1、项目中,数据集的类别顺序有时会改变,例如a项目类别1是b项目的类别3,,需要用a项目的数据集,只需要改类别就行,就不需要重新标注了,例如a项目的classes是
b项目的classes是
a项目的数据可以用到b项目,得a项目的类别改成b项目一致,这里就需要把1改成3,2改成5
import os
def gai_labels(labels_path, new_labels_path):
# 获取labels_path文件夹中所有的文件
labels_files = os.listdir(labels_path)
# 如果new_labels_path文件夹不存在,则创建
if not os.path.exists(new_labels_path):
os.makedirs(new_labels_path)
# 遍历每个标签文件
for labels_file in labels_files:
# 生成标签文件的完整路径
file_path = os.path.join(labels_path, labels_file)
# 创建新的文件路径
new_file_path = os.path.join(new_labels_path, labels_file)
# 读取标签文件内容并修改类别
with open(file_path, 'r') as f:
lines = f.readlines()
new_lines = []
for line in lines:
parts = line.strip().split()
# 修改类别1为3,类别2为5,类别3改成4
if parts[0] == '1':
parts[0] = '3'
# elif parts[0] == '2':
# parts[0] = '5'
new_lines.append(" ".join(parts) + '\n')
# 将修改后的内容写入新的文件
with open(new_file_path, 'w') as f:
f.writelines(new_lines)
if __name__ == "__main__":
labels_path = r"E:\project\CODE\labels"
new_labels_path = r"E:\project\CODE\gaihou"
gai_labels(labels_path, new_labels_path)
0 0.070312 0.476042 0.137500 0.164583 1 0.518750 0.760417 0.103125 0.116667 2 0.200781 0.643750 0.139063 0.170833 0 0.307812 0.527083 0.106250 0.145833 1 0.392969 0.240625 0.085938 0.110417 2 0.328906 0.075000 0.117188 0.145833 改后 0 0.070312 0.476042 0.137500 0.164583 3 0.518750 0.760417 0.103125 0.116667 5 0.200781 0.643750 0.139063 0.170833 0 0.307812 0.527083 0.106250 0.145833 3 0.392969 0.240625 0.085938 0.110417 5 0.328906 0.075000 0.117188 0.145833 2、删除类别0,类别1,类别2,类别4,类别5,只留下类别3的标签,代码如下:
import os
def del_labels(labels_path, new_labels_path):
# 获取labels_path文件夹中所有的文件
labels_files = os.listdir(labels_path)
# 如果new_labels_path文件夹不存在,则创建
if not os.path.exists(new_labels_path):
os.makedirs(new_labels_path)
# 遍历每个标签文件
for labels_file in labels_files:
# 生成标签文件的完整路径
file_path = os.path.join(labels_path, labels_file)
# 创建新的文件路径
new_file_path = os.path.join(new_labels_path, labels_file)
# 读取标签文件内容并过滤指定类别
with open(file_path, 'r') as f:
lines = f.readlines()
new_lines = []
for line in lines:
parts = line.strip().split()
# 跳过类别为0、1、2、4、5的行
if parts[0] in {'0', '1', '2', '4', '5'}:
continue
new_lines.append(" ".join(parts) + '\n')
# 将过滤后的内容写入新的文件
with open(new_file_path, 'w') as f:
f.writelines(new_lines)
if __name__ == "__main__":
labels_path = r"E:\project\CODE\labels"
new_labels_path = r"E:\project\CODE\del_hou"
del_labels(labels_path, new_labels_path)
删除后