Yolov5(一)VOC划分数据集、VOC转YOLO数据集

news/2024/7/10 23:56:48 标签: YOLO, 深度学习, 人工智能

代码使用方法注意修改一下路径、验证集比例、类别名称,其他均不需要改动,自动划分训练集、验证集、建好全部文件夹、一键自动生成Yolo格式数据集在当前目录下,大家可以直接修改相应的配置文件进行训练。

目录

使用方法:

 全部代码:


使用方法:

 全部代码:

import os,random,shutil

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir,getcwd
from os.path import join


def convert(size,box):
    x_center=(box[0]+box[1])/2.0
    y_center=(box[2]+box[3])/2.0

    x=x_center/size[0]
    y=y_center/size[1]
    w=(box[1]-box[0])/size[0]
    h=(box[3]-box[2])/size[1]
    return (x,y,w,h)

def convert_annotation(xml_file_path,save_txt_file_path,classes):
    xml_file=os.listdir(xml_file_path)
    print(xml_file)
    for xml_name in xml_file:
        print(xml_file)
        xml_file=os.path.join(xml_file_path,xml_name)
        out_txt_path=os.path.join(save_txt_file_path,xml_name.split('.')[0]+".txt")
        out_txt_f=open(out_txt_path,'w')
        tree=ET.parse(xml_file)
        root=tree.getroot()
        size=root.find('size')

        w=int(size.find("width").text)
        h=int(size.find("height").text)

        for obj in root.iter("object"):
            difficult= obj.find('difficult').text
            cls=obj.find('name').text
            if cls not in classes or int(difficult)==1:
                continue
            cls_id=classes.index(cls)
            xmlbox=obj.find('bndbox')
            b=(float(xmlbox.find('xmin').text),
               float(xmlbox.find('xmax').text),
               float(xmlbox.find('ymin').text),
               float(xmlbox.find('ymax').text))

            print(w,h,b)
            bb=convert((w,h),b)
            out_txt_f.write(str(cls_id)+" "+" ".join([str(a) for a in bb])+"\n")


def moving(fileDir,tarDir,rate=0.2):
    pathDir=os.listdir(fileDir)
    filenumber=len(pathDir)
                     #自定义抽取图片比例
    picknumber=int(filenumber*rate)#按照rate比例从文件夹中取一定数量的图片
    sample=random.sample(pathDir,picknumber)#随机选取picknumber数量的图片
    print(sample)

    for name in sample:
        shutil.move(fileDir+"/"+name,tarDir+"/"+name)
    return

def movelabel(file_list,file_label_train,file_label_val):
    for i in file_list:
        if i.endswith(".png") or i.endswith(".jpg"):
            #filename=file_label_train+"/"+i[:-4]       可以将.xml文件将.txt改成.xml文件
            filename=file_label_train+"/"+i[:-4]+".xml"       #可以改成xml文件将.txt改成.xml
            if os.path.exists(filename):
                shutil.move(filename,file_label_val)
                print("处理成功")

if __name__=="__main__":
    """
    设置图片路径、label路径、验证集比例、类别
    """
    fileDir=r"./JPEGImages"    #图片的路径
    file_label_train = r"./Annotations"    #标签文件的路径
    rate=0.2  #验证集的比例
    classes1 = ['fire']

    """
    以下均不需要改动
    """



    if not os.path.exists("./JPEGImages_val"):
        # Create the folder
        os.makedirs("./JPEGImages_val")

    tarDir=r"./JPEGImages_val"
    moving(fileDir,tarDir,rate)
    file_list=os.listdir(tarDir)

    if not os.path.exists("./Annotations_val"):
        # Create the folder
        os.makedirs("./Annotations_val")

    file_label_val=r"./Annotations_val"
    movelabel(file_list,file_label_train,file_label_val)

    #VOC转Yolo格式

    # 2 voc 格式的xml标签文件
    if not os.path.exists("./val"):
        # Create the folder
        os.makedirs("./val")

    if not os.path.exists("./train"):
        # Create the folder
        os.makedirs("./train")


    xml_files1 = r"./Annotations_val"
    save_txt_files1 = r"./val"

    convert_annotation(xml_files1, save_txt_files1, classes1)

    xml_files1 = r"./Annotations"
    save_txt_files1 = r"./train"

    convert_annotation(xml_files1, save_txt_files1, classes1)


    #创建所有文件夹
    if not os.path.exists("./images"):
        # Create the folder
        os.makedirs("./images")

    if not os.path.exists("./labels"):
        # Create the folder
        os.makedirs("./labels")


    #将所有文件移动到最终的文件夹中

    import shutil

    # Define the source and destination folders
    source_folder = "./train"
    destination_folder = "./labels"

    # Move the files from the source folder to the destination folder
    shutil.move(source_folder, destination_folder)


    source_folder = "./val"
    destination_folder = "./labels"

    # Move the files from the source folder to the destination folder
    shutil.move(source_folder, destination_folder)

    source_folder = "./JPEGImages"
    destination_folder = "./images"

    # Move the files from the source folder to the destination folder
    shutil.move(source_folder, destination_folder)
    os.rename("./images/JPEGImages", "./images/train")

    source_folder = "./JPEGImages_val"
    destination_folder = "./images"

    # Move the files from the source folder to the destination folder
    shutil.move(source_folder, destination_folder)
    os.rename("./images/JPEGImages_val", "./images/val")


