You are on page 1of 45

FIRE DETECTION

Project report submitted in partial fulfillment of the requirements for the


award of Bachelor of Science (Computer Science)
of Bharathiar University, Coimbatore-46.

Submitted by
Mr. Rosekumar.V
(Reg. No. 2122J0854)

Under the guidance of


Dr. N. Kamalraj, MCA, M.Phil., (Ph.D.)
Associate Professor & Head,
Department of Computer Science

SUGUNA COLLEGE OF ARTS AND SCIENCE


(Affiliated to Bharathiar University)
Nehru Nagar, Kalapatti Road,
Coimbatore-641014, Tamil Nadu.
E.Mail: sugunacas@gmail.com
Website: sugunacas.ac.in

April 2024
PROJECT WORK
FIRE DETECTION

Bonafide Work Done by

Mr. Rosekumar.V
Reg. No. 2122J0854

Project report submitted in partial fulfillment of the requirements for the


award of Bachelor of Science (Computer Science)
of Bharathiar University, Coimbatore-46.

Signature of the Guide Signature of the HOD

Submitted for the Viva-voce Examination held on ________________

Internal Examiner External Exminer

April 2024
DECLARATION

I,Mr.Rosekumar.V, hereby declare that the project entitled “FIRE DETECTION”


submitted to the Bharathiar University, Coimbatore in partial fulfillment of the requirements
for the award of the Degree of Bachelor of Computer Application is a record of original
project work done by me during the period of 2023-2024 under the supervision and guidance
of Dr. N. Kamalraj, MCA, M.Phil., Ph.D., Associate Professor & Head, Department of
Computer Science, Suguna College of Arts and Science, Coimbatore and it has not
formed on the basis for the award of any Degree/ Diploma/ Associate ship/ Fellowship or
other similar title to any candidate of any University.

Date: Signature of the Candidate


Place: Coimbatore Mr. Rosekumar.V
(Reg. No. 2122J0854)
ACKNOWLEDGEMENT

I take great pleasure in acknowledging the noble hearts who lent their helping hands for the
successful completion of my project. I also extend my gratitude to all those who contributed
directly and indirectly to the success of this project.

I am profoundly thankful to Shri. V. Lakshminarayanaswamy, Chairman, Suguna Group of


Institutions, Coimbatore for providing me with the opportunity to undertake and successfully
complete this project work.

Deep thanks are extended to Smt. L. Suguna, President, Suguna Group of Institutions,
Coimbatore who also offered me the chance to undertake and successfully complete this
project work.

Sincere appreciation goes to Dr. Srikanth Kannan, Secretary, Suguna Group of Institutions,
Coimbatore for his full support and cooperation, enabling the success of this project and
granting permission to utilize various facilities.

I express my heartfelt thanks to Dr. V. Sekar, Director, Suguna College of Arts and Science,
Coimbatore for encouraging me throughout the project work.

I take this opportunity to thank Dr. R. Rajkumar, M.Com., MBA., M.Phil., Ph.D.,
Principal Suguna College of Arts and Science, Coimbatore for his unwavering support and
assistance in completing this project.

I express my deep gratitude and respect to my guide, Dr. N. Kamalraj, MCA, M.Phil.,
Ph.D., Associate Professor & Head, Department of Computer Science, Suguna College of
Arts and Science, Coimbatore, for his valuable suggestions and timely guidance, which
played a pivotal role in streamlining the successful completion of this project.
SYNOPSIS
In addition to the foundational elements described, the Python script offers a robust
framework for real-time fire detection and management. Its modular architecture promotes
scalability and extensibility, enabling easy integration of additional features or enhancements
to meet specific requirements.

One notable aspect is the utilization of threading to handle concurrent tasks effectively. By
offloading resource-intensive operations such as alarm sound playback and email notification
sending to separate threads, the script maintains responsiveness and ensures smooth
execution without blocking the main thread. This approach enhances the overall
responsiveness of the system, particularly in scenarios where multiple operations need to be
performed simultaneously.

Furthermore, the integration of Matplotlib's `FuncAnimation` for live visualization of the


webcam feed enhances the user experience and facilitates real-time monitoring of potential
fire incidents. This feature not only provides immediate feedback to the user but also enables
prompt decision-making and intervention in case of emergency situations.

Moreover, the script's adaptive approach to fire detection, based on color segmentation in the
HSV color space, demonstrates versatility and robustness across different lighting conditions.
By setting appropriate thresholds for red pixel counts, the script effectively identifies
potential fire outbreaks while minimizing false positives and negatives. This ensures reliable
detection performance in various environments, enhancing the system's effectiveness and
reliability.

Additionally, the script's integration with a SQLite database enables seamless storage and
retrieval of fire detection data, facilitating comprehensive analysis and reporting. This
functionality is particularly valuable for long-term monitoring and trend analysis, enabling
stakeholders to identify patterns, assess risks, and implement proactive measures to enhance
fire safety.

Despite its limitations, such as assumptions regarding the webcam configuration and
hardcoded email credentials, the script serves as a solid foundation for building advanced fire
detection systems. With further refinement and customization, including addressing security
concerns and optimizing performance, the script can be adapted for practical use in various
applications, ranging from home security to industrial fire safety monitoring. Overall, it
exemplifies the power of Python in developing robust and scalable solutions for real-world
challenges.

TABLE OF CONTENTS

S. No. Description Page No.


ACKNOWLEDGEMENT
SYNOPSIS
CONTENTS

1 INTRODUCTION
1.1 OVERVIEW OF THE PROJECT
1.2 SYSTEM SPECIFICATION
1.2.1 HARDWARE CONFIGURATION
1.2.2 SOFTWARE SPECIFICATION

