YOLOv8 常用转换脚本
# 前言
本文为 YOLOv8 常用转换脚本
# 重命名图片和标注文件
我们在进行 YOLOv8 训练的数据集合并的时候经常遇到文件重名问题,下面的脚本将会批量重命名图片和标注文件
注意:标注文件为 txt 格式,图片为 jpg 格式,同时标注文件和图片文件在同一目录,如果有偏差请自行微调代码
rename_with_timestamp.py
import os
import time
import argparse
parser = argparse.ArgumentParser(description='Batch rename files with timestamp')
parser.add_argument('--dir', type=str, help='Directory path')
args = parser.parse_args()
file_path = args.dir
file_list = os.listdir(file_path)
for file in file_list:
if file.endswith(".txt"):
print(file)
base_name = os.path.splitext(file)[0]
extension = os.path.splitext(file)[1]
timestamp = str(round(time.time() * 1000))
new_name = base_name + timestamp + extension
os.rename(os.path.join(file_path, file), os.path.join(file_path, new_name)) # 重命名txt
image_file = os.path.join(file_path, base_name + ".jpg")
if os.path.exists(image_file):
os.rename(image_file, os.path.join(file_path, base_name + timestamp + ".jpg")) # 重命名jpg文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
使用方式
python ./rename_with_timestamp.py --dir ./
1
# 标签种类序号批量修改
txt_label_index_rename.py
import os
import re
import argparse
parser = argparse.ArgumentParser(description='Replace the label in text files')
parser.add_argument('--dir', type=str, help='Directory path')
args = parser.parse_args()
path = args.dir
files = []
for file in os.listdir(path):
if file.endswith(".txt"):
files.append(os.path.join(path, file))
for file in files:
with open(file, 'r') as f:
new_data = re.sub('^1', '0', f.read(), flags=re.MULTILINE)
with open(file, 'w') as f:
f.write(new_data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
上面的代码会将文件中的所有 txt 标注文件中的标签 1 替换为 0
使用形式
python ./txt_label_index_rename.py --dir ./
1
# 标注文件转换脚本
三种不同格式标注文件转换之前的文章讲到过,此处不赘述
编辑 (opens new window)
上次更新: 2023/10/14, 10:01:13