基于深度学习的水果检测识别系统(PyTorch+Pyside6+YOLOv5模型)

目录

1.数据集

2.数据集处理

3.模型训练

4.系统实现和部署


在文章中,我会上传本次项目,项目内容为非盈利性,二转请表明出处,出现任何收费等行为与本人无关

在数字化浪潮之下,水果识别技术已渐变为日常生活与工作中不可或缺的核心组件。为响应广大用户对水果识别精准度与效率的高标准,我们计划启动一项创新工程。此工程将采纳多通道数据处理技术,广泛覆盖图片、视频及实时摄像头输入,为用户塑造前所未有的检测体验。

多通道数据处理技术的运用,将极大地拓宽数据获取途径,使我们得以更全面捕捉水果的特征信息。无论是静态图片,还是动态视频,乃至实时摄像头捕捉的即时画面,我们的系统均可迅速、精确地展开分析与识别。此种全面的数据处理方式,确保在各种应用场景中,我们均可为用户提供准确无误的水果种类识别结果。

在算法选择上,我们将采纳业内成熟的深度学习算法YOLO v5,以保障水果识别的精确性与高效性。经过大量数据的训练与优化,我们的算法已具备卓越的图像识别能力,能够精准辨识各种水果的形态、颜色等细微特征。这将为用户提供更为可靠的水果识别结果,助其更好地了解与选择水果。

同时,我们深知用户体验的重要性。因此,在项目研发过程中,我们将注重界面的设计与交互的便捷性。我们将打造一款直观、美观且易于操作的用户界面,使用户能够轻松与系统进行交互,获取水果识别的结果。此外,我们将持续优化界面设计,依据用户反馈与需求进行改进,以提升用户的满意度与体验。

1.数据集

本项目采用的数据集来自Github上已公开的公共训练集,训练集链接:https://github.com/lddniupi/fastestdet-fruits/tree/fastestdet-fruits/data。Github用户lijiale提供的数据集包括了750张JPG格式图片及750份对应的XML标注文件。

2.数据集处理

import os
from tqdm import tqdm
import xml.etree.ElementTree as ET

path = "data/annotations"
if __name__ == '__main__':
    list_cls = []
    for name in tqdm(os.listdir(path)):
        xml_path = os.path.join(path, name)
        tree = ET.parse(xml_path)
        root = tree.getroot()

        for obj in root.iter('object'):
            cls = obj.findtext('name')
            if cls not in list_cls:
                list_cls.append(cls)
    print(list_cls)

在data_getclasses.py脚本中,程序将遍历annotations文件夹中的所有XML文件,并从中提取水果种类信息。

下面为XML格式文件内容:

<annotation>
    <folder>allfruits</folder>
    <filename>banana (2).jpg</filename>
    <path>F:\Yolo-FastestV2-main\my_data\allfruits\banana (2).jpg</path>
    <source>
       <database>Unknown</database>
    </source>
    <size>
       <width>640</width>
       <height>480</height>
       <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
       <name>banana</name>
       <pose>Unspecified</pose>
       <truncated>0</truncated>
       <difficult>0</difficult>
       <bndbox>
          <xmin>136</xmin>
          <ymin>79</ymin>
          <xmax>452</xmax>
          <ymax>396</ymax>
       </bndbox>
    </object>
</annotation>

data_getclasses程序能够解析内容并定位至根节点,随后逐步遍历所有object标签。在遍历过程中,程序会提取每个object标签下的name子标签作为标签名cls。接下来,程序将比较提取的cls与预定义的列表list_cls,若cls不在列表中,则将其添加至list_cls中。待所有object标签遍历完成后,程序将打印出list_cls,展示所有水果种类的标签。

通过使用data_getclasses程序,我们能够迅速识别文件中存在的所有水果种类,从而减轻人工阅读文件的负担,并降低出错的可能性。并通过引入tqdm库,更加直观的可视化了读取进度。

import os
import cv2
from tqdm import tqdm

path = r"C:\Users\Lenovo\Desktop\fruit_detect\data\JPEGimages"
if __name__ == '__main__':
    for name in tqdm(os.listdir(path)):
        img_path = os.path.join(path,name)


        img=cv2.imread(img_path,0)
        clahe=cv2.createCLAHE(tileGridSize=(3,3))
        dst =clahe.apply(img)

`data_util.py` 脚本旨在利用 OpenCV 库对 JPEGimages 文件夹中的所有图像执行直方图均衡化操作,旨在提升图像对比度和细节表现。

在主程序中,脚本会遍历指定路径下的所有文件,并对每张图片进行相应处理。对于每张图片,首先会构建完整的图片路径 `img_path`。接着,使用 `cv2.imread()` 方法以灰度模式(参数 0)读取图片。然后,创建一个 CLAHE(Contrast Limited Adaptive Histogram Equalization)对象,并设定块大小为 (3,3)。最后,将读取的灰度图像应用于 CLAHE 直方图均衡化操作,以生成处理后的图像 `dst`。

'''
拆分数据集: 训练集:验证集:测试集 = 7:2:1
'''
import os
import random
train_val_percent = 0.9
train_percent = 0.9 #这里的 train_percent 是指占 train_val_percent 中的
# xml 标签文件
base_path='data'
xml_file_path =base_path + '/annotations'
txt_save_path =base_path +'/ImageSets'
# 判断txt_save_path文件夹路径如果不存在,就创建出来
if not os.path.exists(txt_save_path):
    os.makedirs(txt_save_path)
# 统计标签文件xml的总数
total_xml = os.listdir(xml_file_path)
num = len(total_xml)
list_index = range(num) # 获取随机0 到 num-1的数字,作为索引值
# 计算训练集和验证集的数据量
train_val_num = int(num * train_val_percent)
# 计算训练集的数据量
train_num = int(train_val_num * train_percent)
# 获取列表 list_index 中 指定长度的随机数
train_val_indexs = random.sample(list_index, train_val_num)
train_indexs = random.sample(train_val_indexs, train_num)
# 打开四个文件 trainval.txt、test.txt、train.txt、val.txt 用来保存分出来的数据名称
file_train_val = open(os.path.join(txt_save_path, 'trainval.txt'), 'w')
file_train = open(os.path.join(txt_save_path, 'train.txt'), 'w')
file_test = open(os.path.join(txt_save_path, 'test.txt'), 'w')
file_val = open(os.path.join(txt_save_path, 'val.txt'), 'w')
for i in list_index:
# 获取到xml的文件名称,不要后缀
    name = total_xml[i][:-4] + '\n'
# 判断当前的索引值i是在哪部分
    if i in train_val_indexs:
# 在训练集或者验证集中
        file_train_val.write(name)
        if i in train_indexs:
# 在训练集中
            file_train.write(name)
        else:
# 在验证集中
            file_val.write(name)
    else:
    # 在测试集中
        file_test.write(name)
