如何构建一个基于YOLOv8的智慧化工地管理系统,用于工地要素分割与检测
2026/5/15 19:45:08 网站建设 项目流程

如何构建一个基于YOLOv8的智慧化工地管理系统,用于工地要素分割与检测。该系统将涵盖10大要素(工人佩戴安全帽、不佩戴安全帽、预制构件、混凝土运输车、渣土车、搅拌车、挖掘机、压路车、推土车、装载车)

文章目录

    • 以下文字仅供参考:
      • 1. 安装依赖
      • 2. 数据准备
      • 3. 文件内容
        • 3.1 `datasets/construction_site/` 目录
        • 3.2 `Config.py`
        • 3.3 `train.py`
        • 3.4 `detect_tools.py`
        • 3.5 `UIProgram/MainProgram.py`
        • 3.6 `requirements.txt`
        • 3.7 `setup.py`
        • 3.8 `README.md`
    • Training
    • Running the GUI
    • Usage Tutorial

智慧化工地篇,工地要素分割与检测数据集,

包含10大要素(工人佩戴安全帽,不佩戴安全帽,预制构件,构建运输车,渣土车,搅拌车,挖掘机,压路车,推土车,装载车),

共5w张图像,超过8w标注,coco标准格式标注,12GB数据量。

以下文字仅供参考:

如何来构建一个基于YOLOv8的智慧化工地管理系统,用于工地要素分割与检测。该系统将涵盖10大要素(工人佩戴安全帽、不佩戴安全帽、预制构件、混凝土运输车、渣土车、搅拌车、挖掘机、压路车、推土车、装载车),并使用COCO标准格式的数据集进行训练。

以下是完整的代码实现,包括数据加载、模型训练、评估和推理。

1. 安装依赖

首先,确保您已经安装了所需的库,特别是YOLOv8依赖的库。

pipinstalltorch torchvision ultralytics pyqt5 opencv-python

2. 数据准备

假设您的数据集已经按照COCO标准格式进行了标注。具体来说,数据集目录结构如下:

datasets/ └── construction_site/ ├── images/ │ ├── train/ │ └── val/ ├── annotations/ │ ├── instances_train.json │ └── instances_val.json Font/ models/ runs/ save_data/ test-file/ TestFiles/ UIProgram/ 2.py CameraTest.py CITATION.cff Config.py detect_tools.py imgTest.py installPackages.py MainProgram.py requirements.txt setup.py test.py train.py VideoTest.py yolov8n.pt 使用教程.xt 项目文件说明.png

3. 文件内容

3.1datasets/construction_site/目录

假设您的数据集已经按照COCO标准格式进行了标注。具体来说,每个图像对应一个同名的.jpg文件,而标签文件是JSON格式的COCO标准注释文件。

3.2Config.py

配置文件,用于定义数据集路径、模型路径等。

[<title="Config.py">]# Config.pyDATASET_PATH='datasets/construction_site/'MODEL_PATH='runs/detect/train/weights/best.pt'IMG_SIZE=640BATCH_SIZE=16EPOCHS=50CONF_THRESHOLD=0.5
3.3train.py

训练YOLOv8模型的脚本。

[<title="train.py">]fromultralyticsimportYOLOimportos# Load a modelmodel=YOLO('yolov8n.pt')# You can also use other versions like yolov8s.pt, yolov8m.pt, etc.# Define dataset configurationdataset_config=f""" train:{os.path.join(os.getenv('DATASET_PATH','datasets/construction_site/'),'images/train')}val:{os.path.join(os.getenv('DATASET_PATH','datasets/construction_site/'),'images/val')}annotations: train:{os.path.join(os.getenv('DATASET_PATH','datasets/construction_site/'),'annotations/instances_train.json')}val:{os.path.join(os.getenv('DATASET_PATH','datasets/construction_site/'),'annotations/instances_val.json')}"""# Save dataset configuration to a YAML filewithopen('construction_site.yaml','w')asf:f.write(dataset_config)# Train the modelresults=model.train(data='construction_site.yaml',epochs=int(os.getenv('EPOCHS',50)),imgsz=int(os.getenv('IMG_SIZE',640)),batch=int(os.getenv('BATCH_SIZE',16)))
3.4detect_tools.py

用于检测的工具函数。

