在做yolov5_obb旋转目标检测时,用到的txt文件里的数据是整数型,用标注工具导出来的数据是浮点数,所以我们需要把导出来的数据进行四舍五入换成整数(int)形式。
import os
# 获取文件夹中所有的txt文件
folder_path = "/home/zhang/file/yolov5_obb_master/train_bottle/train/labels"
txt_files = [file for file in os.listdir(folder_path) if file.endswith(".txt")]
# 遍历每个txt文件
for file in txt_files:
file_path = os.path.join(folder_path, file)
# 打开文件并读取内容
with open(file_path, "r") as f:
lines = f.readlines()
# 对每行的数值进行四舍五入,确保可以转换为浮点数的部分
rounded_lines = [str(round(float(coord.split()[0]))) + " " +
str(round(float(coord.split()[1]))) + " " +
str(round(float(coord.split()[2]))) + " " +
str(round(float(coord.split()[3]))) + " " +
str(round(float(coord.split()[4]))) + " " +
str(round(float(coord.split()[5]))) + " " +
str(round(float(coord.split()[6]))) + " " +
str(round(float(coord.split()[7]))) + " " +
coord.split()[8] + " " +
coord.split()[9] for coord in lines]
# 将四舍五入后的内容写回文件
with open(file_path, "w") as f:
f.writelines('\n'.join(rounded_lines))