当前位置: 首页 > article >正文

YOLOv8 第Y7周 水果识别

1.创建文件夹:

YOLOv8开源地址 -- ultralytics-main文件下载链接:GitHub - ultralytics/ultralytics: NEW - YOLOv8 🚀 in PyTorch > ONNX > OpenVINO > CoreML > TFLite

其余文件由代码生成。 

数据集下载地址:Fruit Detection | Kaggle

2.运行split_train_val.py 代码内容 :

# 划分train、test、val文件
import os
import random
import argparse
 
parser = argparse.ArgumentParser()
# xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default='D:/ultralytics-main/ultralytics-main/paper_data/Annotations', type=str, help='input txt label path')
# 数据集的划分,地址选择自己数据下的ImageSets/Main
parser.add_argument('--txt_path', default='D:/ultralytics-main/ultralytics-main/paper_data/ImageSets/Main', type=str, help='output txt label path')
opt = parser.parse_args()
 
trainval_percent = 1.0
train_percent = 8/9
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
    os.makedirs(txtsavepath)
 
num = len(total_xml)
list_index = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)
 
file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_test = open(txtsavepath + '/test.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')
 
 
for i in list_index:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        file_trainval.write(name)
        if i in train:
            file_train.write(name)
        else:
            file_val.write(name)
    else:
        file_test.write(name)
 
file_trainval.close()
file_train.close()
file_val.close()
file_test.close()

3.运行voc_label.py 代码内容: 

import xml.etree.ElementTree as ET
import os
from os import getcwd
 
sets = ['train', 'val', 'test']
classes = ["banana", "snake fruit", "dragon fruit", "pineapple"]  # 改成自己的类别
abs_path = os.getcwd()
print(abs_path)
 
 
def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return x, y, w, h
 
 
 
def convert_annotation(image_id):
    in_file = open('D:/ultralytics-main/ultralytics-main/paper_data/Annotations/%s.xml' % (image_id), encoding='UTF-8')
    out_file = open('D:/ultralytics-main/ultralytics-main/paper_data/labels/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
 
    filename = root.find('filename').text
    filenameFormat = filename.split(".")[1]
    
    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))
        b1, b2, b3, b4 = b
        # 标注越界修正
        if b2 > w:
            b2 = w
        if b4 > h:
            b4 = h
        b = (b1, b2, b3, b4)
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    return filenameFormat
 
 
wd = getcwd()
for image_set in sets:
    if not os.path.exists('D:/ultralytics-main/ultralytics-main/paper_data/labels/'):
        os.makedirs('D:/ultralytics-main/ultralytics-main/paper_data/labels/')
    image_ids = open('D:/ultralytics-main/ultralytics-main/paper_data/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
    list_file = open('D:/ultralytics-main/ultralytics-main/paper_data/%s.txt' % (image_set),'w')
    for image_id in image_ids:
        filenameFormat = convert_annotation(image_id)
        list_file.write( 'D:/ultralytics-main/ultralytics-main/paper_data/images/%s.%s\n' % (image_id,filenameFormat))
    list_file.close()

 

4.命令窗代码:

yolo task=detect mode =train model=yolov8s.yaml data=D:\ultralytics-main\ultralytics-main\paper_data\ab.yaml epochs=100 batch=4

 运行结果:

D:\ultralytics-main\ultralytics-main>yolo task=detect mode =train model=yolov8s.yaml data=D:\ultralytics-main\ultralytics-main\paper_data\ab.yaml epochs=100 batch=4

                   from  n    params  module                                       arguments
  0                  -1  1       928  ultralytics.nn.modules.conv.Conv             [3, 32, 3, 2]
  1                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]
  2                  -1  1     29056  ultralytics.nn.modules.block.C2f             [64, 64, 1, True]
  3                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]
  4                  -1  2    197632  ultralytics.nn.modules.block.C2f             [128, 128, 2, True]
  5                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]
  6                  -1  2    788480  ultralytics.nn.modules.block.C2f             [256, 256, 2, True]
  7                  -1  1   1180672  ultralytics.nn.modules.conv.Conv             [256, 512, 3, 2]
  8                  -1  1   1838080  ultralytics.nn.modules.block.C2f             [512, 512, 1, True]
  9                  -1  1    656896  ultralytics.nn.modules.block.SPPF            [512, 512, 5]
 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 12                  -1  1    591360  ultralytics.nn.modules.block.C2f             [768, 256, 1]
 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 15                  -1  1    148224  ultralytics.nn.modules.block.C2f             [384, 128, 1]
 16                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 2]
 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 18                  -1  1    493056  ultralytics.nn.modules.block.C2f             [384, 256, 1]
 19                  -1  1    590336  ultralytics.nn.modules.conv.Conv             [256, 256, 3, 2]
 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 21                  -1  1   1969152  ultralytics.nn.modules.block.C2f             [768, 512, 1]
 22        [15, 18, 21]  1   2147008  ultralytics.nn.modules.head.Detect           [80, [128, 256, 512]]
YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients, 28.8 GFLOPs

New https://pypi.org/project/ultralytics/8.0.221 available  Update with 'pip install -U ultralytics'
Ultralytics YOLOv8.0.200  Python-3.10.7 torch-2.0.1+cpu CPU (AMD Ryzen 7 4800U with Radeon Graphics)
engine\trainer: task=detect, mode=train, model=yolov8s.yaml, data=D:\ultralytics-main\ultralytics-main\paper_data\ab.yaml, epochs=100, patience=50, batch=4, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=train, exist_ok=False, pretrained=True, optimizer=auto, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, show=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, vid_stride=1, stream_buffer=False, line_width=None, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, boxes=True, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, tracker=botsort.yaml, save_dir=runs\detect\train
Overriding model.yaml nc=80 with nc=4

                   from  n    params  module                                       arguments
  0                  -1  1       928  ultralytics.nn.modules.conv.Conv             [3, 32, 3, 2]
  1                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]
  2                  -1  1     29056  ultralytics.nn.modules.block.C2f             [64, 64, 1, True]
  3                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]
  4                  -1  2    197632  ultralytics.nn.modules.block.C2f             [128, 128, 2, True]
  5                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]
  6                  -1  2    788480  ultralytics.nn.modules.block.C2f             [256, 256, 2, True]
  7                  -1  1   1180672  ultralytics.nn.modules.conv.Conv             [256, 512, 3, 2]
  8                  -1  1   1838080  ultralytics.nn.modules.block.C2f             [512, 512, 1, True]
  9                  -1  1    656896  ultralytics.nn.modules.block.SPPF            [512, 512, 5]
 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 12                  -1  1    591360  ultralytics.nn.modules.block.C2f             [768, 256, 1]
 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']
 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 15                  -1  1    148224  ultralytics.nn.modules.block.C2f             [384, 128, 1]
 16                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 2]
 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 18                  -1  1    493056  ultralytics.nn.modules.block.C2f             [384, 256, 1]
 19                  -1  1    590336  ultralytics.nn.modules.conv.Conv             [256, 256, 3, 2]
 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 21                  -1  1   1969152  ultralytics.nn.modules.block.C2f             [768, 512, 1]
 22        [15, 18, 21]  1   2117596  ultralytics.nn.modules.head.Detect           [4, [128, 256, 512]]
YOLOv8s summary: 225 layers, 11137148 parameters, 11137132 gradients, 28.7 GFLOPs