http://www.niftyadmin.cn/n/4935441.html

相关文章

Java注解的学习和自定义一个简单的注解

学习Java注解的使用 一、Java注解的含义? Java注解(Annotations)是Java 5之后引入的特性,用于为Java代码提供元数据。这些元数据本身不直接影响代码的逻辑功能,但可以被编译器、开发工具或框架用于生成代码、执行测试…

不知道打仗之害,就不知道打仗之利

不知道打仗之害,就不知道打仗之利 【安志强趣讲《孙子兵法》第7讲】 【原文】 夫钝兵挫锐,屈力殚货,则诸侯乘其弊而起,虽有智者,不能善其后矣。 【注释】 屈力殚货:屈力,指力量消耗,…

【刷题笔记8.13】【动态规划相关】LeetCode题目:斐波那契数列、爬楼梯

【动态规划相关】LeetCode题目&#xff1a;斐波那契数列、爬楼梯 &#xff08;一&#xff09;爬楼梯 题目描述 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; 提示&#xff1a; 1 < n <…

MongoDB-yum安装修改数据目录后启动失败

# 问题 mongodb 进程权限默认会被 SELinux 管理&#xff0c;修改配置中默认 storage.dbPath 、systemLog.path 造成启动失败。 # 解决方案 ① 修改为默认路径或重新安装 /var/lib/mongo /var/log/mongodb/mongod.log② 临时关闭 SELINUX 权限控制 setenforce 0③ 永久关闭 SE…

MySQL数据库----------安装anaconda---------python与数据库的链接

作者前言 &#x1f382; ✨✨✨✨✨✨&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f382; ​&#x1f382; 作者介绍&#xff1a; &#x1f382;&#x1f382; &#x1f382; &#x1f389;&#x1f389;&#x1f389…

利用爬虫爬取图片并保存

1 问题 在工作中&#xff0c;有时会遇到需要相当多的图片资源&#xff0c;可是如何才能在短时间内获得大量的图片资源呢&#xff1f; 2 方法 我们知道&#xff0c;网页中每一张图片都是一个连接&#xff0c;所以我们提出利用爬虫爬取网页图片并下载保存下来。 首先通过网络搜索…

【算法——双指针】LeetCode 283 移动零

题目描述&#xff1a; 思路&#xff1a; (双指针) O(n)O(n)O(n) 给定一个数组 nums&#xff0c;要求我们将所有的 0 移动到数组的末尾&#xff0c;同时保持非零元素的相对顺序。 如图所示&#xff0c;数组nums [0,1,0,3,12]&#xff0c;移动完成后变成nums [1,3,12,0,0] &am…

SQL | 汇总数据

9-汇总数据 9.1-聚集函数 在实际开发过程中&#xff0c;可能会遇到下面这些情况&#xff1a; 确定大于某个值的有多少行数据&#xff0c;比如游戏排行榜&#xff0c;查询玩家排行多少名。 获取表中某些行的和&#xff0c;比如双十一当天&#xff0c;某个用户总订单价格是多少…