基于YOLOv8的鱼病害检测系统 鱼类病害数据集 训练使用鱼类病害检测数据集_包括环境设置、数据准备、模型训练、评估和推理部署。
如何构建一个基于YOLOv8的鱼病害检测系统训练使用鱼类病害检测数据集_包括环境设置、数据准备、模型训练、评估和推理部署。鱼病害检测数据集 鱼病害 1988张 带标注 voc yolo分类名: (图片张数 标注个数)红斑病: (896 1440)细菌性背部溃疡: (409, 451)白点病: (517, 586)骨髓炎:(273858)红腮病:(311321 )总数: (1988, 3656)构建一个基于YOLOv8的鱼病害检测系统涉及多个步骤包括环境设置、数据准备、模型训练、评估和推理部署。标注并且是VOC或YOLO格式文章目录如何构建一个基于YOLOv8的鱼病害检测系统训练使用鱼类病害检测数据集_包括环境设置、数据准备、模型训练、评估和推理部署。以下文字及代码仅供参考1. 环境设置2. 数据准备2.1 数据集结构2.2 转换VOC到YOLO格式3. 文件内容3.1 Config.py3.2 train.py3.3 detect_tools.py3.4 UIProgram/MainProgram.py3.5 requirements.txt3.6 setup.py3.7 README.mdTrainingRunning the GUIUsage Tutorial以下文字及代码仅供参考1. 环境设置确保你的开发环境已经安装了必要的库和工具pipinstalltorch torchvision ultralytics pyqt5 opencv-python pandas2. 数据准备2.1 数据集结构假设你的数据集已经按照YOLO标准格式进行了标注并且包含1988张图片和3656个标注。确保数据集目录结构如下datasets/ └── fish_disease_detection/ ├── images/ │ ├── train/ │ └── val/ ├── labels_yolo/ │ ├── train/ │ └── val/每个图像对应一个同名的.txt文件YOLO格式而标签文件是CSV或XML格式的注释文件。如果标注是VOC格式你需要将其转换为YOLO格式。2.2 转换VOC到YOLO格式如果你的数据是以VOC格式提供的可以使用Python脚本将它们转换为YOLO格式importxml.etree.ElementTreeasETimportos# Define class names and their corresponding IDsclass_names[红斑病,细菌性背部溃疡,白点病,骨髓炎,红腮病]class_ids{name:idxforidx,nameinenumerate(class_names)}defconvert_voc_to_yolo(xml_file,output_dir):treeET.parse(xml_file)roottree.getroot()img_widthint(root.find(size/width).text)img_heightint(root.find(size/height).text)withopen(os.path.join(output_dir,root.find(filename).text.split(.)[0].txt),w)asf:forobjinroot.findall(object):class_nameobj.find(name).textifclass_namenotinclass_ids:continuebboxobj.find(bndbox)x_minfloat(bbox.find(xmin).text)y_minfloat(bbox.find(ymin).text)x_maxfloat(bbox.find(xmax).text)y_maxfloat(bbox.find(ymax).text)x_center((x_minx_max)/2)/img_width y_center((y_miny_max)/2)/img_height bbox_width(x_max-x_min)/img_width bbox_height(y_max-y_min)/img_height f.write(f{class_ids[class_name]}{x_center}{y_center}{bbox_width}{bbox_height}\n)# Example usageforfilenameinos.listdir(path/to/voc/annotations):iffilename.endswith(.xml):convert_voc_to_yolo(os.path.join(path/to/voc/annotations,filename),labels_yolo/train)3. 文件内容3.1 Config.py配置文件用于定义数据集路径、模型路径等。# Config.pyDATASET_PATHdatasets/fish_disease_detection/MODEL_PATHruns/detect/train/weights/best.ptIMG_SIZE640BATCH_SIZE16EPOCHS50CONF_THRESHOLD0.53.2 train.py训练YOLOv8模型的脚本。注意这里我们有多个类别因此nc应该设置为类别数量并且names列表应该包含所有类别的名称。fromultralyticsimportYOLOimportos# Load a modelmodelYOLO(yolov8n.pt)# You can also use other versions like yolov8s.pt, yolov8m.pt, etc.# Define dataset configurationdataset_configf train:{os.path.join(os.getenv(DATASET_PATH,datasets/fish_disease_detection/),images/train)}val:{os.path.join(os.getenv(DATASET_PATH,datasets/fish_disease_detection/),images/val)}nc: 5 names: [红斑病, 细菌性背部溃疡, 白点病, 骨髓炎, 红腮病] # Save dataset configuration to a YAML filewithopen(fish_disease.yaml,w)asf:f.write(dataset_config)# Train the modelresultsmodel.train(datafish_disease.yaml,epochsint(os.getenv(EPOCHS,50)),imgszint(os.getenv(IMG_SIZE,640)),batchint(os.getenv(BATCH_SIZE,16)))3.3 detect_tools.py用于检测的工具函数。fromultralyticsimportYOLOimportcv2importnumpyasnpdefload_model(model_path):returnYOLO(model_path)defdetect_objects(frame,model,conf_threshold0.5):resultsmodel(frame,confconf_threshold)detections[]forresultinresults:boxesresult.boxes.cpu().numpy()forboxinboxes:rbox.xyxy[0].astype(int)clsint(box.cls[0])confround(float(box.conf[0]),2)labelf{model.names[cls]}{conf}detections.append((r,label))returndetectionsdefdraw_detections(frame,detections):for(r,label)indetections:cv2.rectangle(frame,(r[0],r[1]),(r[2],r[3]),(0,255,0),2)cv2.putText(frame,label,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,(0,255,0),2)returnframe3.4 UIProgram/MainProgram.py主程序使用PyQt5构建图形界面。importsysimportcv2fromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabel,QVBoxLayout,QWidget,QPushButtonfromPyQt5.QtGuiimportQImage,QPixmapfromPyQt5.QtCoreimportQt,QTimerfromdetect_toolsimportload_model,detect_objects,draw_detectionsimportosclassVideoWindow(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle(Fish Disease Detection)self.setGeometry(100,100,800,600)self.central_widgetQWidget()self.setCentralWidget(self.central_widget)self.layoutQVBoxLayout()self.central_widget.setLayout(self.layout)self.labelQLabel()self.layout.addWidget(self.label)self.start_buttonQPushButton(Start Detection)self.start_button.clicked.connect(self.start_detection)self.layout.addWidget(self.start_button)self.capNoneself.timerQTimer()self.timer.timeout.connect(self.update_frame)self.modelload_model(os.getenv(MODEL_PATH,runs/detect/train/weights/best.pt))defstart_detection(self):ifnotself.cap:self.capcv2.VideoCapture(0)# Use webcamself.timer.start(30)defupdate_frame(self):ret,frameself.cap.read()ifnotret:returndetectionsdetect_objects(frame,self.model,conf_thresholdfloat(os.getenv(CONF_THRESHOLD,0.5)))framedraw_detections(frame,detections)rgb_imagecv2.cvtColor(frame,cv2.COLOR_BGR2RGB)h,w,chrgb_image.shape bytes_per_linech*w qt_imageQImage(rgb_image.data,w,h,bytes_per_line,QImage.Format_RGB888)pixmapQPixmap.fromImage(qt_image)self.label.setPixmap(pixmap.scaled(800,600,Qt.KeepAspectRatio))if__name____main__:appQApplication(sys.argv)windowVideoWindow()window.show()sys.exit(app.exec_())3.5 requirements.txt列出所有依赖项。torch torchvision ultralytics pyqt5 opencv-python pandas3.6 setup.py用于安装项目的脚本。fromsetuptoolsimportsetup,find_packages setup(namefish_disease_detection,version0.1,packagesfind_packages(),install_requires[torch,torchvision,ultralytics,pyqt5,opencv-python,pandas],entry_points{console_scripts:[traintrain:main,detectUIProgram.MainProgram:main]})3.7 README.md项目说明文档。# Fish Disease Detection System This project uses YOLOv8 and PyQt5 to create a real-time fish disease detection system for images. The system detects various types of fish diseases such as red spot disease, bacterial back ulcers, white spot disease, myelitis, and red gill disease. ## Installation 1. Clone the repository: bash git clone https://github.com/yourusername/fish-disease-detection.git cd fish-disease-detectionInstall dependencies:pipinstall-rrequirements.txtSet up environment variables (optional):exportDATASET_PATH./datasets/fish_disease_detection/exportMODEL_PATH./runs/detect/train/weights/best.ptexportIMG_SIZE640exportBATCH_SIZE16exportEPOCHS50exportCONF_THRESHOLD0.5TrainingTo train the YOLOv8 model:python train.pyRunning the GUITo run the graphical user interface:python UIProgram/MainProgram.pyUsage TutorialSee 使用教程.xt for detailed usage instructions.### 4. 运行步骤 - **确保数据集路径正确**将你的数据集放在 datasets/fish_disease_detection 目录下。 - **安装必要的库**确保已安装所有所需库。 - **运行代码** - 首先运行训练代码来训练YOLOv8模型 bash python train.py - 然后运行GUI代码来启动检测系统 bash python UIProgram/MainProgram.py ### 5. 模型评估与优化 在训练完成后你可以通过验证集评估模型性能查看mAP平均精度均值和其他指标。根据评估结果调整超参数如学习率、批次大小、图像尺寸等以优化模型性能。 ### 6. 结果分析与可视化 利用内置的方法或自定义脚本来分析结果和可视化预测边界框。这有助于理解模型的表现并识别可能的改进点。 ### 7. 用户界面开发 为了构建用户界面你可以使用Flask或FastAPI等框架创建RESTful服务或者直接用Streamlit这样的快速原型开发工具。上述代码中已经包含了使用PyQt5创建的简单GUI示例。 希望这些信息能帮助你顺利构建基于YOLOv8的鱼病害检测系统。