YOLO建立没有目标的负样本标签

在yolo格式中,如果想让无目标地背景图片参与训练,需要创建与图片名字一样的空白的txt文件。

如果标注文件夹里,没有相应图片的标注,则就创建一个同样名字的空白txt作为负样本的标签。

import os  #通过os模块调用系统命令


images_list = os.listdir(r"D:\Document_Exercitation\Video_Segmentation\picture1") #遍历整个文件夹下的文件并返回一个列表
txt_list = os.listdir(r"D:\Document_Exercitation\Video_Segmentation\Annotations")
txt_name=[]
for j in txt_list:
    txt_name.append(j.split(".")[0])  # 若带有后缀名,split去掉后缀名


for i in images_list:
     image_name=i.split(".")[0]#若带有后缀名,split去掉后缀名
    #print(image_name)
     if image_name not in txt_name:
         output_txt = f"D:\\Document_Exercitation\\Video_Segmentation\\yolo\\{image_name}.txt"
         with open(output_txt, "w", encoding='utf-8') as file:
             pass
         print(image_name)

images_list = os.listdir(r"D:\Document_Exercitation\Video_Segmentation\picture1")  # 遍历整个文件夹下的文件并返回一个列表
txt_list = os.listdir(r"D:\Document_Exercitation\Video_Segmentation\Annotations") 

 使用 os.listdir 列出 picture1Annotations 文件夹中的所有文件,分别存储在 images_listtxt_list 中。

txt_name = []
for j in txt_list:
    txt_name.append(j.split(".")[0])  # 若带有后缀名,split去掉后缀名  

 遍历 txt_list,使用 split(".")[0] 去掉文件后缀名,将处理后的文件名添加到 txt_name 列表中。

for i in images_list:
    image_name = i.split(".")[0]  # 若带有后缀名,split去掉后缀名
    # print(image_name)
    if image_name not in txt_name:
        output_txt = f"D:\\Document_Exercitation\\Video_Segmentation\\yolo\\{image_name}.txt"
        with open(output_txt, "w", encoding='utf-8') as file:
            pass  # 创建一个空文件
        print(image_name) 

遍历 images_list,使用 split(".")[0] 去掉文件后缀名,如果 image_name 不在 txt_name 列表中,则创建一个空的同名 .txt 文件,并打印 image_name 

JSON转换为YOLO格式标签需要经过以下步骤: 1. 将JSON文件加载到Python中。 2. 对于每个图像,将其宽度和高度读入。 3. 对于每个对象,将其类别ID转换为YOLO格式。 4. 计算每个对象的中心点坐标和宽度高度。 5. 将所有对象的YOLO格式标签写入一个文本文件。 下面是一个示例Python代码来实现这个转换: ``` import json # 加载JSON文件 with open('annotations.json', 'r') as f: data = json.load(f) # 获取图像宽度和高度 width, height = data['imageWidth'], data['imageHeight'] # 转换每个对象的类别ID为YOLO格式 class_map = {'cat': 0, 'dog': 1} # 假设类别ID为0和1 yolo_labels = [] for obj in data['annotations']: class_id = class_map[obj['label']] x_min, y_min, x_max, y_max = obj['BoundingBox'] x_center = (x_min + x_max) / 2 / width y_center = (y_min + y_max) / 2 / height w = (x_max - x_min) / width h = (y_max - y_min) / height yolo_labels.append(f"{class_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}") # 写入YOLO格式标签文件 with open('labels.txt', 'w') as f: f.write('\n'.join(yolo_labels)) ``` 在这个例子中,我们假设JSON文件包含一个名为`annotations.json`的图像注释文件,其中类别ID为`cat`和`dog`。我们还假设图像的宽度和高度可以在JSON文件中找到,并且我们将YOLO格式标签写入名为`labels.txt`的文件中。最后,我们使用`join()`方法将所有标签连接为单个字符串,并将其写入文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值