2 SYSTEM STUDY
2.1 EXISTING SYSTEM
2.1.1 DRAWBACKS OF EXISTING SYSTEM
2.2 PROPOSED SYSTEM
2.2.1 FEATURES OF PROPOSED SYSTEM

3 SYSTEM DESIGN AND DEVELOPMENT


3.1 DATA FLOW DIAGRAM
3.2 INPUT DESIGN
3.3 OUTPUT DESIGN
3.4 DATABASE DESIGN
3.5 SYSTEM DEVELOPMENT
3.5.1 DESCRIPTION OF MODULES

4 TESTING AND IMPLEMENTATION

5 CONCLUSION
5.1 BIBLIOGRAPHY

5.2 APPENDICES
A. DATA FLOW DIAGRAM
B. TABLE STRUCTURE
C. SAMPLE CODING
D. FORM DESIGN
CHAPTER 1
1. INTRODUCTION

The provided code appears to be a part of a project focused on real-time fire detection and
alerting system. This system integrates computer vision techniques, email notifications,
sound alarms, and database management to detect instances of fire through a camera feed,
and subsequently alert relevant parties about the occurrence.

The project utilizes OpenCV, a computer vision library, to process frames captured from a
camera in real-time. It applies image processing techniques to identify regions in the frame
that exhibit characteristics resembling fire. Upon detecting such regions, it triggers a series of
actions including activating an alarm sound and sending email notifications to designated
recipients, such as the property owner and local fire station.

Additionally, the system maintains a SQLite database to record instances of fire detection,
providing a log of events for future reference or analysis. Threading is employed to ensure
that different tasks, such as playing the alarm sound and sending emails, can be executed
concurrently without blocking the main program flow.

Furthermore, the system includes a timeout mechanism that closes the output window if no
fire is detected for a specified duration, enhancing efficiency and resource management.

In summary, this project demonstrates an intelligent fire detection and alerting system that
leverages computer vision, email communication, sound alerts, and database management to
enhance safety and response mechanisms in fire-related incidents.

1.1 OVERVIEW OF THE PROJECT

This project represents a comprehensive solution for fire detection and monitoring leveraging
computer vision and real-time data processing. It addresses the critical need for early fire
detection in various environments, including homes, offices, and industrial facilities, to
mitigate the risk of property damage and ensure occupant safety.
At its core, the system continuously captures video frames from a camera feed, employing
sophisticated image processing techniques such as Gaussian blur and color thresholding in
the HSV color space to identify regions indicative of fire. By analyzing pixel intensities and
color distributions, the system can reliably differentiate between normal scenes and potential
fire incidents.

Upon detecting a fire, the system activates multiple response mechanisms in parallel. Firstly,
it triggers an alarm to alert nearby individuals, drawing immediate attention to the emergency
situation. Simultaneously, the system initiates an email notification process, notifying both
the property owner and designated emergency responders, typically local fire stations. This
multi-tiered alert system ensures that relevant stakeholders are promptly informed, enabling
swift response actions to contain the fire and minimize its impact.

Furthermore, the system incorporates intelligent mechanisms to handle prolonged periods


without fire detection. By monitoring the time elapsed since the last detection, it can identify
situations where the absence of fire signals a potential issue, such as system malfunction or
environmental changes. In such cases, the system proactively closes the monitoring interface,
conserving resources and alerting administrators to investigate and resolve any underlying
issues.

Central to the system's functionality is its integration with a database management system,
facilitating the storage and retrieval of fire detection events. By maintaining a comprehensive
log of incidents, including timestamps and detection outcomes, the system enables
retrospective analysis, performance evaluation, and trend identification. This historical data
also serves as a valuable resource for future system enhancements and optimization efforts.

Overall, this project represents a robust and scalable solution for fire detection and
monitoring, offering real-time responsiveness, proactive alerting, and comprehensive event
logging capabilities. By combining advanced computer vision techniques with intelligent
alerting mechanisms and database management, the system contributes significantly to
enhancing fire safety and emergency response readiness across diverse environments.
1.2 SYSTEM SPECIFICATION

This project involves developing a straightforward fire detection system using Python and
basic computer vision techniques, making it accessible for various environments. The
hardware requirements are minimal, only needing a standard webcam and a basic computer
setup with speakers for alarm alerts. For the software, Python serves as the primary language,
with essential libraries such as OpenCV for image processing, Matplotlib for visualization,
NumPy for numerical operations, SQLite3 for database management, and additional utilities
like Pygame and smtplib for alarms and email notifications.

The system's architecture is designed for simplicity, comprising modules responsible for
capturing video frames, analyzing them for potential fire indicators, detecting fire incidents,
issuing alerts through audible alarms and emails, maintaining a log of fire events, and
providing an intuitive user interface for real-time monitoring.

Functional requirements emphasize the system's ability to accurately detect fires while
minimizing false alarms, promptly notify users through alarms and emails upon detection,
maintain a comprehensive record of fire events for reference, and offer a user-friendly
interface for ease of use.

To validate the system's effectiveness, standard testing methodologies such as unit testing for
individual components, integration testing to ensure seamless interaction between modules,
and real-world validation tests to evaluate performance in practical scenarios are employed.
Deployment procedures involve setting up system components, providing user training, and
establishing maintenance protocols for ongoing functionality.
In essence, this project aims to deliver a user-friendly fire detection solution that enhances
safety across diverse environments through its simplicity and reliability.
1.2.1 HARDWARE CONFIGURATION
 Processor: AMD PRO A4-4350B R4, 5 COMPUTE CORES 2C +3G 2.50 GHz
 RAM: Usually ranging from 4GB
 Storage: Hard disk drives (HDD) with capacities ranging from 500GB to 1TB
 Graphics: Integrated graphics for basic multimedia and light gaming.
 Display: Standard screen sizes (14 to 15.6 inches) with HD resolution.
 Webcam: Integrated webcam for video calls and conferencing.
 Resolution: Standard HD resolution, often around 720p or 0.9 megapixels.

