detect.py
1.导入库
1.1导入安装好的python库
import argparse
import os
import sys
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
1.2定义路径
FILE = Path(__file__).resolve() #当前路径G:\2022\Apple-yolov5-master\detect.py
ROOT = FILE.parents[0] # YOLOv5 root directory #当前路径的上路径G:\2022\Apple-yolov5-master
if str(ROOT) not in sys.path: #模块的查询路径列表 Apple-yolov5-master这个里面的列表
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative 将绝对路径转化为相对路径 root = G:\2022\Apple-yolov5-master
1.3相对路径下的模块加载
#相对路径下的模块
from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
1.2主函数解析
有if __name__ == "__main__"表示.py可以独立运行
if __name__ == "__main__":
opt = parse_opt() #解析命令行参数
main(opt) #执行main函数
1.2.1 main函数
def main(opt):
check_requirements(exclude=('tensorboard', 'thop')) #检测包是否成功安装
run(**vars(opt)) #执行run函数
1.2.2 run函数中关键函数
预测
# Inference 预测
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
pred = model(im, augment=augment, visualize=visualize) # augment 是否需要数据增强 #torch.size([1,18900,85]),18900框,85个预测信息 # x,y,w,h,c,种类预测值80
NMS非极大抑制
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) #1,5,6 最后5个框,6个信息,x,y,w,h,c,目标所属类别
图片尺度不标准进行处理
把检测框画到原图上
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round() #坐标映射 im(640,480)映射到原图im0(1080,810)
2.YOLO.py
2.1main函数
定义参数 关键是cfg的yaml文件
if __name__ == '__main__':
#定义参数信息
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--profile', action='store_true', help='profile model speed')
parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
opt = parser.parse_args()
opt.cfg = check_yaml(opt.cfg) # check YAML
print_args(vars(opt))
device = select_device(opt.device)
创建模型
model = Model(opt.cfg).to(device)
模型搭建
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes #模型初始化,网络搭建
更具YOLOv5s.yaml文件搭配模型
def parse_model(d, ch): # model_dict, input_channels(3)
YOLOv5.yaml文件解读
相关Conv、C3、Concat等模型在common.py文件中
3.train.py
3.1参数设置
def parse_opt(known=False):
3.2main函数
Resume从可以设置从中断中恢复
# Resume
if opt.resume and not check_wandb_resume(opt) and not opt.evolve: # resume an interrupted run 从中断中恢复
Evolve超参数优化设置,通过遗传修改hpy里面参数,可以直接使用hpy文件效果满足要求
train训练函数
# Train 正式训练
if not opt.evolve: #evolve
train(opt.hyp, opt, device, callbacks) #train函数
if WORLD_SIZE > 1 and RANK == 0:
LOGGER.info('Destroying process group... ')
dist.destroy_process_group()
def train(hyp, opt, device, callbacks): # hyp 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')
Loggers函数 记录相关日志 在__init__.py中 train训练集 val测试集 Optimizer 优化器 Trainloader 加载训练集数据 val_loader 加载测试训练数据
定义损失函数,相关损失函数在loss.py中
compute_loss = ComputeLoss(model) # init loss class 定义损失函数
4.总结
路径很重要,模型有对应位置,
common.py主要是存放框架模型文件
loss.py损失文件
plots.py绘图文件
yolo.py架构文件
detect.py检测文件,通过这个文件来检测情况
train.py训练文件 这个文件负责训练,得到最优权重文件来进行检测
hyp主要有一些参数设置
数据集的yaml文件如coco.yaml
模型的架构文件 如YOLOv5s.yaml
权重文件YOLOv5s.pt