TensorBoard: Start with 'tensorboard --logdir runs\detect\train', view at http://localhost:6006/
Freezing layer 'model.22.dfl.conv.weight'
train: Scanning D:\ultralytics-main\ultralytics-main\paper_data\labels... 177 images, 0 backgrounds, 0 corrupt: 100%|██
train: New cache created: D:\ultralytics-main\ultralytics-main\paper_data\labels.cache
val: Scanning D:\ultralytics-main\ultralytics-main\paper_data\labels... 23 images, 0 backgrounds, 0 corrupt: 100%|█████
val: New cache created: D:\ultralytics-main\ultralytics-main\paper_data\labels.cache
Plotting labels to runs\detect\train\labels.jpg...
optimizer: 'optimizer=auto' found, ignoring 'lr0=0.01' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically...
optimizer: AdamW(lr=0.00125, momentum=0.9) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias(decay=0.0)
Image sizes 640 train, 640 val
Using 0 dataloader workers
Logging results to runs\detect\train
Starting training for 100 epochs...

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      1/100         0G      3.429      4.168      4.378          3        640: 100%|██████████| 45/45 [02:23<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69    0.00059     0.0375   0.000461   7.53e-05

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      2/100         0G       3.26      3.453      4.037         12        640: 100%|██████████| 45/45 [02:23<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69   0.000574       0.05    0.00124   0.000297

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      3/100         0G      3.067      3.385       3.94          7        640: 100%|██████████| 45/45 [02:41<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:06<0
                   all         23         69    0.00482      0.505     0.0869     0.0272

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      4/100         0G       3.03      3.142      3.756         12        640: 100%|██████████| 45/45 [02:34<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:06<0
                   all         23         69      0.439      0.389      0.107     0.0437

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      5/100         0G      2.853       2.94       3.59          2        640: 100%|██████████| 45/45 [02:34<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:07<0
                   all         23         69      0.286      0.126     0.0346    0.00849

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      6/100         0G      2.774      2.647      3.502         12        640: 100%|██████████| 45/45 [02:35<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69      0.635      0.269      0.118     0.0222

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      7/100         0G      2.664      2.496       3.34         12        640: 100%|██████████| 45/45 [02:26<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69      0.304      0.516      0.431      0.161

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      8/100         0G      2.581      2.298      3.141         10        640: 100%|██████████| 45/45 [02:36<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69      0.532      0.429       0.48      0.213

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
      9/100         0G      2.444      2.123      3.049          3        640: 100%|██████████| 45/45 [02:37<00:00,  3.
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 3/3 [00:05<0
                   all         23         69       0.55      0.768      0.699      0.329

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
     10/100         0G      2.329      2.008      2.925         17        640:  82%|████████▏ | 37/45 [02:17<00:29,  3.


http://www.kler.cn/a/153908.html

相关文章:

  • 探究IOC容器刷新环节初始化前的预处理
  • Linux网络——套接字编程
  • Elasticsearch集群拒绝请求:索引磁盘使用超限
  • 如何解决JAVA程序通过obloader并发导数导致系统夯住的问题 | OceanBase 运维实践
  • Java 全栈知识体系
  • 【C/C++】Lambda 用法
  • NXP iMX8M Plus Qt5 双屏显示
  • 【开源】基于JAVA语言的校园电商物流云平台
  • 匿名结构体类型、结构体的自引用、结构体的内存对齐以及结构体传参
  • Git多库多账号本地SSH连接配置方法
  • LINUX 嵌入式C编程--信号编程
  • IDEA在左下角显示当前代码所属的类名/方法名
  • vue---消息订阅与发布(pubsub)
  • 网络通信原理,进制转化总结
  • SQL Server数据库部署
  • 九、FreeRTOS之FreeRTOS列表和列表项
  • 基于ASP.NET MVC技术的图书管理系统的设计与实现
  • Discuz论坛自动采集发布软件
  • JS中 require 与 import 的区别
  • Android File Transfer for Mac:畅享强大的安卓文件传输工具
  • Sock0s1.1
  • ssh连接docker容器处理备忘
  • python处理日期和时间
  • C++模版
  • android开发:获取手机IP和UDP广播
  • 支持Upsert、Kafka Connector、集成Airbyte,Milvus助力高效数据流处理