1.2.2 SOFTWARE CONFIGURATION


 Programming Languages:
 Python 3.12
 Sqlite 3.45.2
 Libraries:
 OpenCV: Used for capturing and processing video frames.
 Matplotlib: Used for visualizing video frames.
 NumPy: Used for numerical operations.
 SQLite3: Used for managing the database.
 Pygame: Used for playing alarm sounds.
 smtplib: Used for sending email notifications
 IDE:
 Visual Studio Code
 Command prompt
 Operating System:
 Windows 8,10.
 Dependencies:
 Requires an alarm sound file ('alarm-sound.mp3').
 Gmail account credentials for sending email notifications.
 Email addresses of recipients for fire alerts.
CHAPTER 2
2. SYSTEM STUDY
The system study section in a project content provides an overview of the existing system, its
limitations, and the need for the proposed solution. Here's a simplified system study for the
fire detection system:

2.1 EXISTING SYSTEM

Traditionally, fire detection systems have primarily relied on either manual intervention or
the installation of standalone fire detectors. These systems, while serving their intended
purpose to some extent, exhibit various limitations that hinder their effectiveness in ensuring
comprehensive fire safety.

Manual systems often entail periodic inspections conducted by personnel to identify signs of
fire or smoke. However, this approach has inherent drawbacks, including the potential for
human error, inconsistency in inspection schedules, and limited coverage due to the inability
to monitor areas continuously. Additionally, manual systems heavily rely on human
intervention for timely response to fire incidents, which can result in delays and inadequate
mitigation efforts.

Standalone fire detectors, on the other hand, are deployed in fixed locations within buildings
or premises and are designed to trigger alarms upon detecting smoke, heat, or other indicators
of fire. While these detectors offer a degree of protection, they are limited in their coverage
area and may not provide adequate surveillance of all spaces, leaving certain areas vulnerable
to undetected fire incidents.

2.1.1 DRAWBACKS OF EXISTING SYSTEM

Limited Coverage:
The current fire detectors are placed in specific spots, leaving some areas without coverage.
Fires in these uncovered areas might go unnoticed, leading to delayed responses and
increased damage.
Dependency on Humans:
The system relies on people to check for signs of fire regularly. However, human error or
oversight can occur, and inspections might not happen as often as needed, risking missed fire
incidents.

No Real-Time Monitoring:
The system doesn't continuously monitor for fires in real-time. This means there's a delay
between when a fire starts and when it's detected, giving it time to grow and become more
dangerous before anyone notices.

False Alarms:
Sometimes, the detectors mistakenly go off due to things like dust or steam, causing
unnecessary evacuations. This can lead to people not taking alarms seriously or ignoring
them when they're real.

Limited Adaptability:
The system isn't easily changed or updated to fit new building layouts or technology
advancements. This means it might not work well in buildings that change over time or need
newer fire safety features.

2.2 PROPOSED SYSTEM:


The proposed fire detection system aims to address the limitations of existing systems by
leveraging advanced technology and automation. This system integrates computer vision and
real-time monitoring capabilities to enhance fire safety and emergency response
effectiveness.

Key components include camera-based monitoring for continuous video frame capture,
sophisticated image processing algorithms for fire sign detection, a dedicated fire detection
algorithm, integration with alerting mechanisms such as audible alarms and email
notifications, database management for logging fire detection events, and a user-friendly
interface for real-time monitoring and system management. By utilizing these components,
the proposed system offers several benefits.
It enables real-time monitoring, allowing for prompt detection and response to fire incidents.
Automation reduces reliance on human intervention, thereby minimizing response time and
potential errors. Additionally, the use of video feeds ensures comprehensive coverage of the
monitored area, mitigating blind spots and ensuring thorough surveillance. Moreover, logging
fire detection events in a database facilitates retrospective analysis and trend identification,
enhancing overall fire detection and management processes.

Overall, the proposed fire detection system represents a significant advancement in fire safety
technology, promising improved reliability, efficiency, and effectiveness in mitigating the
risks associated with fire incidents.

2.2.1 FEATURES OF PROPOSED SYSTEM:

Real-Time Monitoring:
With continuous camera-based monitoring and sophisticated image processing algorithms,
the system enables real-time detection of fire incidents. This allows for prompt response
actions to be initiated as soon as a fire is detected, minimizing the spread of fire and reducing
potential damage.

Automation:
By leveraging automation, the system reduces reliance on human intervention for fire
detection and response. Automated alerts and notifications ensure that relevant stakeholders
are promptly informed of fire incidents, streamlining the emergency response process and
minimizing response time.

Comprehensive Coverage:
The utilization of camera-based monitoring ensures comprehensive coverage of the
monitored area, including previously inaccessible or poorly covered spaces. This minimizes
blind spots and ensures that all areas are continuously monitored for signs of fire, enhancing
overall fire safety.
Reduced False Alarms:
The system's advanced image processing algorithms help minimize false alarms by accurately
distinguishing between genuine fire incidents and false triggers caused by factors such as dust
or steam. This reduces the likelihood of unnecessary evacuations and disruptions, enhancing
the credibility and effectiveness of the fire detection system.

Enhanced Data Analysis:


By logging fire detection events in a centralized database, the system facilitates
comprehensive data analysis and reporting. Historical data on fire incidents can be analyzed
to identify trends, patterns, and areas of concern, enabling informed decision-making and
continuous improvement of fire safety measures.

Scalability and Flexibility:


