YOLO FastestV2目标检测网络使用

环境:opencv_python==4.2.0.34    pytorch==1.9.0

YOLO Fastest系列是轻量级目标检测网络,目前yolo系列最轻最快,适合全平台通用,也可以搭载在嵌入式端做到实时识别 效果

1、准备工作

下载源码:GitHub上YOLO FastestV2源码

使用前建议先看下REAMDE.md中的说明

配置环境:

pip install -r requirements.txt

测试是否配置成功

python test.py --data data/coco.data --weights modelzoo/coco2017-0.241078ap-model.pth --img img/000139.jpg

运行成功后 ,会生成图片test_result.png

2、数据集准备:

运行以下代码,会在当前目录新建train和val文件夹,数据集分割成训练集和验证集,分别放入两个文件夹中,并建立train.txt和val.txt文件

import os
import random
import shutil

image_Path=r'C:\Users\User\Desktop\marked\data'          #数据集路径
val_num=20                                               #验证集数据量
folder_txt_dir = ["train","val"]

def Creating_folder(folder_txt_dir):    
    '创建train和val文件夹'
    for foler in folder_txt_dir:
        data_path =os.path.join(str(os.getcwd()),foler)
        folder = os.path.exists(data_path)
        if not folder:                 
            os.makedirs(data_path)
    print('创建train和val文件夹成功')

def Split_datasets(paths):             
    '索引所有图片'    
    images=[]
    train_num_list=[]
    val_num_list=[]
    for path,folder,imgs in os.walk(paths):
        for img in imgs:
            if img.endswith(".jpg"):
                images.append(os.path.join(path,img))
            
    '分割数据集'        
    alist = random.sample(range(0,len(images)),val_num)
    alist.sort(reverse=True)
    for n in alist:
        val_num_list.append(images[n])
        images.pop(n)
    train_num_list=images    
                       
    '移动图片'
    train_path=os.path.join(str(os.getcwd()),'train')
    val_path=os.path.join(str(os.getcwd()),'val')        
    for train in train_num_list:
        fpath,fname=os.path.split(train)
        shutil.copy(train, os.path.join(train_path,fname))
    for val in val_num_list:
        fpath,fname=os.path.split(val)
        shutil.copy(val, os.path.join(val_path,fname))
        
    print('分割数据集成功')
        
def make_txt(folder_txt_dir):
    '创建train.txt和val.txt'
    for txt in folder_txt_dir:
        data_path =os.path.join(str(os.getcwd()),txt)
        image_list=os.listdir(txt)
        with open(file=txt+'.txt',mode='a+') as f:
            for name in image_list:
                if name.endswith(".jpg"):
                    item=os.path.join(data_path,name)  
                    f.write(item)
                    f.write("\n")
                    
    print('创建train.txt和val.txt成功')

if __name__ =='__main__':
    Creating_folder(folder_txt_dir)
    Split_datasets(image_Path)
    make_txt(folder_txt_dir)

然后新建class.txt,写入物体类别(一行写一个)

标注数据集:

Make Sense上进行标志数据集,点击Get Started,然后点击Click here to select them,选择分割好的train或者val文件夹,选中里面所有图片,然后点击Object Detection,点击Load labels from file,点击Click here to select them,选择刚才建立好的class.txt文件

标注图片时注意下对应标签,标注结束点击Actions,点击Export Annotations下载标志文件,将里面的图片.txt文件复制到train或者val文件夹下。

然后将class.txt改为class.namse

按照REAMDE.md上的描述,我可以得到如下目录结构

 

 

3、训练配置

生成锚点:

python genanchors.py --traintxt ./train.txt

--traintxt是上一步中生成的train.txt路径,运行后会生成anchors6.txt

配置训练文件:

在data文件夹中可以看到coco.data,我们可以仿照这个文件,新建mytrain.data,复制coco.data的内容到里面

[name]
model_name=coco           # model name

[train-configure]
epochs=300                # train epichs
steps=150,250             # Declining learning rate steps
batch_size=64             # batch size
subdivisions=1            # Same as the subdivisions of the darknet cfg file
learning_rate=0.001       # learning rate

[model-configure]
pre_weights=None          # The path to load the model, if it is none, then restart the training
classes=80                # Number of detection categories
width=352                 # The width of the model input image
height=352                # The height of the model input image
anchor_num=3              # anchor num
anchors=12.64,19.39, 37.88,51.48, 55.71,138.31, 126.91,78.23, 131.57,214.55, 279.92,258.87 #anchor bias

[data-configure]
train=/media/qiuqiu/D/coco/train2017.txt   # train dataset path .txt file
val=/media/qiuqiu/D/coco/val2017.txt       # val dataset path .txt file 
names=./data/coco.names                    # .names category label file

注意修改里面的anchors的值,为上一步anchors6.txt的内容,另外还有model_name和classes的值以及data-configure里面的路径,其他根据自己的需求修改即可。

4、训练模型

python train.py --data data/mytrain.data

--data为上一步建立的配置文件路径

如果是CPU训练,可能会爆内存,关掉一些后台,重新运行即可。正常运行如下图

 运行结束后,可以在weights文件下看到生成的.pth文件,我们使用最大一步的文件即可

5、模型评估

python evaluation.py --data data/mytrain.data --weights weights/mytrain-300-epoch-0.793847ap-model.pth

 --weights这个直接指向weights文件夹中最大一步的.pth文件即可

 6、使用模型进行检测

也是使用test.py文件

--data指向配置文件mytrain.data --weights指向weights文件夹中最大一步的.pth文件 --img指向想要检测图片路径,运行后也是生成test_result.png,也可以根据自己需求进行修改test.py文件

版权声明:本文为CSDN博主「猪不爱动脑」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_46292437/article/details/121240477

猪不爱动脑

我还没有学会写个人说明!

暂无评论

发表评论

相关推荐