基于深度学习的火焰与烟雾检测系统(UI界面+YOLOv8/v7/v6/v5代码+训练数据集)
引言

火灾是对人类生命和财产安全的严重威胁,及时检测和报警是减少火灾损失的关键。传统的火焰和烟雾检测方法主要依靠传感器,但这些方法存在检测范围有限和易受环境干扰等问题。随着深度学习技术的快速发展,我们可以利用计算机视觉技术构建一个高效、准确的火焰与烟雾检测系统。本文将详细介绍如何从零开始实现一个基于深度学习的火焰与烟雾检测系统,包括环境搭建、数据集准备、模型训练、系统实现和用户界面设计。

系统概述

本文系统的主要步骤如下:

  1. 环境搭建
  2. 数据收集与处理
  3. 模型训练
  4. 系统实现
  5. 用户界面设计
环境搭建

首先,需要搭建一个合适的开发环境。本文使用Python 3.8或以上版本,并依赖于多个深度学习和图像处理库。

安装必要的库

我们需要安装以下库:

  • numpy: 用于数值计算。
  • pandas: 用于数据处理。
  • matplotlib: 用于数据可视化。
  • opencv-python: 用于图像处理。
  • torchtorchvision: PyTorch深度学习框架。
  • ultralytics: YOLO模型库。
  • PyQt5: 用于构建用户界面。

在命令行中运行以下命令安装这些库:

pip install numpy pandas matplotlib opencv-python
pip install torch torchvision torchaudio
pip install ultralytics
pip install PyQt5
  • 1.
  • 2.
  • 3.
  • 4.
验证安装

安装完成后,可以运行以下代码验证库是否安装成功:

import torch
import cv2
import PyQt5
import ultralytics

print("All packages installed successfully.")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
数据收集与处理

数据是深度学习系统的基础。为了构建一个高效的火焰与烟雾检测系统,我们需要收集并处理火焰与烟雾检测的数据集。

数据收集

我们可以从以下几个途径获取火焰与烟雾检测数据集:

  1. 公开数据集:许多网站提供免费的火焰与烟雾检测数据集,例如Kaggle。
  2. 自定义数据集:通过拍摄火焰和烟雾图片或视频,并进行标注。
数据标注

数据收集完成后,需要对数据进行标注。标注的目的是确定火焰和烟雾在图像中的位置。我们可以使用工具如LabelImg对数据进行标注。

下载并安装LabelImg:

pip install labelImg
  • 1.

启动LabelImg并打开要标注的图片目录:

labelImg
  • 1.

标注完成后,保存标注文件,目录结构如下:

dataset/
  ├── images/
  │   ├── train/
  │   └── val/
  └── labels/
      ├── train/
      └── val/
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
数据预处理

为了提高模型的训练效果,我们需要对数据进行预处理,包括图像的归一化、尺寸调整等。

import os
import cv2

def preprocess_image(image_path, output_path, size=(640, 640)):
    image = cv2.imread(image_path)
    image = cv2.resize(image, size)
    cv2.imwrite(output_path, image)

input_dir = 'path/to/images'
output_dir = 'path/to/preprocessed_images'

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

for image_name in os.listdir(input_dir):
    preprocess_image(os.path.join(input_dir, image_name), os.path.join(output_dir, image_name))
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
模型训练

本文采用YOLOv8模型进行火焰与烟雾检测的训练。YOLO(You Only Look Once)是一种高效的目标检测算法,可以在保持高准确率的同时实现实时检测。

配置YOLO数据集

创建一个YAML文件来配置数据集信息:

# dataset.yaml
train: path/to/train/images
val: path/to/val/images

nc: 2  # 检测火焰和烟雾
names: ['fire', 'smoke']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
训练代码

使用YOLOv8模型进行训练。以下是训练代码示例:

from ultralytics import YOLO

# 加载预训练的YOLOv8模型
model = YOLO('yolov8.yaml')

# 配置训练参数
model.train(data='path/to/dataset.yaml', epochs=50, imgsz=640, batch=16)

# 保存训练后的模型
model.save('best.pt')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
模型评估

在训练完成后,我们需要对模型进行评估,以确定其在测试集上的表现。

results = model.val(data='path/to/dataset.yaml')
print(results)
  • 1.
  • 2.

通过评估结果,我们可以调整模型的参数和训练策略,以进一步提高模型的性能。

系统实现