The modular design of the proposed system allows for scalability and adaptability to
accommodate varying needs and requirements across different environments and
applications. This ensures that the system can grow and evolve alongside changing fire safety
needs and technological advancements.

Improved Emergency Response:


By providing real-time alerts and notifications to relevant stakeholders, the system enhances
emergency response coordination and effectiveness. This ensures that appropriate response
actions can be initiated promptly, minimizing the impact of fire incidents and ensuring the
safety of occupants and property.
CHAPTER 3
3. SYSTEM DESIGN AND DEVELOPMENT

The system design and development process commenced with a meticulous requirements
analysis to ascertain the comprehensive needs of the fire detection system. This involved
delving into user preferences, system limitations, and environmental factors to ensure a
nuanced understanding of the challenges inherent in fire detection. Subsequently, an
architectural blueprint was crafted, delineating the integration of various components like
camera-based monitoring, image processing algorithms, alerting mechanisms, database
management, and user interface. This architectural design adhered to a modular and scalable
framework, facilitating adaptability and future enhancements.

Each component underwent meticulous design, emphasizing modularity, reusability, and


seamless interoperability. For instance, the camera-based monitoring component was
designed to capture high-quality video frames seamlessly, while the image processing
algorithms were meticulously crafted to discern fire patterns with precision and accuracy.
Implementation entailed the judicious use of appropriate programming languages and
frameworks, ensuring the efficient realization of the designed architecture. Python, coupled
with OpenCV, was employed for image processing tasks, while Pygame facilitated the
implementation of audible alarm functionalities.

Extensive testing and validation procedures were conducted at every stage of development to
ascertain the functionality, reliability, and performance of the system. Unit testing was
conducted to scrutinize individual components, while integration testing evaluated the
seamless interaction between system modules. Comprehensive end-to-end testing simulated
various fire scenarios and environmental conditions to ensure robustness and efficacy.
Following validation, the system was deployed in the target environment, encompassing
configuration, integration, and optimization processes to ensure seamless operation.

Ongoing maintenance and support activities were paramount to sustaining the system's
functionality and effectiveness post-deployment. This encompassed continuous performance
monitoring, prompt issue resolution, timely application of updates and patches, and provision
of user training and support as needed. Through a systematic approach and leveraging
cutting-edge technologies, the fire detection system was successfully designed, developed,
and deployed, heralding a paradigm shift in fire safety and emergency response capabilities.

3.1 DATA FLOW DIAGRAM


3.2 INPUT DESIGN
The input design for the fire detection system encompasses a multifaceted approach to cater
to various aspects crucial for its efficient operation. Beginning with the camera input, it is
imperative to ensure compatibility not only with the OpenCV library but also with the
specific camera hardware being utilized. This involves validating the camera's resolution,
frame rate, and interface compatibility with the system. Additionally, considerations should
be made regarding the camera's field of view, angle, and placement to optimize fire detection
coverage within the monitored area.

Email configuration forms another critical component, facilitating timely notifications to both
the property owner and the designated fire station in the event of a fire detection. Alongside
providing valid email addresses and SMTP server details, mechanisms for securely storing
and transmitting sensitive email credentials must be implemented to prevent unauthorized
access and safeguard user privacy. Furthermore, incorporating error handling and logging
mechanisms for email transmission failures ensures the reliability of notification delivery.

The inclusion of an alarm sound file enhances the system's ability to promptly alert occupants
or responders to the presence of a fire. When selecting an alarm sound, factors such as
intensity, duration, and distinctiveness must be considered to ensure effective auditory
notification amidst varying ambient noise levels. Additionally, provisions should be made to
dynamically adjust the alarm volume based on the severity of the detected fire or user
preferences.

Fire detection thresholds play a pivotal role in accurately identifying fire-related phenomena
within captured frames. Fine-tuning these thresholds involves iteratively adjusting parameters
such as hue, saturation, and value ranges to differentiate between normal environmental
variations and potential fire signatures. Techniques such as adaptive thresholding and
machine learning-based approaches can further enhance the system's ability to adapt to
diverse lighting conditions and mitigate false alarms.

Database configuration encompasses the establishment of a robust data storage and


management framework to persistently store fire detection records and related metadata. In
addition to defining the database schema, considerations should be made regarding data
retention policies, backup strategies, and access control mechanisms to maintain data
integrity and confidentiality. Furthermore, implementing periodic data purging routines can
mitigate database bloat and optimize query performance over time.

User interaction aspects, although optional, contribute to enhancing the system's usability and
configurability. Providing intuitive keyboard commands for functions such as system
configuration, alarm mute, or emergency shutdown fosters user engagement and
empowerment. Additionally, integrating a graphical user interface (GUI) component can
further streamline user interaction and facilitate real-time monitoring of fire detection status
and system health metrics.

In conclusion, a comprehensive input design encompasses a holistic understanding of the


system's functional requirements, user needs, and security considerations. By meticulously
addressing each aspect, from hardware compatibility to user interaction paradigms, the fire
detection system can be effectively tailored to meet the demands of diverse deployment
scenarios while ensuring reliability, usability, and data security.

3.3 OUTPUT DESIGN


The output design for the fire detection system focuses on presenting relevant information to
users and stakeholders in a clear and actionable format. This includes visual feedback on fire
detection events, auditory alarms, and email notifications. Here's a detailed breakdown of the
output design:

1. Visual Output:
Real-time Display: Display live video feed from the camera with overlaid visual indicators
highlighting areas identified as potential fires.
Fire Detection Alerts: Highlight or annotate frames where fire detection thresholds are
exceeded to draw immediate attention to potential fire incidents.
Graphical User Interface (GUI): Optionally, provide a user-friendly interface for
configuring system settings, viewing historical fire detection data, and acknowledging alerts.

