道路积水数据集 路面积水识别数据集 图片数量4524xml和txt标签都有公路积水数据集✓类别puddle✓图片数量4524xml和txt标签都有✓类别puddle好的下面是一个完整的项目代码和详细配置说明用于基于YOLOv8进行路面积水识别。该项目包括数据集准备、模型训练、评估和推理并附带一个简单的Streamlit界面。完整项目代码1. 数据集准备与转换首先我们需要将数据集从XML格式转换为YOLO格式如果数据集已经是YOLO格式则跳过此步骤。importxml.etree.ElementTreeasETimportosfrompathlibimportPathdefconvert_xml_to_yolo(xml_dir,output_dir):forxml_fileinPath(xml_dir).glob(*.xml):treeET.parse(xml_file)roottree.getroot()img_nameroot.find(filename).text img_widthint(root.find(size/width).text)img_heightint(root.find(size/height).text)txt_file_pathos.path.join(output_dir,Path(img_name).stem.txt)withopen(txt_file_path,w)astxt_file:forobjinroot.findall(object):clsobj.find(name).textifcls!puddle:continuebboxobj.find(bndbox)xminfloat(bbox.find(xmin).text)yminfloat(bbox.find(ymin).text)xmaxfloat(bbox.find(xmax).text)ymaxfloat(bbox.find(ymax).text)x_center(xminxmax)/2/img_width y_center(yminymax)/2/img_height width(xmax-xmin)/img_width height(ymax-ymin)/img_height txt_file.write(f0{x_center}{y_center}{width}{height}\n)# 使用示例convert_xml_to_yolo(datasets/puddle_dataset/xml,datasets/puddle_dataset/yolo/labels)2. 创建数据集配置文件 (data.yaml)创建一个data.yaml文件来配置数据集路径和类别信息。3. 分割数据集为了训练和验证我们需要将数据集分割成训练集和验证集。importosimportrandomfrompathlibimportPathimportshutildefsplit_dataset(data_dir,train_ratio0.8):imageslist(Path(data_dir).glob(*.jpg))random.shuffle(images)num_trainint(len(images)*train_ratio)train_imagesimages[:num_train]val_imagesimages[num_train:]train_dirPath(data_dir).parent/trainval_dirPath(data_dir).parent/valtrain_img_dirtrain_dir/imagestrain_label_dirtrain_dir/labelsval_img_dirval_dir/imagesval_label_dirval_dir/labelstrain_img_dir.mkdir(parentsTrue,exist_okTrue)train_label_dir.mkdir(parentsTrue,exist_okTrue)val_img_dir.mkdir(parentsTrue,exist_okTrue)val_label_dir.mkdir(parentsTrue,exist_okTrue)forimgintrain_images:label_pathimg.with_suffix(.txt)shutil.copy(img,train_img_dir/img.name)shutil.copy(label_path,train_label_dir/label_path.name)forimginval_images:label_pathimg.with_suffix(.txt)shutil.copy(img,val_img_dir/img.name)shutil.copy(label_path,val_label_dir/label_path.name)# 使用示例split_dataset(./datasets/puddle_dataset/images)4. 训练脚本接下来是使用YOLOv8进行训练的脚本。importtorchfromultralyticsimportYOLO# 设置随机种子以保证可重复性torch.manual_seed(42)# 定义数据集路径dataset_configdata.yaml# 加载预训练的YOLOv8n模型modelYOLO(yolov8n.pt)# 训练模型resultsmodel.train(datadataset_config,epochs100,imgsz512,batch16,namepuddle_detection,projectruns/train)# 评估模型metricsmodel.val()# 保存最佳模型权重best_model_weightsruns/train/puddle_detection/weights/best.ptprint(fBest model weights saved to{best_model_weights})5. 推理脚本以下是一个简单的推理脚本用于测试模型的性能。fromultralyticsimportYOLOimportcv2importnumpyasnpfromPILimportImage# 加载模型modelYOLO(runs/train/puddle_detection/weights/best.pt)# 图片检测函数defdetect_image(model,image_path,conf_threshold0.5):resultsmodel.predict(image_path,confconf_threshold)[0]annotated_frameannotate_image(image_path,results,model)returnannotated_frame# 标注图像函数defannotate_image(image_path,results,model):framecv2.imread(image_path)forresultinresults.boxes.cpu().numpy():rresult.xyxy[0].astype(int)clsint(result.cls[0])confresult.conf[0]labelf{model.names[cls]}{conf:.2f}color(0,255,0)cv2.rectangle(frame,(r[0],r[1]),(r[2],r[3]),color,2)cv2.putText(frame,label,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,color,2)returnframe# 测试一张图片test_image_path./datasets/puddle_dataset/images/test_image.jpgannotated_imagedetect_image(model,test_image_path)cv2.imwrite(annotated_test_image.jpg,annotated_image)6. Streamlit 主界面最后我们创建一个简单的Streamlit界面来进行实时推理和显示结果。importstreamlitasstfromultralyticsimportYOLOimportcv2importnumpyasnpfromPILimportImageimporttempfile# 加载模型st.cache_resourcedefload_model(weights_path):modelYOLO(weights_path)returnmodel# 图片检测函数defdetect_image(model,image,conf_threshold):resultsmodel.predict(image,confconf_threshold)[0]annotated_frameannotate_image(image,results,model)returnannotated_frame# 视频检测函数defdetect_video(model,video_path,conf_threshold):capcv2.VideoCapture(video_path)whilecap.isOpened():ret,framecap.read()ifnotret:breakresultsmodel.predict(frame,confconf_threshold)[0]annotated_frameannotate_image(frame,results,model)yieldannotated_frame cap.release()# 摄像头检测函数defdetect_camera(model,conf_threshold):capcv2.VideoCapture(0)whileTrue:ret,framecap.read()ifnotret:breakresultsmodel.predict(frame,confconf_threshold)[0]annotated_frameannotate_image(frame,results,model)yieldannotated_frame cap.release()# 标注图像函数defannotate_image(image,results,model):forresultinresults.boxes.cpu().numpy():rresult.xyxy[0].astype(int)clsint(result.cls[0])confresult.conf[0]labelf{model.names[cls]}{conf:.2f}color(0,255,0)cv2.rectangle(image,(r[0],r[1]),(r[2],r[3]),color,2)cv2.putText(image,label,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,color,2)returnimage# Streamlit 主界面defmain():st.title(Puddle Detection System)# 动态加载模型weights_options[best_puddle_yolov8.pt]# 添加更多权重文件路径selected_weightsst.sidebar.selectbox(Select Model Weights,weights_options)modelload_model(selected_weights)# 动态调整置信度阈值conf_thresholdst.sidebar.slider(Confidence Threshold,min_value0.0,max_value1.0,value0.5,step0.01)# 输入方式选择input_typest.sidebar.radio(Input Type,[Image,Video,Camera])ifinput_typeImage:uploaded_filest.file_uploader(Upload an image...,type[jpg,jpeg,png])ifuploaded_fileisnotNone:imageImage.open(uploaded_file)image_npnp.array(image)annotated_imagedetect_image(model,image_np,conf_threshold)st.image(annotated_image,channelsBGR,captionDetected Image)# 统计检测到的物体数量resultsmodel.predict(image_np,confconf_threshold)[0]class_counts{}forresultinresults.boxes.cpu().numpy():clsint(result.cls[0])class_namemodel.names[cls]ifclass_nameinclass_counts:class_counts[class_name]1else:class_counts[class_name]1st.subheader(Detection Summary:)forclass_name,countinclass_counts.items():st.write(f{class_name}:{count})elifinput_typeVideo:uploaded_filest.file_uploader(Upload a video...,type[mp4,avi])ifuploaded_fileisnotNone:tfiletempfile.NamedTemporaryFile(deleteFalse)tfile.write(uploaded_file.read())tfpathtfile.name capcv2.VideoCapture(tfpath)frame_placeholderst.empty()forannotated_frameindetect_video(model,tfpath,conf_threshold):frame_placeholder.image(annotated_frame,channelsBGR,use_column_widthTrue)cap.release()os.remove(tfpath)elifinput_typeCamera:frame_placeholderst.empty()forannotated_frameindetect_camera(model,conf_threshold):frame_placeholder.image(annotated_frame,channelsBGR,use_column_widthTrue)if__name____main__:main()文件结构puddle_detection/ ├── main.py ├── datasets/ │ └── puddle_dataset/ │ ├── xml/ │ │ ├── image1.xml │ │ ├── image2.xml │ │ └── ... │ ├── yolo/ │ │ ├── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── ... │ │ ├── train/ │ │ │ ├── images/ │ │ │ │ ├── image1.jpg │ │ │ │ ├── image2.jpg │ │ │ │ └── ... │ │ │ └── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── ... │ │ └── val/ │ │ ├── images/ │ │ │ ├── image1.jpg │ │ │ ├── image2.jpg │ │ │ └── ... │ │ └── labels/ │ │ ├── image1.txt │ │ ├── image2.txt │ │ └── ... │ └── images/ │ ├── image1.jpg │ ├── image2.jpg │ └── ... ├── best_puddle_yolov8.pt └── requirements.txt安装依赖项首先确保你已经安装了所有必要的依赖项。你可以通过以下命令安装pipinstall-rrequirements.txtrequirements.txt内容如下streamlit1.25.0 opencv-python torch2.0 ultralytics运行步骤总结克隆项目仓库如果有的话gitclone https://github.com/yourusername/puddle_detection.gitcdpuddle_detection安装依赖项pipinstall-rrequirements.txt数据集准备如果数据集尚未转换请运行数据集转换脚本。python convert_xml_to_yolo.py如果数据集尚未分割请运行数据集分割脚本。python split_dataset.py确保数据集目录结构正确。训练模型python train.py评估模型在训练脚本中模型会在训练结束后自动进行评估。推理测试python inference.py运行Streamlit应用streamlit run main.py总结以上是完整的基于YOLOv8的路面积水识别系统的项目介绍和代码实现。该项目支持图片、视频识别以及本地摄像头识别并且可以通过UI界面动态调节模型置信度和选择不同的模型权重。希望这些详细的信息和代码能够帮助你顺利实施和优化你的路面积水识别系统。
道路积水数据集 路面积水识别数据集 图片数量4524,xml和txt标签都有;公路积水数据集 ✓类别:puddle;
发布时间:2026/6/4 7:30:11
道路积水数据集 路面积水识别数据集 图片数量4524xml和txt标签都有公路积水数据集✓类别puddle✓图片数量4524xml和txt标签都有✓类别puddle好的下面是一个完整的项目代码和详细配置说明用于基于YOLOv8进行路面积水识别。该项目包括数据集准备、模型训练、评估和推理并附带一个简单的Streamlit界面。完整项目代码1. 数据集准备与转换首先我们需要将数据集从XML格式转换为YOLO格式如果数据集已经是YOLO格式则跳过此步骤。importxml.etree.ElementTreeasETimportosfrompathlibimportPathdefconvert_xml_to_yolo(xml_dir,output_dir):forxml_fileinPath(xml_dir).glob(*.xml):treeET.parse(xml_file)roottree.getroot()img_nameroot.find(filename).text img_widthint(root.find(size/width).text)img_heightint(root.find(size/height).text)txt_file_pathos.path.join(output_dir,Path(img_name).stem.txt)withopen(txt_file_path,w)astxt_file:forobjinroot.findall(object):clsobj.find(name).textifcls!puddle:continuebboxobj.find(bndbox)xminfloat(bbox.find(xmin).text)yminfloat(bbox.find(ymin).text)xmaxfloat(bbox.find(xmax).text)ymaxfloat(bbox.find(ymax).text)x_center(xminxmax)/2/img_width y_center(yminymax)/2/img_height width(xmax-xmin)/img_width height(ymax-ymin)/img_height txt_file.write(f0{x_center}{y_center}{width}{height}\n)# 使用示例convert_xml_to_yolo(datasets/puddle_dataset/xml,datasets/puddle_dataset/yolo/labels)2. 创建数据集配置文件 (data.yaml)创建一个data.yaml文件来配置数据集路径和类别信息。3. 分割数据集为了训练和验证我们需要将数据集分割成训练集和验证集。importosimportrandomfrompathlibimportPathimportshutildefsplit_dataset(data_dir,train_ratio0.8):imageslist(Path(data_dir).glob(*.jpg))random.shuffle(images)num_trainint(len(images)*train_ratio)train_imagesimages[:num_train]val_imagesimages[num_train:]train_dirPath(data_dir).parent/trainval_dirPath(data_dir).parent/valtrain_img_dirtrain_dir/imagestrain_label_dirtrain_dir/labelsval_img_dirval_dir/imagesval_label_dirval_dir/labelstrain_img_dir.mkdir(parentsTrue,exist_okTrue)train_label_dir.mkdir(parentsTrue,exist_okTrue)val_img_dir.mkdir(parentsTrue,exist_okTrue)val_label_dir.mkdir(parentsTrue,exist_okTrue)forimgintrain_images:label_pathimg.with_suffix(.txt)shutil.copy(img,train_img_dir/img.name)shutil.copy(label_path,train_label_dir/label_path.name)forimginval_images:label_pathimg.with_suffix(.txt)shutil.copy(img,val_img_dir/img.name)shutil.copy(label_path,val_label_dir/label_path.name)# 使用示例split_dataset(./datasets/puddle_dataset/images)4. 训练脚本接下来是使用YOLOv8进行训练的脚本。importtorchfromultralyticsimportYOLO# 设置随机种子以保证可重复性torch.manual_seed(42)# 定义数据集路径dataset_configdata.yaml# 加载预训练的YOLOv8n模型modelYOLO(yolov8n.pt)# 训练模型resultsmodel.train(datadataset_config,epochs100,imgsz512,batch16,namepuddle_detection,projectruns/train)# 评估模型metricsmodel.val()# 保存最佳模型权重best_model_weightsruns/train/puddle_detection/weights/best.ptprint(fBest model weights saved to{best_model_weights})5. 推理脚本以下是一个简单的推理脚本用于测试模型的性能。fromultralyticsimportYOLOimportcv2importnumpyasnpfromPILimportImage# 加载模型modelYOLO(runs/train/puddle_detection/weights/best.pt)# 图片检测函数defdetect_image(model,image_path,conf_threshold0.5):resultsmodel.predict(image_path,confconf_threshold)[0]annotated_frameannotate_image(image_path,results,model)returnannotated_frame# 标注图像函数defannotate_image(image_path,results,model):framecv2.imread(image_path)forresultinresults.boxes.cpu().numpy():rresult.xyxy[0].astype(int)clsint(result.cls[0])confresult.conf[0]labelf{model.names[cls]}{conf:.2f}color(0,255,0)cv2.rectangle(frame,(r[0],r[1]),(r[2],r[3]),color,2)cv2.putText(frame,label,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,color,2)returnframe# 测试一张图片test_image_path./datasets/puddle_dataset/images/test_image.jpgannotated_imagedetect_image(model,test_image_path)cv2.imwrite(annotated_test_image.jpg,annotated_image)6. Streamlit 主界面最后我们创建一个简单的Streamlit界面来进行实时推理和显示结果。importstreamlitasstfromultralyticsimportYOLOimportcv2importnumpyasnpfromPILimportImageimporttempfile# 加载模型st.cache_resourcedefload_model(weights_path):modelYOLO(weights_path)returnmodel# 图片检测函数defdetect_image(model,image,conf_threshold):resultsmodel.predict(image,confconf_threshold)[0]annotated_frameannotate_image(image,results,model)returnannotated_frame# 视频检测函数defdetect_video(model,video_path,conf_threshold):capcv2.VideoCapture(video_path)whilecap.isOpened():ret,framecap.read()ifnotret:breakresultsmodel.predict(frame,confconf_threshold)[0]annotated_frameannotate_image(frame,results,model)yieldannotated_frame cap.release()# 摄像头检测函数defdetect_camera(model,conf_threshold):capcv2.VideoCapture(0)whileTrue:ret,framecap.read()ifnotret:breakresultsmodel.predict(frame,confconf_threshold)[0]annotated_frameannotate_image(frame,results,model)yieldannotated_frame cap.release()# 标注图像函数defannotate_image(image,results,model):forresultinresults.boxes.cpu().numpy():rresult.xyxy[0].astype(int)clsint(result.cls[0])confresult.conf[0]labelf{model.names[cls]}{conf:.2f}color(0,255,0)cv2.rectangle(image,(r[0],r[1]),(r[2],r[3]),color,2)cv2.putText(image,label,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,color,2)returnimage# Streamlit 主界面defmain():st.title(Puddle Detection System)# 动态加载模型weights_options[best_puddle_yolov8.pt]# 添加更多权重文件路径selected_weightsst.sidebar.selectbox(Select Model Weights,weights_options)modelload_model(selected_weights)# 动态调整置信度阈值conf_thresholdst.sidebar.slider(Confidence Threshold,min_value0.0,max_value1.0,value0.5,step0.01)# 输入方式选择input_typest.sidebar.radio(Input Type,[Image,Video,Camera])ifinput_typeImage:uploaded_filest.file_uploader(Upload an image...,type[jpg,jpeg,png])ifuploaded_fileisnotNone:imageImage.open(uploaded_file)image_npnp.array(image)annotated_imagedetect_image(model,image_np,conf_threshold)st.image(annotated_image,channelsBGR,captionDetected Image)# 统计检测到的物体数量resultsmodel.predict(image_np,confconf_threshold)[0]class_counts{}forresultinresults.boxes.cpu().numpy():clsint(result.cls[0])class_namemodel.names[cls]ifclass_nameinclass_counts:class_counts[class_name]1else:class_counts[class_name]1st.subheader(Detection Summary:)forclass_name,countinclass_counts.items():st.write(f{class_name}:{count})elifinput_typeVideo:uploaded_filest.file_uploader(Upload a video...,type[mp4,avi])ifuploaded_fileisnotNone:tfiletempfile.NamedTemporaryFile(deleteFalse)tfile.write(uploaded_file.read())tfpathtfile.name capcv2.VideoCapture(tfpath)frame_placeholderst.empty()forannotated_frameindetect_video(model,tfpath,conf_threshold):frame_placeholder.image(annotated_frame,channelsBGR,use_column_widthTrue)cap.release()os.remove(tfpath)elifinput_typeCamera:frame_placeholderst.empty()forannotated_frameindetect_camera(model,conf_threshold):frame_placeholder.image(annotated_frame,channelsBGR,use_column_widthTrue)if__name____main__:main()文件结构puddle_detection/ ├── main.py ├── datasets/ │ └── puddle_dataset/ │ ├── xml/ │ │ ├── image1.xml │ │ ├── image2.xml │ │ └── ... │ ├── yolo/ │ │ ├── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── ... │ │ ├── train/ │ │ │ ├── images/ │ │ │ │ ├── image1.jpg │ │ │ │ ├── image2.jpg │ │ │ │ └── ... │ │ │ └── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── ... │ │ └── val/ │ │ ├── images/ │ │ │ ├── image1.jpg │ │ │ ├── image2.jpg │ │ │ └── ... │ │ └── labels/ │ │ ├── image1.txt │ │ ├── image2.txt │ │ └── ... │ └── images/ │ ├── image1.jpg │ ├── image2.jpg │ └── ... ├── best_puddle_yolov8.pt └── requirements.txt安装依赖项首先确保你已经安装了所有必要的依赖项。你可以通过以下命令安装pipinstall-rrequirements.txtrequirements.txt内容如下streamlit1.25.0 opencv-python torch2.0 ultralytics运行步骤总结克隆项目仓库如果有的话gitclone https://github.com/yourusername/puddle_detection.gitcdpuddle_detection安装依赖项pipinstall-rrequirements.txt数据集准备如果数据集尚未转换请运行数据集转换脚本。python convert_xml_to_yolo.py如果数据集尚未分割请运行数据集分割脚本。python split_dataset.py确保数据集目录结构正确。训练模型python train.py评估模型在训练脚本中模型会在训练结束后自动进行评估。推理测试python inference.py运行Streamlit应用streamlit run main.py总结以上是完整的基于YOLOv8的路面积水识别系统的项目介绍和代码实现。该项目支持图片、视频识别以及本地摄像头识别并且可以通过UI界面动态调节模型置信度和选择不同的模型权重。希望这些详细的信息和代码能够帮助你顺利实施和优化你的路面积水识别系统。