# 关闭资源
file_train_val.close()
file_train.close()
file_test.close()
file_val.close()

`data_split.py`脚本的功能是将给定的数据集按照指定比例划分为训练集、验证集和测试集,并生成相应的文件列表,方便后续的数据加载和处理。

首先,我们设定了三个基础路径变量:base_path、xml_file_path和txt_save_path。接下来,我们判断并创建txt_save_path所指向的文本文件保存路径,确保在路径不存在的情况下能够成功创建。

然后,我们统计XML标签文件的总数,并根据设定的比例计算出训练集、验证集和测试集各自应包含的数据量。通过随机抽样的方式,我们获得了train_val_indexs和train_indexs两个索引集合,分别对应训练集和验证集+训练集的索引。

为了保存划分后的数据名称,我们打开了四个文本文件:trainval.txt、test.txt、train.txt和val.txt。随后,我们遍历所有的标签文件,根据之前获得的索引值,将数据集划分为训练集、验证集和测试集,并将相应的文件名写入对应的文本文件中。

通过以上步骤,我们成功地实现了数据集的划分,并将结果保存到了指定的文本文件中。

import os
import shutil
import xml.etree.ElementTree as ET
from tqdm import tqdm

sets = ['train', 'test', 'val']
classes = ['banana', 'cucumber', 'grape', 'mongo', 'pear', 'peach']


def voc2yolo(image_id):
    in_file = open(annotations_path % image_id, encoding='utf-8')
    out_file = open(labels_path + r'\%s.txt' % image_id, 'w', encoding='utf-8')
    tree = ET.parse(in_file)
    root = tree.getroot()

    size = root.find('size')
    img_w = int(size.findtext('width'))
    img_h = int(size.findtext('height'))

    for obj in root.iter('object'):
        cls = obj.findtext('name')
        difficult = obj.findtext('difficult')

        if cls not in classes or int(difficult) == 1:
            continue

        cls_id = classes.index(cls)
        bndbox = obj.find('bndbox')
        xmin = int(bndbox.findtext('xmin'))
        ymin = int(bndbox.findtext('ymin'))
        xmax = int(bndbox.findtext('xmax'))
        ymax = int(bndbox.findtext('ymax'))

        if xmax > img_w:
            xmax = img_w
        if ymax > img_h:
            ymax = img_h

        w = xmax - xmin
        h = ymax - ymin
        cx = xmin + w / 2
        cy = ymin + h / 2

        w = round(w / img_w, 6)
        h = round(h / img_h, 6)
        cx = round(cx / img_w, 6)
        cy = round(cy / img_h, 6)

        out_file.write(f"{cls_id} {cx} {cy} {w} {h}\n")

    out_file.close()


def read_files():
    for img_set in sets:
        img_path = imageSets_path % (img_set)
        with open(img_path, 'r', encoding='utf-8') as file:
            image_ids = [item.strip() for item in file.readlines()]

        list_file = open(os.path.join(base_path, f'{img_set}.txt'), 'w')

        for image_id in tqdm(image_ids):
            voc2yolo(image_id)
            list_file.write(os.path.join(images_path, f'{image_id}.jpg\n'))

        list_file.close()


base_path = r'C:\Users\Lenovo\Desktop\fruit_detect\data'
imageSets_path = os.path.join(base_path, r'ImageSets\%s.txt')
annotations_path = os.path.join(base_path, r'annotations\%s.xml')
labels_path = os.path.join(base_path, 'labels')
images_path = os.path.join(base_path, 'images')
JPEGImages_path = os.path.join(base_path, 'JPEGImages')

if __name__ == '__main__':
    print("数据处理 开始")

    if not os.path.exists(labels_path):
        os.makedirs(labels_path)

    if os.path.exists(images_path):
        shutil.rmtree(images_path)

    shutil.copytree(JPEGImages_path, images_path)
    read_files()

    print("数据处理 完成")

在YOLO v5框架中,模型无法直接处理XML格式文件。因此,我们开发了`voc_2.yolo`脚本,用于将XML格式转换为txt格式,并生成训练目标检测模型所需的标签文件和图像列表。

明确界定了处理的数据集,包括'train'、'test'、'val'三个子集,涉及的目标类别为'banana'、'cucumber'、'grape'、'mongo'、'pear'、'peach'六种。为了满足将VOC格式标注数据转换为YOLO格式的需求,我们设计了voc2yolo函数。该函数的功能是将单个VOC格式标注数据转换成YOLO格式,并将其保存为.txt文件。

同时,为了处理数据集中的图像列表,我们开发了read_files函数。该函数负责读取每个数据集中的图像列表,并对列表中的每个图像调用voc2yolo函数进行格式转换和保存。

在程序执行过程中,我们设置了相应的路径变量,包括数据集路径、标注文件路径、输出标签路径和输出图像路径等。这些路径的设置确保了程序能够正确地访问和处理数据。

在主程序中,我们实施了严格的数据处理流程控制。首先,创建了输出标签文件夹labels_path。然后,清空images_path,并将JPEGImages_path中的图像复制到images_path下。最后,调用read_files函数对数据集进行处理,以确保数据的准确性和一致性。

3.模型训练

import argparse
import math
import os
os.environ["GIT_PYTHON_REFRESH"] = 'quiet'
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
import random
import subprocess
import sys
import time
from copy import deepcopy
from datetime import datetime, timedelta
from pathlib import Path

try:
    import comet_ml  # must be imported before torch (if installed)
except ImportError:
    comet_ml = None

import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import yaml
from torch.optim import lr_scheduler
from tqdm import tqdm

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

import val as validate  # for end-of-epoch mAP
from models.experimental import attempt_load
from models.yolo import Model
from utils.autoanchor import check_anchors
from utils.autobatch import check_train_batch_size
from utils.callbacks import Callbacks
from utils.dataloaders import create_dataloader
from utils.downloads import attempt_download, is_url
from utils.general import (
    LOGGER,
    TQDM_BAR_FORMAT,
    check_amp,
    check_dataset,
    check_file,
    check_git_info,
    check_git_status,
    check_img_size,
    check_requirements,
    check_suffix,
    check_yaml,
    colorstr,
    get_latest_run,
    increment_path,
    init_seeds,
    intersect_dicts,
    labels_to_class_weights,
    labels_to_image_weights,
    methods,
    one_cycle,
    print_args,
    print_mutation,
    strip_optimizer,
    yaml_save,
)
from utils.loggers import LOGGERS, Loggers
from utils.loggers.comet.comet_utils import check_comet_resume
from utils.loss import ComputeLoss
from utils.metrics import fitness
from utils.plots import plot_evolve
from utils.torch_utils import (
    EarlyStopping,
    ModelEMA,
    de_parallel,
    select_device,
    smart_DDP,
    smart_optimizer,
    smart_resume,
    torch_distributed_zero_first,
)

LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1))  # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
GIT_INFO = check_git_info()


def train(hyp, opt, device, callbacks):
    """
    Trains YOLOv5 model with given hyperparameters, options, and device, managing datasets, model architecture, loss
    computation, and optimizer steps.

    `hyp` argument is path/to/hyp.yaml or hyp dictionary.
    """
    save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = (
        Path(opt.save_dir),
        opt.epochs,
        opt.batch_size,
        opt.weights,
        opt.single_cls,
        opt.evolve,
        opt.data,
        opt.cfg,
        opt.resume,
        opt.noval,
        opt.nosave,
        opt.workers,
        opt.freeze,
    )
    callbacks.run("on_pretrain_routine_start")

    # Directories
    w = save_dir / "weights"  # weights dir
    (w.parent if evolve else w).mkdir(parents=True, exist_ok=True)  # make dir
    last, best = w / "last.pt", w / "best.pt"

    # Hyperparameters
    if isinstance(hyp, str):
        with open(hyp, errors="ignore") as f:
            hyp = yaml.safe_load(f)  # load hyps dict
    LOGGER.info(colorstr("hyperparameters: ") + ", ".join(f"{k}={v}" for k, v in hyp.items()))
    opt.hyp = hyp.copy()  # for saving hyps to checkpoints

    # Save run settings
    if not evolve:
        yaml_save(save_dir / "hyp.yaml", hyp)
        yaml_save(save_dir / "opt.yaml", vars(opt))

    # Loggers
    data_dict = None
    if RANK in {-1, 0}:
        include_loggers = list(LOGGERS)
        if getattr(opt, "ndjson_console", False):
            include_loggers.append("ndjson_console")
        if getattr(opt, "ndjson_file", False):
            include_loggers.append("ndjson_file")

        loggers = Loggers(
            save_dir=save_dir,
            weights=weights,
            opt=opt,
            hyp=hyp,
            logger=LOGGER,
            include=tuple(include_loggers),
        )

        # Register actions
        for k in methods(loggers):
            callbacks.register_action(k, callback=getattr(loggers, k))

        # Process custom dataset artifact link
        data_dict = loggers.remote_dataset
        if resume:  # If resuming runs from remote artifact
            weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size

    # Config
    plots = not evolve and not opt.noplots  # create plots
    cuda = device.type != "cpu"
    init_seeds(opt.seed + 1 + RANK, deterministic=True)
    with torch_distributed_zero_first(LOCAL_RANK):
        data_dict = data_dict or check_dataset(data)  # check if None
    train_path, val_path = data_dict["train"], data_dict["val"]
    nc = 1 if single_cls else int(data_dict["nc"])  # number of classes
    names = {0: "item"} if single_cls and len(data_dict["names"]) != 1 else data_dict["names"]  # class names
    is_coco = isinstance(val_path, str) and val_path.endswith("coco/val2017.txt")  # COCO dataset

    # Model
    check_suffix(weights, ".pt")  # check weights
    pretrained = weights.endswith(".pt")
    if pretrained:
        with torch_distributed_zero_first(LOCAL_RANK):
            weights = attempt_download(weights)  # download if not found locally
        ckpt = torch.load(weights, map_location="cpu")  # load checkpoint to CPU to avoid CUDA memory leak
        model = Model(cfg or ckpt["model"].yaml, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device)  # create
        exclude = ["anchor"] if (cfg or hyp.get("anchors")) and not resume else []  # exclude keys
        csd = ckpt["model"].float().state_dict()  # checkpoint state_dict as FP32
        csd = intersect_dicts(csd, model.state_dict(), exclude=exclude)  # intersect
        model.load_state_dict(csd, strict=False)  # load
        LOGGER.info(f"Transferred {len(csd)}/{len(model.state_dict())} items from {weights}")  # report
    else:
        model = Model(cfg, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device)  # create
    amp = check_amp(model)  # check AMP

    # Freeze
    freeze = [f"model.{x}." for x in (freeze if len(freeze) > 1 else range(freeze[0]))]  # layers to freeze
    for k, v in model.named_parameters():
        v.requires_grad = True  # train all layers
        # v.register_hook(lambda x: torch.nan_to_num(x))  # NaN to 0 (commented for erratic training results)
        if any(x in k for x in freeze):
            LOGGER.info(f"freezing {k}")
            v.requires_grad = False

    # Image size
    gs = max(int(model.stride.max()), 32)  # grid size (max stride)
    imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2)  # verify imgsz is gs-multiple

    # Batch size
    if RANK == -1 and batch_size == -1:  # single-GPU only, estimate best batch size
        batch_size = check_train_batch_size(model, imgsz, amp)
        loggers.on_params_update({"batch_size": batch_size})

    # Optimizer
    nbs = 64  # nominal batch size
    accumulate = max(round(nbs / batch_size), 1)  # accumulate loss before optimizing
    hyp["weight_decay"] *= batch_size * accumulate / nbs  # scale weight_decay
    optimizer = smart_optimizer(model, opt.optimizer, hyp["lr0"], hyp["momentum"], hyp["weight_decay"])

    # Scheduler
    if opt.cos_lr:
        lf = one_cycle(1, hyp["lrf"], epochs)  # cosine 1->hyp['lrf']
    else:
        lf = lambda x: (1 - x / epochs) * (1.0 - hyp["lrf"]) + hyp["lrf"]  # linear
    scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)  # plot_lr_scheduler(optimizer, scheduler, epochs)

    # EMA
    ema = ModelEMA(model) if RANK in {-1, 0} else None

    # Resume
    best_fitness, start_epoch = 0.0, 0
    if pretrained:
        if resume:
            best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
        del ckpt, csd

    # DP mode
    if cuda and RANK == -1 and torch.cuda.device_count() > 1:
        LOGGER.warning(
            "WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n"
            "See Multi-GPU Tutorial at https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training to get started."
        )
        model = torch.nn.DataParallel(model)

    # SyncBatchNorm
    if opt.sync_bn and cuda and RANK != -1:
        model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
        LOGGER.info("Using SyncBatchNorm()")

    # Trainloader
    train_loader, dataset = create_dataloader(
        train_path,
        imgsz,
        batch_size // WORLD_SIZE,
        gs,
        single_cls,
        hyp=hyp,
        augment=True,
        cache=None if opt.cache == "val" else opt.cache,
        rect=opt.rect,
        rank=LOCAL_RANK,
        workers=workers,
        image_weights=opt.image_weights,
        quad=opt.quad,
        prefix=colorstr("train: "),
        shuffle=True,
        seed=opt.seed,
    )
    labels = np.concatenate(dataset.labels, 0)
    mlc = int(labels[:, 0].max())  # max label class
    assert mlc < nc, f"Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}"

    # Process 0
    if RANK in {-1, 0}:
        val_loader = create_dataloader(
            val_path,
            imgsz,
            batch_size // WORLD_SIZE * 2,
            gs,
            single_cls,
            hyp=hyp,
            cache=None if noval else opt.cache,
            rect=True,
            rank=-1,
            workers=workers * 2,
            pad=0.5,
            prefix=colorstr("val: "),
        )[0]

        if not resume:
            if not opt.noautoanchor:
                check_anchors(dataset, model=model, thr=hyp["anchor_t"], imgsz=imgsz)  # run AutoAnchor
            model.half().float()  # pre-reduce anchor precision

        callbacks.run("on_pretrain_routine_end", labels, names)

    # DDP mode
    if cuda and RANK != -1:
        model = smart_DDP(model)

    # Model attributes
    nl = de_parallel(model).model[-1].nl  # number of detection layers (to scale hyps)
    hyp["box"] *= 3 / nl  # scale to layers
    hyp["cls"] *= nc / 80 * 3 / nl  # scale to classes and layers
    hyp["obj"] *= (imgsz / 640) ** 2 * 3 / nl  # scale to image size and layers
    hyp["label_smoothing"] = opt.label_smoothing
    model.nc = nc  # attach number of classes to model
    model.hyp = hyp  # attach hyperparameters to model
    model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc  # attach class weights
    model.names = names

    # Start training
    t0 = time.time()
    nb = len(train_loader)  # number of batches
    nw = max(round(hyp["warmup_epochs"] * nb), 100)  # number of warmup iterations, max(3 epochs, 100 iterations)
    # nw = min(nw, (epochs - start_epoch) / 2 * nb)  # limit warmup to < 1/2 of training
    last_opt_step = -1
    maps = np.zeros(nc)  # mAP per class
    results = (0, 0, 0, 0, 0, 0, 0)  # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
    scheduler.last_epoch = start_epoch - 1  # do not move
    scaler = torch.cuda.amp.GradScaler(enabled=amp)
    stopper, stop = EarlyStopping(patience=opt.patience), False
    compute_loss = ComputeLoss(model)  # init loss class
    callbacks.run("on_train_start")
    LOGGER.info(
        f'Image sizes {imgsz} train, {imgsz} val\n'
        f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
        f"Logging results to {colorstr('bold', save_dir)}\n"
        f'Starting training for {epochs} epochs...'
    )
    for epoch in range(start_epoch, epochs):  # epoch ------------------------------------------------------------------
        callbacks.run("on_train_epoch_start")
        model.train()

        # Update image weights (optional, single-GPU only)
        if opt.image_weights:
            cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc  # class weights
            iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw)  # image weights
            dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n)  # rand weighted idx

        # Update mosaic border (optional)
        # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
        # dataset.mosaic_border = [b - imgsz, -b]  # height, width borders

        mloss = torch.zeros(3, device=device)  # mean losses
        if RANK != -1:
            train_loader.sampler.set_epoch(epoch)
        pbar = enumerate(train_loader)
        LOGGER.info(("\n" + "%11s" * 7) % ("Epoch", "GPU_mem", "box_loss", "obj_loss", "cls_loss", "Instances", "Size"))
        if RANK in {-1, 0}:
            pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT)  # progress bar
        optimizer.zero_grad()
        for i, (imgs, targets, paths, _) in pbar:  # batch -------------------------------------------------------------
            callbacks.run("on_train_batch_start")
            ni = i + nb * epoch  # number integrated batches (since train start)
            imgs = imgs.to(device, non_blocking=True).float() / 255  # uint8 to float32, 0-255 to 0.0-1.0

            # Warmup
            if ni <= nw:
                xi = [0, nw]  # x interp
                # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0])  # iou loss ratio (obj_loss = 1.0 or iou)
                accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
                for j, x in enumerate(optimizer.param_groups):
                    # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
                    x["lr"] = np.interp(ni, xi, [hyp["warmup_bias_lr"] if j == 0 else 0.0, x["initial_lr"] * lf(epoch)])
                    if "momentum" in x:
                        x["momentum"] = np.interp(ni, xi, [hyp["warmup_momentum"], hyp["momentum"]])

            # Multi-scale
            if opt.multi_scale:
                sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs  # size
                sf = sz / max(imgs.shape[2:])  # scale factor
                if sf != 1:
                    ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]]  # new shape (stretched to gs-multiple)
                    imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False)

            # Forward
            with torch.cuda.amp.autocast(amp):
                pred = model(imgs)  # forward
                loss, loss_items = compute_loss(pred, targets.to(device))  # loss scaled by batch_size
                if RANK != -1:
                    loss *= WORLD_SIZE  # gradient averaged between devices in DDP mode
                if opt.quad:
                    loss *= 4.0

            # Backward
            scaler.scale(loss).backward()

            # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
            if ni - last_opt_step >= accumulate:
                scaler.unscale_(optimizer)  # unscale gradients
                torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0)  # clip gradients
                scaler.step(optimizer)  # optimizer.step
                scaler.update()
                optimizer.zero_grad()
                if ema:
                    ema.update(model)
                last_opt_step = ni

            # Log
            if RANK in {-1, 0}:
                mloss = (mloss * i + loss_items) / (i + 1)  # update mean losses
                mem = f"{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G"  # (GB)
                pbar.set_description(
                    ("%11s" * 2 + "%11.4g" * 5)
                    % (f"{epoch}/{epochs - 1}", mem, *mloss, targets.shape[0], imgs.shape[-1])
                )
                callbacks.run("on_train_batch_end", model, ni, imgs, targets, paths, list(mloss))
                if callbacks.stop_training:
                    return
            # end batch ------------------------------------------------------------------------------------------------

        # Scheduler
        lr = [x["lr"] for x in optimizer.param_groups]  # for loggers
        scheduler.step()

        if RANK in {-1, 0}:
            # mAP
            callbacks.run("on_train_epoch_end", epoch=epoch)
            ema.update_attr(model, include=["yaml", "nc", "hyp", "names", "stride", "class_weights"])
            final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
            if not noval or final_epoch:  # Calculate mAP
                results, maps, _ = validate.run(
                    data_dict,
                    batch_size=batch_size // WORLD_SIZE * 2,
                    imgsz=imgsz,
                    half=amp,
                    model=ema.ema,
                    single_cls=single_cls,
                    dataloader=val_loader,
                    save_dir=save_dir,
                    plots=False,
                    callbacks=callbacks,
                    compute_loss=compute_loss,
                )

            # Update best mAP
            fi = fitness(np.array(results).reshape(1, -1))  # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
            stop = stopper(epoch=epoch, fitness=fi)  # early stop check
            if fi > best_fitness:
                best_fitness = fi
            log_vals = list(mloss) + list(results) + lr
            callbacks.run("on_fit_epoch_end", log_vals, epoch, best_fitness, fi)

            # Save model
            if (not nosave) or (final_epoch and not evolve):  # if save
                ckpt = {
                    "epoch": epoch,
                    "best_fitness": best_fitness,
                    "model": deepcopy(de_parallel(model)).half(),
                    "ema": deepcopy(ema.ema).half(),
                    "updates": ema.updates,
                    "optimizer": optimizer.state_dict(),
                    "opt": vars(opt),
                    "git": GIT_INFO,  # {remote, branch, commit} if a git repo
                    "date": datetime.now().isoformat(),
                }

                # Save last, best and delete
                torch.save(ckpt, last)
                if best_fitness == fi:
                    torch.save(ckpt, best)
                if opt.save_period > 0 and epoch % opt.save_period == 0:
                    torch.save(ckpt, w / f"epoch{epoch}.pt")
                del ckpt
                callbacks.run("on_model_save", last, epoch, final_epoch, best_fitness, fi)

        # EarlyStopping
        if RANK != -1:  # if DDP training
            broadcast_list = [stop if RANK == 0 else None]
            dist.broadcast_object_list(broadcast_list, 0)  # broadcast 'stop' to all ranks
            if RANK != 0:
                stop = broadcast_list[0]
        if stop:
            break  # must break all DDP ranks

        # end epoch ----------------------------------------------------------------------------------------------------
    # end training -----------------------------------------------------------------------------------------------------
    if RANK in {-1, 0}:
        LOGGER.info(f"\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.")
        for f in last, best:
            if f.exists():
                strip_optimizer(f)  # strip optimizers
                if f is best:
                    LOGGER.info(f"\nValidating {f}...")
                    results, _, _ = validate.run(
                        data_dict,
                        batch_size=batch_size // WORLD_SIZE * 2,
                        imgsz=imgsz,
                        model=attempt_load(f, device).half(),
                        iou_thres=0.65 if is_coco else 0.60,  # best pycocotools at iou 0.65
                        single_cls=single_cls,
                        dataloader=val_loader,
                        save_dir=save_dir,
                        save_json=is_coco,
                        verbose=True,
                        plots=plots,
                        callbacks=callbacks,
                        compute_loss=compute_loss,
                    )  # val best model with plots
                    if is_coco:
                        callbacks.run("on_fit_epoch_end", list(mloss) + list(results) + lr, epoch, best_fitness, fi)

        callbacks.run("on_train_end", last, best, epoch, results)

    torch.cuda.empty_cache()
    return results