2. Auditory Output:
Alarm Sound: Play a distinct alarm sound when a fire is detected to alert occupants or
nearby individuals of the potential danger.
Volume Control:Implement volume control options to adjust the intensity of the alarm
sound based on user preferences or ambient noise levels.

3. Email Notifications:
Email Alerts:Send email notifications to the property owner and designated fire station
personnel upon detecting a fire.
Notification Content:Include relevant details such as the timestamp of the fire detection
event, camera location, and a brief description of the detected anomaly.

4. Logging and Reporting:


Event Logging:Maintain a log of fire detection events, including timestamps, camera
identifiers, and detection confidence scores, for historical analysis and audit purposes.
Reporting Dashboard: Optionally, provide a reporting dashboard to visualize trends in fire
detection incidents over time, analyze system performance metrics, and generate
customizable reports.

5. User Interaction:
Alert Acknowledgment: Allow users to acknowledge fire detection alerts via the GUI,
email, or other means to indicate that the situation is being addressed.
System Status Updates: Provide status updates on the system's operational state, including
connectivity status, camera health, and database integrity checks.

6. Error Handling and Notifications:


Error Messages: Display informative error messages in case of system errors, camera
connection issues, or database operation failures to guide troubleshooting efforts.
Email Delivery Status: Provide feedback on the success or failure of email delivery attempts
to ensure stakeholders are informed of the system's response to fire detection events.

7. Remote Access:
Web Interface: Offer a web-based interface for remote access to the fire detection system,
enabling users to monitor live camera feeds, configure system settings, and receive alerts
from anywhere with internet access.
Mobile Application: Develop a mobile application for iOS and Android platforms to provide
on-the-go access to fire detection alerts, system status updates, and historical data analysis.

8. Accessibility Considerations:
Visual and Auditory Alerts: Ensure visual indicators and auditory alarms are accessible to
users with disabilities, with options for customizable alerts and alternative notification
methods.
User Interface Design: Design the GUI with attention to accessibility guidelines, including
contrast ratios, text size, and navigational aids, to accommodate users with diverse needs.

3.4 DATABASE DESIGN


Designing the database for the fire detection system involves structuring the data schema to
efficiently store and manage information related to fire detection events, system
configurations, and user interactions. Here's a breakdown of the database design content:

1. Tables:
a. `fire_data` Table:
Columns:
1. `id` (Primary Key): Unique identifier for each fire detection event.
2. `timestamp`: Timestamp indicating the date and time of the fire detection event.
3. `camera_id`: Identifier for the camera capturing the footage.
4. `fire_detected`: Boolean indicating whether a fire was detected (1 for detected, 0 for not
detected).

b. `system_configuration` Table:
Columns:
1. `id` (Primary Key): Unique identifier for each configuration record.
2. `parameter_name`: Name of the system parameter (e.g., email server, alarm sound file
path).
3. `parameter_value`: Value of the corresponding parameter.

2. Relationships:
One-to-Many Relationship:The `fire_data` table has a one-to-many relationship with the
`camera` table, as multiple fire detection events can be associated with a single camera.

3. Database Constraints:
Foreign Key Constraints: Ensure referential integrity by establishing foreign key constraints
between related tables, such as `fire_data.camera_id` referencing `camera.id`.

4. Data Integrity:
Data Validation:Implement data validation checks to ensure the integrity and consistency of
stored data, such as enforcing valid timestamp formats and boolean values for fire detection
status.

5. Indexing Strategies:
Composite Indexes:Create composite indexes on frequently queried columns, such as
`(timestamp, camera_id)` in the `fire_data` table, to optimize search performance for specific
queries.

6. Backup and Recovery:


Regular Backups:Establish a backup strategy to periodically backup the database to prevent
data loss in the event of system failures or corruption.

7. Scalability Considerations:
Partitioning:Implement partitioning strategies to distribute data across multiple physical
storage devices or servers, ensuring scalability and improved performance as data volume
increases.

8. Security Measures:
a. Access Control:
Enforce access control mechanisms to restrict unauthorized access to sensitive database
tables and operations.
b. Encryption:
Encrypt sensitive data stored in the database, such as email server credentials, to prevent
unauthorized access in case of data breaches.
9. Database Management Tools:
a. Database Management System (DBMS):
Select a suitable DBMS, such as SQLite or PostgreSQL, to manage the database and perform
administrative tasks efficiently.
b. Monitoring and Maintenance:
Utilize database monitoring tools to track performance metrics, identify bottlenecks, and
schedule routine maintenance tasks, such as index rebuilding and database vacuuming.

3.5 SYSTEM DEVELOPMENT


The system development process for the fire detection project involves several key phases to
ensure its successful implementation. Firstly, requirements gathering and analysis are
conducted to comprehensively understand the project objectives, stakeholder needs, and
system functionalities. This phase involves collaboration with stakeholders to define clear
and achievable requirements, which serve as the foundation for subsequent development
activities. Following requirements analysis, system design entails the creation of detailed
architectural diagrams, such as data flow diagrams and system architecture diagrams, to map
out the structure and components of the fire detection system. Design considerations
encompass scalability, reliability, and integration with existing infrastructure.

Once the design is finalized, the development phase commences, where software engineers
and developers code the system components according to the design specifications. During
development, adherence to coding standards, best practices, and version control processes
ensures code quality and facilitates collaboration among team members. As development
progresses, rigorous testing is performed to identify and rectify defects, ensuring that the
system meets functional requirements and performs reliably under various scenarios. Testing
methodologies include unit testing, integration testing, and system testing, with automated
testing frameworks aiding in efficient test execution and result validation.
Upon successful completion of testing, deployment and implementation activities are carried
out to roll out the fire detection system into production environments. Deployment
encompasses activities such as software installation, configuration, and data migration,
ensuring seamless transition from development to production environments. Post-
deployment, ongoing maintenance and support efforts are essential to address any issues,
implement enhancements, and ensure the continued operation of the system. This phase
involves monitoring system performance, applying software updates, and providing timely
support to users and stakeholders.

