yolov5风力发电风扇检测代码仅供参考附数据代码数据集训练好的yolov5代码使用你提供的风力发电风扇检测数据集和预训练的YOLOv5代码来进行训练。以下是详细的步骤和代码示例帮助你开始使用这个数据集进行训练和评估。项目结构wind_turbine_blade_detection/ ├── main.py ├── train.py ├── evaluate.py ├── infer.py ├── visualize.py ├── datasets/ │ ├── wind_turbine_images/ │ │ ├── images/ │ │ │ ├── train/ │ │ │ └── val/ │ │ ├── labels/ │ │ │ ├── train/ │ │ │ └── val/ │ │ ├── train.txt │ │ └── val.txt ├── best_wind_model.pt ├── requirements.txt └── data.yaml文件内容requirements.txtopencv-python4.5.3.56 torch1.9.0cu111 matplotlib numpy pandas albumentations pyyamldata.yaml假设你的数据集自带data.yaml文件其内容应类似于train:./datasets/wind_turbine_images/images/trainval:./datasets/wind_turbine_images/images/valnc:1# 假设只有一个类别bladenames:[blade]数据准备确认数据集目录结构:确保你的数据集已经按照以下结构组织好datasets/ └── wind_turbine_images/ ├── images/ │ ├── train/ │ └── val/ ├── labels/ │ ├── train/ │ └── val/ ├── train.txt └── val.txt检查data.yaml文件:确认data.yaml文件中的路径和类别信息正确无误。训练脚本train.pyimporttorchfrompathlibimportPathfrommodels.experimentalimportattempt_loadfromutils.generalimportcheck_img_size,non_max_suppression,scale_coordsfromutils.datasetsimportLoadImagesfromutils.torch_utilsimportselect_devicefromutils.plotsimportplot_one_boximportmatplotlib.pyplotaspltimportcv2importyaml# 设置随机种子以保证可重复性torch.manual_seed(42)deftrain():# 定义参数weightsyolov5s.pt# 预训练权重文件cfgmodels/yolov5s.yaml# 模型配置文件data_cfgdata.yaml# 数据集配置文件imgsz640# 图像尺寸batch_size16# 批量大小epochs50# 训练轮数device# 设备选择 表示自动选择# 选择设备deviceselect_device(device)# 加载模型modelattempt_load(weights,map_locationdevice)model.nc1# 类别数量model.hyp[cls]*1.25# 调整分类损失权重model.hyp[obj]*1.25# 调整目标损失权重# 训练模型!python train.py--img{imgsz}--batch{batch_size}--epochs{epochs}--data{data_cfg}--cfg{cfg}--weights{weights}--name wind_turbine_blade_detection--project runs/trainif__name____main__:train()评估脚本evaluate.pyimporttorchfrompathlibimportPathfrommodels.experimentalimportattempt_loadfromutils.generalimportcheck_img_size,non_max_suppression,scale_coordsfromutils.datasetsimportLoadImagesfromutils.torch_utilsimportselect_devicefromutils.plotsimportplot_one_boximportmatplotlib.pyplotaspltimportcv2importyamldefevaluate():# 定义参数weightsruns/train/wind_turbine_blade_detection/weights/best.pt# 最佳权重文件data_cfgdata.yaml# 数据集配置文件imgsz640# 图像尺寸conf_thres0.25# 置信度阈值iou_thres0.45# NMS IoU 阈值device# 设备选择 表示自动选择# 选择设备deviceselect_device(device)# 加载模型modelattempt_load(weights,map_locationdevice)strideint(model.stride.max())# 模型步长imgszcheck_img_size(imgsz,sstride)# 检查图像尺寸# 加载数据集datasetLoadImages(datasets/wind_turbine_images/images/val,img_sizeimgsz,stridestride)# 评估模型!python val.py--data{data_cfg}--weights{weights}--img{imgsz}--conf-thres{conf_thres}--iou-thres{iou_thres}if__name____main__:evaluate()推理脚本infer.pyimporttorchfrompathlibimportPathfrommodels.experimentalimportattempt_loadfromutils.generalimportcheck_img_size,non_max_suppression,scale_coordsfromutils.datasetsimportLoadImagesfromutils.torch_utilsimportselect_devicefromutils.plotsimportplot_one_boximportmatplotlib.pyplotaspltimportcv2importyamldefdetect_and_visualize(image_path):# 定义参数weightsruns/train/wind_turbine_blade_detection/weights/best.pt# 最佳权重文件conf_thres0.25# 置信度阈值iou_thres0.45# NMS IoU 阈值imgsz640# 图像尺寸device# 设备选择 表示自动选择# 选择设备deviceselect_device(device)# 加载模型modelattempt_load(weights,map_locationdevice)strideint(model.stride.max())# 模型步长imgszcheck_img_size(imgsz,sstride)# 检查图像尺寸# 加载数据集datasetLoadImages(image_path,img_sizeimgsz,stridestride)forpath,img,im0s,vid_capindataset:imgtorch.from_numpy(img).to(device)imgimg.float()# uint8 to fp32img/255.0# 0 - 255 to 0.0 - 1.0ifimg.ndimension()3:imgimg.unsqueeze(0)# Inferencepredmodel(img,augmentFalse)[0]# Apply NMSprednon_max_suppression(pred,conf_thres,iou_thres,classesNone,agnosticFalse)# Process detectionsfori,detinenumerate(pred):# detections per imagep,s,im0,framepath,,im0s.copy(),getattr(dataset,frame,0)gntorch.tensor(im0.shape)[[1,0,1,0]]# normalization gain whwhiflen(det):# Rescale boxes from img_size to im0 sizedet[:,:4]scale_coords(img.shape[2:],det[:,:4],im0.shape).round()# Print resultsforcindet[:,-1].unique():n(det[:,-1]c).sum()# detections per classsf{n}{model.names[int(c)]}{s*(n1)}, # add to string# Write resultsfor*xyxy,conf,clsinreversed(det):labelf{model.names[int(cls)]}{conf:.2f}plot_one_box(xyxy,im0,labellabel,color(0,255,0),line_thickness2)# Show the resultsplt.imshow(cv2.cvtColor(im0,cv2.COLOR_BGR2RGB))plt.axis(off)plt.show()if__name____main__:image_pathpath/to/your/image.jpg# 替换为你的图像路径detect_and_visualize(image_path)可视化脚本visualize.pyimporttorchfrompathlibimportPathfrommodels.experimentalimportattempt_loadfromutils.generalimportcheck_img_size,non_max_suppression,scale_coordsfromutils.datasetsimportLoadImagesfromutils.torch_utilsimportselect_devicefromutils.plotsimportplot_one_boximportmatplotlib.pyplotaspltimportcv2importyamlimportrandomdefvisualize_dataset(dataset_path,num_samples5):# 定义参数weightsruns/train/wind_turbine_blade_detection/weights/best.pt# 最佳权重文件conf_thres0.25# 置信度阈值iou_thres0.45# NMS IoU 阈值imgsz640# 图像尺寸device# 设备选择 表示自动选择# 选择设备deviceselect_device(device)# 加载模型modelattempt_load(weights,map_locationdevice)strideint(model.stride.max())# 模型步长imgszcheck_img_size(imgsz,sstride)# 检查图像尺寸# 加载数据集withopen(dataset_path,r)asf:linesf.readlines()sample_pathsrandom.sample(lines,num_samples)forpathinsample_paths:pathpath.strip()datasetLoadImages(path,img_sizeimgsz,stridestride)forpath,img,im0s,vid_capindataset:imgtorch.from_numpy(img).to(device)imgimg.float()# uint8 to fp32img/255.0# 0 - 255 to 0.0 - 1.0ifimg.ndimension()3:imgimg.unsqueeze(0)# Inferencepredmodel(img,augmentFalse)[0]# Apply NMSprednon_max_suppression(pred,conf_thres,iou_thres,classesNone,agnosticFalse)# Process detectionsfori,detinenumerate(pred):# detections per imagep,s,im0,framepath,,im0s.copy(),getattr(dataset,frame,0)gntorch.tensor(im0.shape)[[1,0,1,0]]# normalization gain whwhiflen(det):# Rescale boxes from img_size to im0 sizedet[:,:4]scale_coords(img.shape[2:],det[:,:4],im0.shape).round()# Print resultsforcindet[:,-1].unique():n(det[:,-1]c).sum()# detections per classsf{n}{model.names[int(c)]}{s*(n1)}, # add to string# Write resultsfor*xyxy,conf,clsinreversed(det):labelf{model.names[int(cls)]}{conf:.2f}plot_one_box(xyxy,im0,labellabel,color(0,255,0),line_thickness2)# Show the resultsplt.imshow(cv2.cvtColor(im0,cv2.COLOR_BGR2RGB))plt.axis(off)plt.show()if__name____main__:dataset_pathdatasets/wind_turbine_images/val.txt# 替换为你的验证集路径visualize_dataset(dataset_path)运行步骤总结克隆项目仓库如果有的话:gitclone https://github.com/yourusername/wind_turbine_blade_detection.gitcdwind_turbine_blade_detection安装依赖项:conda create--namewind_det_envpython3.8conda activate wind_det_env pipinstall-rrequirements.txt下载YOLOv5代码:如果你还没有YOLOv5的代码库可以从GitHub上克隆下来gitclone https://github.com/ultralytics/yolov5.gitcdyolov5 pipinstall-rrequirements.txt准备数据集:确保你的数据集已经按照上述结构组织好。确认data.yaml文件中的路径和类别信息正确无误。训练模型:python train.py评估模型:python evaluate.py运行推理:python infer.py可视化数据集:python visualize.py操作界面选择图片进行检测: 修改infer.py中的image_path变量指向你要检测的图片路径然后运行python infer.py。批量检测: 在visualize.py中设置dataset_path为你想要可视化的数据集路径然后运行python visualize.py。详细解释requirements.txt列出项目所需的所有Python包及其版本。data.yaml配置数据集路径和类别信息用于YOLOv5模型训练。train.py加载预训练的YOLOv5模型并使用自定义数据集进行训练。训练完成后打印训练结果。evaluate.py加载训练好的YOLOv5模型并对验证集进行评估打印评估结果。infer.py对单张图像进行预测并可视化检测结果。visualize.py对数据集中的一些样本进行预测并可视化检测结果。希望这些详细的信息和代码能够帮助你顺利实施和优化你的风力发电风扇检测系统。