[<title="detect_tools.py">]fromultralyticsimportYOLOimportcv2importnumpyasnpdefload_model(model_path):returnYOLO(model_path)defdetect_objects(frame,model,conf_threshold=0.5):results=model(frame,conf=conf_threshold)detections=[]forresultinresults:boxes=result.boxes.cpu().numpy()forboxinboxes:r=box.xyxy[0].astype(int)cls=int(box.cls[0])conf=round(float(box.conf[0]),2)label=f"{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)returnframe
3.5UIProgram/MainProgram.py

主程序,使用PyQt5构建图形界面。

[<title="UIProgram/MainProgram.py">]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("Construction Site Detection")self.setGeometry(100,100,800,600)self.central_widget=QWidget()self.setCentralWidget(self.central_widget)self.layout=QVBoxLayout()self.central_widget.setLayout(self.layout)self.label=QLabel()self.layout.addWidget(self.label)self.start_button=QPushButton("Start Detection")self.start_button.clicked.connect(self.start_detection)self.layout.addWidget(self.start_button)self.cap=Noneself.timer=QTimer()self.timer.timeout.connect(self.update_frame)self.model=load_model(os.getenv('MODEL_PATH','runs/detect/train/weights/best.pt'))defstart_detection(self):ifnotself.cap:self.cap=cv2.VideoCapture(0)# Use webcamself.timer.start(30)defupdate_frame(self):ret,frame=self.cap.read()ifnotret:returndetections=detect_objects(frame,self.model,conf_threshold=float(os.getenv('CONF_THRESHOLD',0.5)))frame=draw_detections(frame,detections)rgb_image=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)h,w,ch=rgb_image.shape bytes_per_line=ch*w qt_image=QImage(rgb_image.data,w,h,bytes_per_line,QImage.Format_RGB888)pixmap=QPixmap.fromImage(qt_image)self.label.setPixmap(pixmap.scaled(800,600,Qt.KeepAspectRatio))if__name__=="__main__":app=QApplication(sys.argv)window=VideoWindow()window.show()sys.exit(app.exec_())
3.6requirements.txt

列出所有依赖项。

[<title="requirements.txt">] torch torchvision ultralytics pyqt5 opencv-python
3.7setup.py

用于安装项目的脚本。

[<title="setup.py">]fromsetuptoolsimportsetup,find_packages setup(name='construction_site_detection',version='0.1',packages=find_packages(),install_requires=['torch','torchvision','ultralytics','pyqt5','opencv-python'],entry_points={'console_scripts':['train=train:main','detect=UIProgram.MainProgram:main']})
3.8README.md

项目说明文档。

[<title="README.md">] # Construction Site Detection System This project uses YOLOv8 and PyQt5 to create a real-time construction site detection system. The system detects various elements such as workers wearing safety helmets, concrete transport vehicles, dump trucks, mixers, excavators, rollers, bulldozers, and loaders on a construction site. ## Installation 1. Clone the repository: ```bash git clone https://github.com/yourusername/construction-site-detection.git cd construction-site-detection
  1. Install dependencies:

    pipinstall-rrequirements.txt
  2. Set up environment variables (optional):

    exportDATASET_PATH=./datasets/construction_site/exportMODEL_PATH=./runs/detect/train/weights/best.ptexportIMG_SIZE=640exportBATCH_SIZE=16exportEPOCHS=50exportCONF_THRESHOLD=0.5

Training

To train the YOLOv8 model:

python train.py

Running the GUI

To run the graphical user interface:

python UIProgram/MainProgram.py

Usage Tutorial

See 使用教程.xt for detailed usage instructions.

### 4. 运行步骤 1. **确保数据集路径正确**: - 将您的数据集放在 `datasets/construction_site` 目录下。 - 确保图像和对应的标签文件存在并且格式正确。 2. **安装必要的库**: - 确保您已经安装了所需的库,如 `torch`, `torchvision`, `ultralytics`, `pyqt5`, `opencv-python` 等。 - 您可以使用以下命令安装这些库: ```bash pip install -r requirements.txt ``` 3. **运行代码**: - 首先运行训练代码来训练YOLOv8模型: ```bash python train.py ``` - 然后运行GUI代码来启动检测系统: ```bash python UIProgram/MainProgram.py ``` hope这些信息能帮助您顺利构建基于YOLOv8和PyQt5的智慧化工地管理系统。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询