def parse_opt(known=False):
    """Parses command-line arguments for YOLOv5 training, validation, and testing."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="initial weights path")
    parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
    parser.add_argument("--data", type=str, default=ROOT / "data/VOC.yaml", help="dataset.yaml path")
    parser.add_argument("--hyp", type=str, default=ROOT / "data/hyps/hyp.scratch-low.yaml", help="hyperparameters path")
    parser.add_argument("--epochs", type=int, default=100, help="total training epochs")
    parser.add_argument("--batch-size", type=int, default=16, help="total batch size for all GPUs, -1 for autobatch")
    parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="train, val image size (pixels)")
    parser.add_argument("--rect", action="store_true", help="rectangular training")
    parser.add_argument("--resume", nargs="?", const=True, default=False, help="resume most recent training")
    parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
    parser.add_argument("--noval", action="store_true", help="only validate final epoch")
    parser.add_argument("--noautoanchor", action="store_true", help="disable AutoAnchor")
    parser.add_argument("--noplots", action="store_true", help="save no plot files")
    parser.add_argument("--evolve", type=int, nargs="?", const=300, help="evolve hyperparameters for x generations")
    parser.add_argument(
        "--evolve_population", type=str, default=ROOT / "data/hyps", help="location for loading population"
    )
    parser.add_argument("--resume_evolve", type=str, default=None, help="resume evolve from last generation")
    parser.add_argument("--bucket", type=str, default="", help="gsutil bucket")
    parser.add_argument("--cache", type=str, nargs="?", const="ram", help="image --cache ram/disk")
    parser.add_argument("--image-weights", action="store_true", help="use weighted image selection for training")
    parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
    parser.add_argument("--multi-scale", action="store_true", help="vary img-size +/- 50%%")
    parser.add_argument("--single-cls", action="store_true", help="train multi-class data as single-class")
    parser.add_argument("--optimizer", type=str, choices=["SGD", "Adam", "AdamW"], default="SGD", help="optimizer")
    parser.add_argument("--sync-bn", action="store_true", help="use SyncBatchNorm, only available in DDP mode")
    parser.add_argument("--workers", type=int, default=0, help="max dataloader workers (per RANK in DDP mode)")
    parser.add_argument("--project", default=ROOT / "runs/train", help="save to project/name")
    parser.add_argument("--name", default="exp", help="save to project/name")
    parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
    parser.add_argument("--quad", action="store_true", help="quad dataloader")
    parser.add_argument("--cos-lr", action="store_true", help="cosine LR scheduler")
    parser.add_argument("--label-smoothing", type=float, default=0.0, help="Label smoothing epsilon")
    parser.add_argument("--patience", type=int, default=100, help="EarlyStopping patience (epochs without improvement)")
    parser.add_argument("--freeze", nargs="+", type=int, default=[0], help="Freeze layers: backbone=10, first3=0 1 2")
    parser.add_argument("--save-period", type=int, default=-1, help="Save checkpoint every x epochs (disabled if < 1)")
    parser.add_argument("--seed", type=int, default=0, help="Global training seed")
    parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")

    # Logger arguments
    parser.add_argument("--entity", default=None, help="Entity")
    parser.add_argument("--upload_dataset", nargs="?", const=True, default=False, help='Upload data, "val" option')
    parser.add_argument("--bbox_interval", type=int, default=-1, help="Set bounding-box image logging interval")
    parser.add_argument("--artifact_alias", type=str, default="latest", help="Version of dataset artifact to use")

    # NDJSON logging
    parser.add_argument("--ndjson-console", action="store_true", help="Log ndjson to console")
    parser.add_argument("--ndjson-file", action="store_true", help="Log ndjson to file")

    return parser.parse_known_args()[0] if known else parser.parse_args()


def main(opt, callbacks=Callbacks()):
    """Runs training or hyperparameter evolution with specified options and optional callbacks."""
    if RANK in {-1, 0}:
        print_args(vars(opt))
        check_git_status()
        check_requirements(ROOT / "requirements.txt")

    # Resume (from specified or most recent last.pt)
    if opt.resume and not check_comet_resume(opt) and not opt.evolve:
        last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
        opt_yaml = last.parent.parent / "opt.yaml"  # train options yaml
        opt_data = opt.data  # original dataset
        if opt_yaml.is_file():
            with open(opt_yaml, errors="ignore") as f:
                d = yaml.safe_load(f)
        else:
            d = torch.load(last, map_location="cpu")["opt"]
        opt = argparse.Namespace(**d)  # replace
        opt.cfg, opt.weights, opt.resume = "", str(last), True  # reinstate
        if is_url(opt_data):
            opt.data = check_file(opt_data)  # avoid HUB resume auth timeout
    else:
        opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = (
            check_file(opt.data),
            check_yaml(opt.cfg),
            check_yaml(opt.hyp),
            str(opt.weights),
            str(opt.project),
        )  # checks
        assert len(opt.cfg) or len(opt.weights), "either --cfg or --weights must be specified"
        if opt.evolve:
            if opt.project == str(ROOT / "runs/train"):  # if default project name, rename to runs/evolve
                opt.project = str(ROOT / "runs/evolve")
            opt.exist_ok, opt.resume = opt.resume, False  # pass resume to exist_ok and disable resume
        if opt.name == "cfg":
            opt.name = Path(opt.cfg).stem  # use model.yaml as name
        opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))

    # DDP mode
    device = select_device(opt.device, batch_size=opt.batch_size)
    if LOCAL_RANK != -1:
        msg = "is not compatible with YOLOv5 Multi-GPU DDP training"
        assert not opt.image_weights, f"--image-weights {msg}"
        assert not opt.evolve, f"--evolve {msg}"
        assert opt.batch_size != -1, f"AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size"
        assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
        assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
        torch.cuda.set_device(LOCAL_RANK)
        device = torch.device("cuda", LOCAL_RANK)
        dist.init_process_group(
            backend="nccl" if dist.is_nccl_available() else "gloo", timeout=timedelta(seconds=10800)
        )

    # Train
    if not opt.evolve:
        train(opt.hyp, opt, device, callbacks)

    # Evolve hyperparameters (optional)
    else:
        # Hyperparameter evolution metadata (including this hyperparameter True-False, lower_limit, upper_limit)
        meta = {
            "lr0": (False, 1e-5, 1e-1),  # initial learning rate (SGD=1E-2, Adam=1E-3)
            "lrf": (False, 0.01, 1.0),  # final OneCycleLR learning rate (lr0 * lrf)
            "momentum": (False, 0.6, 0.98),  # SGD momentum/Adam beta1
            "weight_decay": (False, 0.0, 0.001),  # optimizer weight decay
            "warmup_epochs": (False, 0.0, 5.0),  # warmup epochs (fractions ok)
            "warmup_momentum": (False, 0.0, 0.95),  # warmup initial momentum
            "warmup_bias_lr": (False, 0.0, 0.2),  # warmup initial bias lr
            "box": (False, 0.02, 0.2),  # box loss gain
            "cls": (False, 0.2, 4.0),  # cls loss gain
            "cls_pw": (False, 0.5, 2.0),  # cls BCELoss positive_weight
            "obj": (False, 0.2, 4.0),  # obj loss gain (scale with pixels)
            "obj_pw": (False, 0.5, 2.0),  # obj BCELoss positive_weight
            "iou_t": (False, 0.1, 0.7),  # IoU training threshold
            "anchor_t": (False, 2.0, 8.0),  # anchor-multiple threshold
            "anchors": (False, 2.0, 10.0),  # anchors per output grid (0 to ignore)
            "fl_gamma": (False, 0.0, 2.0),  # focal loss gamma (efficientDet default gamma=1.5)
            "hsv_h": (True, 0.0, 0.1),  # image HSV-Hue augmentation (fraction)
            "hsv_s": (True, 0.0, 0.9),  # image HSV-Saturation augmentation (fraction)
            "hsv_v": (True, 0.0, 0.9),  # image HSV-Value augmentation (fraction)
            "degrees": (True, 0.0, 45.0),  # image rotation (+/- deg)
            "translate": (True, 0.0, 0.9),  # image translation (+/- fraction)
            "scale": (True, 0.0, 0.9),  # image scale (+/- gain)
            "shear": (True, 0.0, 10.0),  # image shear (+/- deg)
            "perspective": (True, 0.0, 0.001),  # image perspective (+/- fraction), range 0-0.001
            "flipud": (True, 0.0, 1.0),  # image flip up-down (probability)
            "fliplr": (True, 0.0, 1.0),  # image flip left-right (probability)
            "mosaic": (True, 0.0, 1.0),  # image mixup (probability)
            "mixup": (True, 0.0, 1.0),  # image mixup (probability)
            "copy_paste": (True, 0.0, 1.0),
        }  # segment copy-paste (probability)

        # GA configs
        pop_size = 50
        mutation_rate_min = 0.01
        mutation_rate_max = 0.5
        crossover_rate_min = 0.5
        crossover_rate_max = 1
        min_elite_size = 2
        max_elite_size = 5
        tournament_size_min = 2
        tournament_size_max = 10

        with open(opt.hyp, errors="ignore") as f:
            hyp = yaml.safe_load(f)  # load hyps dict
            if "anchors" not in hyp:  # anchors commented in hyp.yaml
                hyp["anchors"] = 3
        if opt.noautoanchor:
            del hyp["anchors"], meta["anchors"]
        opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir)  # only val/save final epoch
        # ei = [isinstance(x, (int, float)) for x in hyp.values()]  # evolvable indices
        evolve_yaml, evolve_csv = save_dir / "hyp_evolve.yaml", save_dir / "evolve.csv"
        if opt.bucket:
            # download evolve.csv if exists
            subprocess.run(
                [
                    "gsutil",
                    "cp",
                    f"gs://{opt.bucket}/evolve.csv",
                    str(evolve_csv),
                ]
            )

        # Delete the items in meta dictionary whose first value is False
        del_ = [item for item, value_ in meta.items() if value_[0] is False]
        hyp_GA = hyp.copy()  # Make a copy of hyp dictionary
        for item in del_:
            del meta[item]  # Remove the item from meta dictionary
            del hyp_GA[item]  # Remove the item from hyp_GA dictionary

        # Set lower_limit and upper_limit arrays to hold the search space boundaries
        lower_limit = np.array([meta[k][1] for k in hyp_GA.keys()])
        upper_limit = np.array([meta[k][2] for k in hyp_GA.keys()])

        # Create gene_ranges list to hold the range of values for each gene in the population
        gene_ranges = [(lower_limit[i], upper_limit[i]) for i in range(len(upper_limit))]

        # Initialize the population with initial_values or random values
        initial_values = []

        # If resuming evolution from a previous checkpoint
        if opt.resume_evolve is not None:
            assert os.path.isfile(ROOT / opt.resume_evolve), "evolve population path is wrong!"
            with open(ROOT / opt.resume_evolve, errors="ignore") as f:
                evolve_population = yaml.safe_load(f)
                for value in evolve_population.values():
                    value = np.array([value[k] for k in hyp_GA.keys()])
                    initial_values.append(list(value))

        # If not resuming from a previous checkpoint, generate initial values from .yaml files in opt.evolve_population
        else:
            yaml_files = [f for f in os.listdir(opt.evolve_population) if f.endswith(".yaml")]
            for file_name in yaml_files:
                with open(os.path.join(opt.evolve_population, file_name)) as yaml_file:
                    value = yaml.safe_load(yaml_file)
                    value = np.array([value[k] for k in hyp_GA.keys()])
                    initial_values.append(list(value))

        # Generate random values within the search space for the rest of the population
        if initial_values is None:
            population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size)]
        elif pop_size > 1:
            population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size - len(initial_values))]
            for initial_value in initial_values:
                population = [initial_value] + population

        # Run the genetic algorithm for a fixed number of generations
        list_keys = list(hyp_GA.keys())
        for generation in range(opt.evolve):
            if generation >= 1:
                save_dict = {}
                for i in range(len(population)):
                    little_dict = {list_keys[j]: float(population[i][j]) for j in range(len(population[i]))}
                    save_dict[f"gen{str(generation)}number{str(i)}"] = little_dict

                with open(save_dir / "evolve_population.yaml", "w") as outfile:
                    yaml.dump(save_dict, outfile, default_flow_style=False)

            # Adaptive elite size
            elite_size = min_elite_size + int((max_elite_size - min_elite_size) * (generation / opt.evolve))
            # Evaluate the fitness of each individual in the population
            fitness_scores = []
            for individual in population:
                for key, value in zip(hyp_GA.keys(), individual):
                    hyp_GA[key] = value
                hyp.update(hyp_GA)
                results = train(hyp.copy(), opt, device, callbacks)
                callbacks = Callbacks()
                # Write mutation results
                keys = (
                    "metrics/precision",
                    "metrics/recall",
                    "metrics/mAP_0.5",
                    "metrics/mAP_0.5:0.95",
                    "val/box_loss",
                    "val/obj_loss",
                    "val/cls_loss",
                )
                print_mutation(keys, results, hyp.copy(), save_dir, opt.bucket)
                fitness_scores.append(results[2])

            # Select the fittest individuals for reproduction using adaptive tournament selection
            selected_indices = []
            for _ in range(pop_size - elite_size):
                # Adaptive tournament size
                tournament_size = max(
                    max(2, tournament_size_min),
                    int(min(tournament_size_max, pop_size) - (generation / (opt.evolve / 10))),
                )
                # Perform tournament selection to choose the best individual
                tournament_indices = random.sample(range(pop_size), tournament_size)
                tournament_fitness = [fitness_scores[j] for j in tournament_indices]
                winner_index = tournament_indices[tournament_fitness.index(max(tournament_fitness))]
                selected_indices.append(winner_index)

            # Add the elite individuals to the selected indices
            elite_indices = [i for i in range(pop_size) if fitness_scores[i] in sorted(fitness_scores)[-elite_size:]]
            selected_indices.extend(elite_indices)
            # Create the next generation through crossover and mutation
            next_generation = []
            for _ in range(pop_size):
                parent1_index = selected_indices[random.randint(0, pop_size - 1)]
                parent2_index = selected_indices[random.randint(0, pop_size - 1)]
                # Adaptive crossover rate
                crossover_rate = max(
                    crossover_rate_min, min(crossover_rate_max, crossover_rate_max - (generation / opt.evolve))
                )
                if random.uniform(0, 1) < crossover_rate:
                    crossover_point = random.randint(1, len(hyp_GA) - 1)
                    child = population[parent1_index][:crossover_point] + population[parent2_index][crossover_point:]
                else:
                    child = population[parent1_index]
                # Adaptive mutation rate
                mutation_rate = max(
                    mutation_rate_min, min(mutation_rate_max, mutation_rate_max - (generation / opt.evolve))
                )
                for j in range(len(hyp_GA)):
                    if random.uniform(0, 1) < mutation_rate:
                        child[j] += random.uniform(-0.1, 0.1)
                        child[j] = min(max(child[j], gene_ranges[j][0]), gene_ranges[j][1])
                next_generation.append(child)
            # Replace the old population with the new generation
            population = next_generation
        # Print the best solution found
        best_index = fitness_scores.index(max(fitness_scores))
        best_individual = population[best_index]
        print("Best solution found:", best_individual)
        # Plot results
        plot_evolve(evolve_csv)
        LOGGER.info(
            f'Hyperparameter evolution finished {opt.evolve} generations\n'
            f"Results saved to {colorstr('bold', save_dir)}\n"
            f'Usage example: $ python train.py --hyp {evolve_yaml}'
        )


def generate_individual(input_ranges, individual_length):
    """Generates a list of random values within specified input ranges for each gene in the individual."""
    individual = []
    for i in range(individual_length):
        lower_bound, upper_bound = input_ranges[i]
        individual.append(random.uniform(lower_bound, upper_bound))
    return individual


def run(**kwargs):
    """
    Executes YOLOv5 training with given options, overriding with any kwargs provided.

    Example: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
    """
    opt = parse_opt(True)
    for k, v in kwargs.items():
        setattr(opt, k, v)
    main(opt)
    return opt


if __name__ == "__main__":
    opt = parse_opt()
    main(opt)

Train脚本是基于YOLOv5的目标检测模型所编写的训练脚本。它涵盖了模型训练、超参数设置、数据集管理、模型架构定义、损失计算与优化器步骤等多个核心功能。以下是脚本的主要组成部分概述:

 `train()` 函数:该函数用于启动YOLOv5模型的训练过程。

 `parse_opt()` 函数:负责解析用户在命令行中输入的选项参数,以便脚本根据用户意图执行相应的操作。

 超参数演化部分:该部分利用遗传算法进行超参数搜索与优化。通过这种方法,脚本能够自动寻找最佳的超参数组合,以提升模型训练的效果。

脚本执行入口:该部分负责判断脚本是直接运行还是被其他代码作为模块导入。根据这一判断,脚本将执行相应的操作。

根据用户提供的选项,执行模型训练或超参数演化,以优化模型性能。超参数演化部分利用遗传算法寻找最佳超参数组合,从而提高模型训练的效果。

4.系统实现和部署

在日常生活和工作中,水果识别工具的应用场景可能需要针对特定用户群体进行定制,比如在超市中进行商品称重等。因此,设计一个合适的登录界面对于提高用户体验和工具的使用效率至关重要。

在Pyside6 Designer中,开发者可以利用border-radius属性来修改对象的边角形态,使其呈现出更加圆润的弧线角效果。此外,通过运用Widget功能,开发者还能够方便地将多个部件进行组合操作,从而实现更加高效和灵活的界面设计。

    def password(self):
        account = self.lineEdit.text()
        mima = self.lineEdit_2.text()
        if account == '123' and mima == '123':
            print('登陆成功')
            # self.close()

            win.hide()
            window.show()

在`password`函数中,我们设定登录账号为"123",密码同样为"123"。当账号和密码验证成功后,我们将关闭登录界面,并展示功能界面以供用户使用。

在UI界面中,针对图片检测、视频检测和摄像头检测三个通道,进行了三种组合,在“图片检测”中,下方显示的是相对应的“选择图片”和“侦测结果”,相应的,在“视频检测”中显示的是“选择视频”和“清除视频”,在“摄像头检测”中显示的是“打开摄像头”和“关闭摄像头”。

    def open_img(self):
        self.output.setPixmap(QPixmap())
        print("点击了【选择图片文件】按钮")
        filepath = QFileDialog.getOpenFileName(self, dir=r'C:\Users\Lenovo\Desktop\fruit_detect\data\images', filter='*.png;*.jpg;*jpeg')
        print(filepath)
        self.img_path = filepath[0]
        self.input.setPixmap(QPixmap(filepath[0]))

    def detect_img(self):
        print("点击了【进行种类侦测】按钮")

        print(self.img_path)
        img = self.my_detect.detect(self.img_path)

        h, w, c = img.shape
        qimg = QImage(img, w, h, w*c, QImage.Format_RGB888)
        self.output.setPixmap(QPixmap.fromImage(qimg))

在点击“侦测结果”按钮后,脚本通过传入path_yolov5和path_pt来加载YOLOv5模型。使用torch.hub.load方法加载本地的YOLOv5模型,并设置模型的阈值为0.1,然后将模型设置为评估模式。

在目标检测方法detect中,传入图片路径img_path,然后使用加载的YOLOv5模型对图片进行目标检测,获取检测结果图片,并将结果返回。

整个类的作用是封装了YOLOv5模型的加载和目标检测过程,通过调用detect方法可以实现对输入图片的目标检测,并返回检测结果图片。

    def open_mp4(self):
        self.output.setPixmap(QPixmap())  # 清空输出窗口
        print("点击了【选择视频文件】按钮")
        filepath, _ = QFileDialog.getOpenFileName(self, dir=r'C:\Users\Lenovo\Desktop\fruit_detect\data\mp4',
                                                  filter='*.mp4;*.avi;*mov')
        print(filepath)
        cap = cv2.VideoCapture(filepath)
        self.camera_opened = True  # 添加 camera_opened 属性

        self.model_v5 = torch.hub.load(r'C:\Users\Lenovo\Desktop\fruit_detect',
                                       'custom',
                                       path=r'C:\Users\Lenovo\Desktop\fruit_detect\best001.pt',
                                       source='local')
        self.model_v5.eval()
        self.model_v5.conf = 0.6

        while True:
            while True:
                ret, frame = cap.read()  # 读取一帧视频
                if not ret:
                    print("视频播放完成,重新开始播放")
                    cap.release()
                    cap = cv2.VideoCapture(filepath)  # 重新定位视频指针
                    break

                img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # 将图像从 BGR 格式转换为 RGB 格式
                img = cv2.resize(img, (640, 480))  # 调整图像大小

                qimage = QImage(img.data, img.shape[1], img.shape[0], QImage.Format_RGB888)
                pixmap = QPixmap.fromImage(qimage)

                self.input.setPixmap(pixmap)

                results = self.model_v5(img)
                image = results.render()[0]

                h, w, c = image.shape
                qimage_output = QImage(image.data, w, h, w * c, QImage.Format_RGB888)
                pixmap_output = QPixmap.fromImage(qimage_output)

                self.output.setPixmap(pixmap_output)

                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

                if not self.camera_opened:  # 检查 self.camera_opened 是否为 False
                    break
            if not self.camera_opened:  # 检查 self.camera_opened 是否为 False
                break


        self.input.setPixmap(QPixmap())
        self.output.setPixmap(QPixmap())

    def detect_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            self.timer.stop()
            return

        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        qimg = QImage(frame_rgb, frame_rgb.shape[1], frame_rgb.shape[0], QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(qimg)
        self.input.setPixmap(pixmap)

在代码执行过程中,首先需从给定的选项中选择MP4、AVI或MOV格式的视频文件。随后,利用`cv2.VideoCapture`函数加载并初始化所选视频。接下来,加载针对视频内容特别训练的YOLO v5模型,并设定置信度阈值为0.6。

通过嵌套两层`while`循环,实现视频的帧读取、处理以及循环播放功能。在此过程中,原始视频将展示在名为“input”的窗口中,而经过模型处理后的视频则会在名为“output”的窗口中呈现。

为确保视频处理的流畅性,提前将`self.camera_opened`设置为`True`。通过点击“清除视频”按钮,可将`self.camera_opened`的值修改为`False`。当检测到`self.camera_opened`为`False`时,脚本将终止`while`循环的执行,从而实现清除视频的效果。

    def open_camera(self):
        self.output.setPixmap(QPixmap())  # 清空输出窗口
        print("点击了【打开摄像头】按钮")

        cap = cv2.VideoCapture(0)  # 打开摄像头,参数 0 表示第一个摄像头
        self.camera_opened = True  # 添加 camera_opened 属性

        self.model_v5 = torch.hub.load(r'C:\Users\Lenovo\Desktop\fruit_detect',
                                       'custom',
                                       path=r'C:\Users\Lenovo\Desktop\fruit_detect\runs\train\exp\weights\best.pt',
                                       source='local')
        self.model_v5.eval()
        self.model_v5.conf = 0.6

        while True:
            ret, frame = cap.read()  # 读取一帧视频
            if not ret:
                print("无法读取视频流,请检查摄像头是否连接正常")
                break

            img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # 将图像从 BGR 格式转换为 RGB 格式
            img = cv2.resize(img, (640, 480))  # 调整图像大小

            qimage = QImage(img.data, img.shape[1], img.shape[0], QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(qimage)

            self.input.setPixmap(pixmap)

            results = self.model_v5(img)
            image = results.render()[0]

            h, w, c = image.shape
            qimage_output = QImage(image.data, w, h, w * c, QImage.Format_RGB888)
            pixmap_output = QPixmap.fromImage(qimage_output)

            self.output.setPixmap(pixmap_output)


            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

            if not self.camera_opened:  # 检查 self.camera_opened 是否为 False
                break


        cap.release()
        cv2.destroyAllWindows()
        self.input.setPixmap(QPixmap())
        self.output.setPixmap(QPixmap())

    def quit(self):
        self.camera_opened = False  # 修改实例特性的值,关闭摄像头
        print("退出操作完成")
        print("camera_opened 状态:", self.camera_opened)

在摄像头检测模块中,脚本通过调用`cv2.VideoCapture(0)`函数来启动摄像头设备。随后,利用一个`while`循环持续处理视频帧,这一流程与视频检测过程相似。然而,在判断`self.camera_opened`属性为`False`时,脚本执行了`cap.release()`操作,以确保摄像头资源得到妥善释放。  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值