Real-time AI Fire Detection using Computer Vision and Python in Visual Studio Code

picture of the screen detecting fire

 

This code is a fire detection
program that uses computer vision techniques to detect fire in real-time
through a webcam. The program is written in Python and uses several libraries,
including cv2, numpy, pygame, and threading.

Introduction

The program starts by importing
the necessary libraries. cv2 is the OpenCV library for
Python, which provides tools for real-time computer vision . numpy is a
library for working with arrays of numerical data . pygame is a library for creating multimedia applications, such as video
games, using Python . Finally, threading is a module that provides
tools for working with threads in Python .

Setting up a Virtual Environment
in Visual Studio Code

Before running the code, it is recommended to set up a virtual
environment in Visual Studio Code (VSCode). A virtual environment is an
isolated Python environment that allows you to install packages specific to
your project without affecting other projects or the global Python
installation.

Here are the steps to set up a virtual environment in VSCode:

  1. Open the Command Palette by
    pressing Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS).
  2. Type Python:
    Select Interpreter and
    press Enter.
  3. In the list of available interpreters,
    select Enter interpreter path.
  4. Select Find… and
    navigate to the Python interpreter you want to use for your virtual
    environment.
  5. Open the Command Palette again and
    type Python: Create Terminal. This will create a new terminal that is
    activated with the selected interpreter.
  6. In the new terminal, type python -m venv .venv to create a new virtual environment in a folder named .venv within
    your workspace.
  7. To activate the virtual environment,
    type .venv\Scripts\activate (Windows) or source .venv/bin/activate (macOS/Linux) in the terminal.

After activating the virtual
environment, you can use pip to install packages
specific to your project. These packages will be installed in the .venv folder
and will not affect other projects or the global Python installation.

For more information on using Python environments in VSCode, see Using Python Environments in Visual Studio Code .

Initializing Variables

After importing the libraries
and setting up a virtual environment, the program initializes several
variables. Alarm_Status is a boolean variable that
keeps track of whether the alarm is currently on or off. Fire_Reported is an integer variable that counts the number of times fire has
been detected.

Defining Functions

The program defines two
functions: play_alarm_sound_function() and stop_alarm_sound_function(). These functions use the pygame library to play and stop an alarm sound, respectively.

Capturing Video

The program then captures video
from the webcam using the cv2.VideoCapture() function. The argument
passed to this function specifies which camera to use; in this case, the
default camera (index 0) is used.

Processing Video Frames

The program enters an infinite loop to process each frame of the video.
Within this loop, several operations are performed on each frame.

First, the frame is resized
using the cv2.resize() function. Then, it is
blurred using the cv2.GaussianBlur() function to reduce
high-frequency noise. The blurred frame is then converted from BGR
(blue-green-red) color space to HSV (hue-saturation-value) color space using
the cv2.cvtColor() function.

Next, a mask is created by
thresholding the HSV image using the cv2.inRange() function. This mask
specifies which pixels in the image are within a specified range of HSV values
(in this case, values that correspond to the color of fire). The mask is then
used to create an output image that shows only the pixels within this range.

The program then counts the
number of non-zero pixels in the mask using the cv2.countNonZero() function. If this number exceeds a certain threshold (in this
case, 15000), it is assumed that fire has been detected in the frame.

If fire has been detected and
the alarm is not currently on, a new thread is started using the threading.Thread() function to play the alarm sound. If fire has not been detected
and the alarm is currently on, another thread is started to stop the alarm
sound.

Finally,
the output image is displayed using the 
cv2.imshow() function. The program waits for
1 millisecond for a key press using the 
cv2.waitKey() function. If the ‘q’ key is
pressed, the loop is exited and the program ends.

Conclusion

This code
demonstrates how computer vision techniques can be used to detect fire in
real-time using a webcam. It makes use of several libraries, including OpenCV (
cv2), NumPy (numpy), Pygame (pygame), and threading (threading) to perform image processing, play
sounds, and run tasks concurrently. Before running the code, it is recommended
to set up a virtual environment in Visual Studio Code to isolate the packages
required for this project.

 Master c++ with examples on cnn and arduino here.

code:

 
import cv2
import numpy as np
import pygame
import threading

 

pygame.mixer.init()

 

Alarm_Status = False
Fire_Reported = 0

 

def play_alarm_sound_function():
    pygame.mixer.music.load(‘C:/Users/maryc/Desktop/ppythonnnn/.vscode/Alarm Sound.mp3’)
    pygame.mixer.music.play(1)

 

def stop_alarm_sound_function():
    pygame.mixer.music.stop()

 

video = cv2.VideoCapture(0) # If you want to use webcam, use index like 0, 1, etc.

 

while True:
    (grabbed, frame) = video.read()
    if not grabbed:
        break
    frame = cv2.resize(frame, (960, 540))
    blur = cv2.GaussianBlur(frame, (21, 21), 0)
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
    lower = [18, 50, 50]
    upper = [35, 255, 255]
    lower = np.array(lower, dtype=“uint8”)
    upper = np.array(upper, dtype=“uint8”)
    mask = cv2.inRange(hsv, lower, upper)
    output = cv2.bitwise_and(frame, hsv, mask=mask)
    no_red = cv2.countNonZero(mask)
    if int(no_red) > 15000:
        Fire_Reported = Fire_Reported + 1
        if not Alarm_Status:
            threading.Thread(target=play_alarm_sound_function).start()
            Alarm_Status = True
    else:
        if Alarm_Status:
            threading.Thread(target=stop_alarm_sound_function).start()
            Alarm_Status = False
    cv2.imshow(“output”, output)
    if cv2.waitKey(1) & 0xFF == ord(‘q’):
        break

 

cv2.destroyAllWindows()
video.release()

 

Leave a comment

Hey!

Hello, I’m Maryclare. Dive into the world of technology with my Udemy courses, “Master C++ with Arduino/CNN” and “100 Projects with Web Scraping”. Join over 3000+ students in mastering tech skills that matter. Let’s explore, learn, and create together.

Join the club

Stay updated with our latest tips and other news by joining our newsletter.

Design a site like this with WordPress.com
Get started