Throughout the system development lifecycle, effective project management practices, such
as agile methodologies or the waterfall model, facilitate coordination, communication, and
progress tracking among team members. Project management tools, such as issue trackers
and collaboration platforms, aid in planning, scheduling, and monitoring project activities.
Additionally, regular communication with stakeholders through status updates, demos, and
feedback sessions fosters transparency and alignment with project goals. By following a
systematic and disciplined approach to system development, the fire detection project can
achieve its objectives while delivering value to stakeholders and end-users.

3.5.1 DESCRIPTION OF MODULES

Camera Input Module:


 This module is responsible for capturing live video feed from connected
cameras.
 It interfaces with camera hardware using libraries such as OpenCV to retrieve
video frames.
 It handles camera configuration, resolution settings, and frame rate
adjustments.
 Error handling mechanisms are implemented to manage issues such as camera
disconnection or configuration errors.
Fire Detection Module:
 Utilizing computer vision techniques, this module analyzes the video frames
captured by the Camera Input Module to detect potential fire occurrences.
 Algorithms may include color-based segmentation, motion detection, and
pattern recognition to identify fire-like patterns.
 Parameters such as color thresholds, motion sensitivity, and flame
characteristics are configurable to optimize detection accuracy.
 Continuous monitoring of video streams allows for real-time detection and
immediate response to fire events.
Alert Generation Module:
 Upon detection of a potential fire event by the Fire Detection Module, this
module generates alerts to notify relevant stakeholders.
 It triggers auditory alarms using predefined sound files to alert occupants of
the premises.
 Additionally, it initiates email notifications to inform property owners, facility
managers, and emergency services about the detected fire.
 Robust error handling ensures reliable alert generation and delivery even in
adverse conditions.
Notification Module:
 Integrated with the Alert Generation Module, this module manages the
delivery of email notifications to designated recipients.
 It interfaces with email servers using standard protocols such as SMTP to send
alert emails securely.
 Email content includes details such as timestamp, camera location, and a brief
description of the detected anomaly for quick identification and response.
 Configuration options allow for customization of email templates and
recipient lists.
Database Interaction Module:
 Responsible for managing the storage and retrieval of fire detection events and
related metadata.
 It utilizes a relational database management system (e.g., SQLite, MySQL) to
store event records efficiently.
 Database schema includes tables for storing event timestamps, camera
identifiers, detection statuses, and additional contextual information.
 CRUD (Create, Read, Update, Delete) operations are implemented to maintain
and query the database.
User Interface Module:
 Provides a graphical interface for users to interact with the fire detection
system.
 Features include system configuration settings, real-time monitoring of camera
feeds, and visualization of fire detection events.
 The user interface may be web-based, desktop-based, or mobile-based,
depending on user requirements and platform preferences.
 Intuitive design and user-friendly controls enhance usability and accessibility
for both technical and non-technical users.
Configuration Module:
 Allows users to customize various parameters of the fire detection system,
such as threshold values, email server settings, and notification preferences.
 Configuration options are presented through the user interface, with validation
mechanisms to ensure the integrity of user input.
 Changes made to configuration settings are reflected in real-time, with logging
functionality to track configuration updates and revisions.
Logging and Reporting Module:
 Logs system activities, including fire detection events, configuration changes,
and user interactions, to maintain an audit trail for compliance and
troubleshooting purposes.
 Provides reporting capabilities to generate detailed reports on system
performance, fire detection trends, and event histories.
 Reporting features include customizable report templates, data visualization
tools, and export options for sharing reports with stakeholders.
Geolocation Module:
 Enhances fire detection data with geolocation information to provide context
about the location of detected events.
 Integrates with geolocation services or databases to map fire incidents to
specific geographic coordinates.
 Geospatial visualization tools allow users to visualize fire detection events on
maps, aiding emergency responders in identifying affected areas and
coordinating response efforts.
Integration Module:
 Facilitates integration with external systems and services, such as building
management systems, emergency response platforms, and monitoring tools.
 Provides APIs, webhooks, or other integration endpoints to exchange data and
trigger actions between the fire detection system and external systems.
 Integration capabilities enable interoperability, data sharing, and workflow
automation across different systems and organizational boundaries.
Machine Learning Module:
 Applies machine learning algorithms to enhance fire detection accuracy and
adaptability.
 Utilizes historical fire detection data to train and refine detection models,
improving the system's ability to differentiate between fire-related phenomena
and false alarms.
 Continuously evaluates and updates detection models based on new
observations and feedback, ensuring optimal performance under varying
environmental conditions.
Mobile Application Module:
 Provides a mobile interface for users to access the fire detection system from
smartphones and tablets.
 Features include real-time alert notifications, remote monitoring of camera
feeds, and on-the-go configuration management.
 Cross-platform compatibility ensures seamless user experience across iOS and
Android devices, with support for offline access and synchronization.
CHAPTER 4
4. TESTING AND IMPLEMENTATION

Testing:

1. Unit Testing:
Describe the process of testing individual components or modules in isolation to ensure they
function correctly.
Provide examples of unit tests for key functionalities, such as camera input handling, fire
detection algorithms, and email notification generation.
Specify the testing framework used (e.g., Pytest, JUnit) and any mock objects or stubs
employed to simulate dependencies.

2. Integration Testing:
Explain how different modules are integrated and tested together to verify their interactions
and interoperability.
Detail integration test scenarios covering end-to-end functionality, including camera input,
fire detection, alert generation, and database interaction.
Document any test environments or setups required to simulate real-world conditions during
integration testing.

