1、?項目源碼和結構(轉)?
https://github.com/mushfiq1998/fire-detection-python-opencv
2、?運行環境
# 安裝playsound:用于播放報警聲音
pip install playsound
# 安裝opencv-python:cv2用于圖像和視頻處理,特別是用于檢測火災
pip install opencv-python
3、?fireDetection.py
import cv2 # Library for openCV
import threading # Library for threading -- which allows code to run in backend
import playsound # Library for alarm sound
import smtplib # Library for email sending# To access xml file which includes positive and negative images of fire.
# (Trained images) File is also provided with the code.
fire_cascade = cv2.CascadeClassifier('fire_detection_cascade_model.xml')# To start camera this command is used "0" for laptop inbuilt camera
# and "1" for USB attahed camera
# vid = cv2.VideoCapture(0) vid = cv2.VideoCapture("videos\\fire2.mp4")
runOnce = False # created boolean# defined function to play alarm post fire detection using threading
def play_alarm_sound_function(): # to play alarm # mp3 audio file is also provided with the code.playsound.playsound('fire_alarm.mp3',True) print("Fire alarm end") # to print in consol# Defined function to send mail post fire detection using threading
def send_mail_function(): recipientmail = "add recipients mail" # recipients mailrecipientmail = recipientmail.lower() # To lower case mailtry:server = smtplib.SMTP('smtp.gmail.com', 587)server.ehlo()server.starttls()# Senders mail ID and passwordserver.login("add senders mail", 'add senders password') # recipients mail with mail messageserver.sendmail('add recipients mail', recipientmail, "Warning fire accident has been reported") # to print in consol to whome mail is sentprint("Alert mail sent sucesfully to {}".format(recipientmail))server.close() ## To close serverexcept Exception as e:print(e) # To print error if anywhile(True):Alarm_Status = False# Value in ret is True # To read video frameret, frame = vid.read() # To convert frame into gray colorgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # to provide frame resolutionfire = fire_cascade.detectMultiScale(frame, 1.2, 5) ## to highlight fire with square for (x,y,w,h) in fire:cv2.rectangle(frame,(x-20,y-20),(x+w+20,y+h+20),(255,0,0),2)roi_gray = gray[y:y+h, x:x+w]roi_color = frame[y:y+h, x:x+w]print("Fire alarm initiated")# To call alarm threadthreading.Thread(target=play_alarm_sound_function).start() if runOnce == False:print("Mail send initiated")# To call alarm threadthreading.Thread(target=send_mail_function).start() runOnce = Trueif runOnce == True:print("Mail is already sent once")runOnce = Truecv2.imshow('frame', frame)if cv2.waitKey(1) & 0xFF == ord('q'):break
- 加載訓練模型:代碼加載預訓練的機器學習模型fire_detection_cascade_model.xml(XML 文件),該模型可以檢測圖像中的火災。
- 設置視頻源:設置視頻輸入源,可以是筆記本電腦內置攝像頭,也可以是外接USB 攝像頭。該代碼當前配置為從名為“fire2.mp4”的文件中讀取視頻。
- 播放報警聲音:定義播放報警聲音的函數play_alarm_sound_function(),該函數在后臺運行(線程)并播放名為“fire_alarm.mp3”的警報聲音文件。
- 發送電子郵件:send_mail_function()定義了另一個函數來發送電子郵件。它使用 Gmail 的 SMTP 服務器向指定收件人發送有關火災檢測的警告電子郵件。代碼中需要提供發件人的電子郵件和密碼。