Skip to main content

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

 

Real-time Fire Detection using Computer Vision and Python in Visual Studio Code-CNN examples.

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 cv2numpypygame, 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()

 

Comments

Popular posts from this blog

Thevenin’s Theorem: A Beginner’s Guide

                                        table of content  Introduction History of Thevenin’s theorem Basic circuit analysis concepts Voltage, current, and resistance Ohm’s law Thevenin’s theorem: principles and applications Statement of the theorem Finding the Thevenin equivalent circuit What is Thevenin’s theorem? When should you use Thevenin’s theorem? How do you apply Thevenin’s theorem to a circuit Conclusion . Introduction Electrical engineers can effectively convert complicated circuits into smaller equivalent circuits by using Thevenin's theorem. The French telegraph engineer Léon Charles Thévenin is honored by having his theorem called in his honor. He proposed it in 1883. History of Thevenin’s theorem Hermann von Helmholtz, a German scientist, independently derived Thevenin's theorem in 1853; Léon Charles Thévenin did ...

WHAT IS WEBSCRAPING IN PYTHON

  Web scraping is a technique that allows you to extract data from websites and store it in a format of your choice. It can be useful for various purposes, such as market research, price comparison, content analysis, and more. In this blog post, i will show you everything a beginner needs to know about web scraping, from the basics to some advanced tips and tricks.   What is web scraping?   Web scraping is the process of programmatically retrieving information from web pages. It involves sending requests to web servers, parsing the html code of the web pages, and extracting the data you want. Web scraping can be done manually, by copying and pasting data from a website, or automatically, by using a software tool or a programming language.   Why web scrape?   Web scraping can help you access data that is not available through an api or a downloadable file. For example, you may want to scrape product reviews from an e-commerce website, or news ...

Study Linear Regression: A Beginner’s Guide with c++

Table of content: • Introduction • What is Linear Regression? • Simple vs. Multiple Linear Regression • Implementing Linear Regression in C++ • Complex Linear Regression • Conclusion • References Understanding Linear Regression: A Beginner’s Guide Linear regression is a powerful statistical tool that allows us to understand the relationship between two or more variables. It is widely used in many fields, including finance, economics, and engineering, to make predictions and analyze data. In this article, we will explore the basics of linear regression, including what it is, how it works, and how to implement it in C++. We will also discuss the differences between simple and multiple linear regression and provide examples to help you understand these concepts. What is Linear Regression? At its core, linear regression is a method for finding the line of best fit that describes the relationship between two continuous variables. This line can be used to make predictions about o...