3. System Testing:
Outline the comprehensive testing of the entire fire detection system as a whole.
Define test cases that validate system behavior under various scenarios, including normal
operation, edge cases, and failure conditions.
Include performance testing to evaluate system response times, resource usage, and
scalability under different loads.

4. User Acceptance Testing (UAT):


Describe the process of involving end-users or stakeholders to validate the system against
their requirements and expectations.
Document UAT test cases and feedback received from users, along with any identified issues
or areas for improvement.
Discuss how feedback from UAT was incorporated into system refinements and adjustments.

5. Regression Testing:
Explain the practice of retesting previously validated functionalities to ensure that new
changes or updates do not introduce regressions or unintended side effects.
Detail the regression testing strategy, including the selection of test cases, automation
techniques, and frequency of regression testing cycles.

Implementation:

1. Deployment Strategy:
Outline the plan for deploying the fire detection system into production environments.
Specify deployment procedures, including software installation, configuration, and data
migration steps.
Document any pre-requisites or dependencies required for successful deployment, such as
system hardware specifications or software dependencies.

2. Rollout Plan:
Describe the phased approach for rolling out the fire detection system across different
locations or departments.
Identify key stakeholders involved in the rollout process and their respective responsibilities.
Provide a timeline for each rollout phase, along with milestones and checkpoints for
monitoring progress.

3. Training and Support:


Discuss the training program designed to familiarize users and administrators with the fire
detection system.
Detail training materials, such as user manuals, training videos, or interactive tutorials, and
the delivery methods used (e.g., onsite training sessions, online webinars).
Specify ongoing support mechanisms, including helpdesk support, documentation
repositories, and community forums, to assist users with system usage and troubleshooting.

4. Documentation and Knowledge Transfer:


Emphasize the importance of comprehensive documentation to support system maintenance,
troubleshooting, and knowledge transfer.
Provide links to relevant documentation resources, including user guides, technical
specifications, and API references.
Outline strategies for knowledge transfer, such as peer mentoring, shadowing, and cross-
training, to ensure organizational continuity and expertise retention.

5. Post-Implementation Review:
Discuss the process of conducting a post-implementation review to evaluate the success of
the fire detection system deployment.
Document key performance metrics, user feedback, and lessons learned during the
implementation process.
Identify areas of improvement and recommendations for future enhancements or iterations of
the system.
CHAPTER 5
5. CONCLUSION
In conclusion, the development of the fire detection system represents a significant milestone
in enhancing safety and security within the target environment. Through meticulous planning,
rigorous testing, and careful implementation, the project has successfully delivered a robust
and reliable solution for detecting fire incidents and alerting stakeholders in a timely manner.
By leveraging advanced technologies such as computer vision, machine learning, and real-
time alerting mechanisms, the system provides an effective means of early fire detection,
thereby mitigating potential risks and minimizing the impact of fire-related incidents.

The collaborative efforts of the project team, stakeholders, and end-users have been
instrumental in the successful execution of the project, ensuring alignment with requirements,
user needs, and industry best practices. Feedback gathered throughout the development
lifecycle has been instrumental in refining the system's functionality, usability, and
performance, resulting in a solution that meets the evolving needs of the organization and its
stakeholders.

Looking ahead, continuous monitoring, maintenance, and iterative improvements will be


essential to sustaining the effectiveness and reliability of the fire detection system over time.
Regular updates, proactive system enhancements, and ongoing user training will help ensure
that the system remains responsive to emerging threats, technological advancements, and
evolving regulatory requirements.

In summary, the fire detection system stands as a testament to the collective dedication,
expertise, and innovation of all involved parties. By providing early detection capabilities and
facilitating swift response actions, the system contributes to safeguarding lives, property, and
assets, ultimately fostering a safer and more secure environment for all stakeholders. As we
move forward, our commitment to excellence and continuous improvement will remain
unwavering as we strive to uphold the highest standards of safety and resilience in fire
detection and emergency response.

5.1 BIBLIOGRAPHY
Websites:
1. OpenCV Documentation. (n.d.). Retrieved from https://docs.opencv.org/
2. Matplotlib Documentation. (n.d.). Retrieved from https://matplotlib.org/
3. PythonSQLite Documentation.(n.d.). Retrieved from
https://docs.python.org/3/library/sqlite3.html
4. Python Threading Documentation. (n.d.). Retrieved from
https://docs.python.org/3/library/threading.html
5. Pygame Documentation. (n.d.). Retrieved from https://www.pygame.org/docs/

Software Documentation:
1. SQLite. (n.d.). SQLite Documentation. Version 3. Retrieved from
https://www.sqlite.org/docs.html
2. Pygame. (n.d.). Pygame Documentation. Retrieved from https://www.pygame.org/docs/

Frameworks and Libraries:


1. OpenCV. (n.d.). OpenCV Documentation. Retrieved from https://docs.opencv.org/
2. Matplotlib. (n.d.). Matplotlib Documentation. Retrieved from https://matplotlib.org/
3. Python Standard Library. (n.d.). Retrieved from https://docs.python.org/3/library/
5.2 APPENDICES
A. DATA FLOW DIAGRAM
B. TABLE STRUCTURE

Table: fire_data

Column Name Data Type Description


Id INTEGER Primary key,
auto-incrementing ID
Timestamp TIMESTAMP Timestamp of when the data
was recorded
fire_detected INTEGER Indicator of whether fire was
detected

id: This column serves as the primary key for the table. It is of type INTEGER and is set to auto-
increment, meaning it automatically assigns a unique identifier to each record added to the table.
This ensures that each entry in the table has a distinct identifier for easy retrieval and reference.