在训练好模型后,我们需要将其集成到一个完整的系统中,实现实时的火焰与烟雾检测。

火焰与烟雾检测

利用训练好的模型进行火焰与烟雾检测,并实现图片或视频流的实时检测。

import cv2
from ultralytics import YOLO

# 加载训练好的模型
model = YOLO('best.pt')

# 打开视频流
cap = cv2.VideoCapture(0)  # 使用摄像头作为视频输入

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 检测火焰与烟雾
    results = model(frame)
    for result in results:
        bbox = result['bbox']
        label = result['label']
        confidence = result['confidence']
        
        # 画框和标签
        cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 2)
        cv2.putText(frame, f'{label} {confidence:.2f}', (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
    
    # 显示视频
    cv2.imshow('Fire and Smoke Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

上述代码实现了实时视频流中的火焰与烟雾检测。我们可以通过摄像头实时监控火焰和烟雾。

用户界面设计

为了提高系统的易用性,我们需要设计一个用户友好的界面。本文使用PyQt5实现用户界面,提供图片或视频播放和火焰与烟雾检测结果显示。

界面代码

以下是一个简单的PyQt5界面代码示例:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QFileDialog
from PyQt5.QtGui import QPixmap, QImage
import cv2
from ultralytics import YOLO

class FireSmokeDetectionUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
        self.model = YOLO('best.pt')
        
    def initUI(self):
        self.setWindowTitle('Fire and Smoke Detection System')
        
        self.layout = QVBoxLayout()
        
        self.label = QLabel(self)
        self.layout.addWidget(self.label)
        
        self.button = QPushButton('Open Image or Video', self)
        self.button.clicked.connect(self.open_file)
        self.layout.addWidget(self.button)
        
        self.setLayout(self.layout)
    
    def open_file(self):
        options = QFileDialog.Options()
        file_path, _ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files (*);;MP4 Files (*.mp4);;JPEG Files (*.jpg);;PNG Files (*.png)", options=options)
        
        if file_path:
            if file_path.endswith('.mp4'):
                self.detect_fire_smoke_video(file_path)
            else:
                self.detect_fire_smoke_image(file_path)
    
    def detect_fire_smoke_image(self, file_path):
        frame = cv2.imread(file_path)
        results = self.model(frame)
        for result in results:
            bbox = result['bbox']
            label = result['label']
            confidence = result['confidence']
                
            cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 2)
            cv2.putText(frame, f'{label} {confidence:.2f}', (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
            
        height, width, channel =

 frame.shape
        bytesPerLine = 3 * width
        qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
        
        self.label.setPixmap(QPixmap.fromImage(qImg))
    
    def detect_fire_smoke_video(self, file_path):
        cap = cv2.VideoCapture(file_path)
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            
            results = self.model(frame)
            for result in results:
                bbox = result['bbox']
                label = result['label']
                confidence = result['confidence']
                
                cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 2)
                cv2.putText(frame, f'{label} {confidence:.2f}', (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
            
            height, width, channel = frame.shape
            bytesPerLine = 3 * width
            qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
            
            self.label.setPixmap(QPixmap.fromImage(qImg))
            cv2.waitKey(1)
        
        cap.release()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = FireSmokeDetectionUI()
    ex.show()
    sys.exit(app.exec_())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.

上述代码实现了一个简单的PyQt5界面,用户可以通过界面打开图片或视频文件,并实时查看火焰与烟雾检测结果。

进一步优化
数据增强

为了提高模型的泛化能力,可以对训练数据进行数据增强,如随机裁剪、旋转、翻转等。

from torchvision import transforms

data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
超参数调整

通过调整模型的超参数(如学习率、批量大小等),可以进一步提高模型的性能。

model.train(data='path/to/dataset.yaml', epochs=50, imgsz=640, batch=16, lr0=0.01)
  • 1.
模型压缩与加速

为了提高模型的推理速度,可以对模型进行压缩与加速,如量化、剪枝等。

import torch.quantization

# 模型量化
model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
  • 1.
  • 2.
  • 3.
  • 4.
结论与声明

本文详细介绍了如何构建一个基于深度学习的火焰与烟雾检测系统,涵盖了环境搭建、数据收集与处理、模型训练、系统实现和用户界面设计等各个方面。通过结合YOLO模型和PyQt5,我们实现了一个实时、精确的火焰与烟雾检测系统,为消防安全提供了有力支持。