timestamp: The timestamp column stores the date and time when each fire detection event occurred.
It is of type TIMESTAMP, allowing for precise recording of the time at which the event took place.
Using timestamps enables chronological ordering of fire detection events, facilitating analysis and
tracking of trends over time.

fire_detected: This column indicates whether a fire was detected at the time of the event. It is of
type INTEGER and serves as a binary indicator, where a value of 1 signifies that a fire was detected,
and a value of 0 indicates no fire detection. This column is crucial for tracking instances of fire
detection and analyzing the frequency and distribution of fire incidents over time.

The table structure provides a comprehensive framework for storing fire detection data captured by
the system. By recording essential information such as unique identifiers, timestamps, and fire
detection status, the table enables efficient retrieval, analysis, and monitoring of fire-related events.
Additionally, the use of auto-incrementing primary keys ensures data integrity and facilitates the
management of database records.

C. SAMPLE CODING
import cv2
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import sqlite3
import smtplib
import threading
import pygame
import time
# Initialize database connection
conn = sqlite3.connect('fire_detection.db')
cursor = conn.cursor()
# Create table if not exists
cursor.execute('''CREATE TABLE IF NOT EXISTS fire_data
(id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
fire_detected INTEGER)''')
# Initialize pygame mixer
pygame.mixer.init()
Alarm_Status = False
Email_Status = False
Fire_Reported = 0
last_detection_time = time.time()
def play_alarm_sound_function():
pygame.mixer.music.load('alarm-sound.mp3')
pygame.mixer.music.play()
def send_mail_function(owner_email, fire_station_email):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("Your_Email", 'Your_Password')

owner_message = "Subject: Fire Alert\n\nA fire accident has been reported at your
place."
fire_station_message = "Subject: Fire Alert\n\nA fire accident has been reported at your
place."
# Send email to the owner
server.sendmail('Your_Email', owner_email, owner_message)
# Send email to the fire station
server.sendmail('Your_Email', fire_station_email, fire_station_message)
print("Sent to Owner: {}".format(owner_email))
print("Sent to Fire Station: {}".format(fire_station_email))
server.close()
except Exception as e:
print(e)
# Function to capture frames from camera
def capture_frames():
cap = cv2.VideoCapture(0) # 0 for default camera
while True:
ret, frame = cap.read()
if not ret:
break
yield frame
cap.release()
# Function to update the Matplotlib figure with new frames
def update(frame):
global Alarm_Status, Email_Status, Fire_Reported, last_detection_time
if not hasattr(update, 'img'):
update.img = plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
else:
update.img.set_array(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# Fire detection logic
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)
no_red = cv2.countNonZero(mask)
if no_red > 15000:
Fire_Reported += 1
last_detection_time = time.time() # Update last detection time
# Insert data into the database
cursor.execute("INSERT INTO fire_data (fire_detected) VALUES (?)", (1,))
conn.commit()
if Fire_Reported >= 1:
if not Alarm_Status:
threading.Thread(target=play_alarm_sound_function).start()
Alarm_Status = True
if not Email_Status:
# Provide the email addresses of the owner and the fire station
owner_email = "owner@example.com"
fire_station_email = "firestation@example.com"
threading.Thread(target=send_mail_function, args=
(owner_email, fire_station_email)).start()
Email_Status = True
# Check if no fire is detected for 1 minute
if time.time() - last_detection_time >= 60:
print("No fire detected for 1 minute. Closing the output window.")
plt.close()
return update.img,
# Initialize Matplotlib figure
fig, ax = plt.subplots()
ax.axis('off')
# Create animation
ani = FuncAnimation(fig, update, frames=capture_frames, blit=True)
# Event handler to close the plot window when a key is pressed
def on_key_press(event):
if event.key == 'q':
plt.close()
fig.canvas.mpl_connect('key_press_event', on_key_press)
plt.show()
# Close database connection
conn.close()

D. FORM DESIGN
Form design typically refers to the layout and structure of user interfaces in software
applications. Since the provided code is for a backend system that performs fire detection and
alerting, it doesn't have a user interface in the traditional sense. However, we can design a
simple form that outlines the parameters and settings used in the system. Here's an example
form design for the fire detection system:
Fire Detection System Settings

Camera Settings:
 Camera Source: [Dropdown to select camera source]
 Resolution: [Dropdown to select resolution]
 Frame Rate: [Dropdown to select frame rate]

Fire Detection Parameters:


 Blur Kernel Size: [Input field to specify blur kernel size]
 HSV Color Range:
 Lower Bound: [Input fields for Hue, Saturation, and Value]
 Upper Bound: [Input fields for Hue, Saturation, and Value]
Alert Settings:
 Owner Email: [Input field for owner's email address]
 Fire Station Email: [Input field for fire station's email address]

Alarm Sound:
 Alarm Sound File: [Dropdown to select alarm sound file]

Email Server Settings:


 SMTP Server: [Input field for SMTP server address]
 Port: [Input field for SMTP server port]
 Username: [Input field for SMTP server username]
 Password: [Input field for SMTP server password]

Database Settings:
 Database Path: [Input field for database file path]

System Status:
 Alarm Status: [Checkbox to indicate if alarm is active]
 Email Status: [Checkbox to indicate if email notifications are enabled]
 Fire Reported: [Input field to display the number of fire incidents reported]
 Last Detection Time: [Input field to display the timestamp of the last fire detection]

Control Buttons:
 Save Settings
 Start System
 Stop System

This form outlines various settings and parameters used in the fire detection system,
including camera settings, fire detection parameters, alert settings, alarm sound selection,
email server settings, database settings, system status indicators, and control buttons for
saving settings and controlling system operation. Each setting can be configured through the
form to customize the behavior of the fire detection system according to specific
requirements.

You might also like