Fire Detection Using Surveillance Camera on Roads

Credit: AITS Cainvas Community

Photo by Aslan Almukhambetov on Dribbble

Accidents on the road can sometimes lead to a fire that can get worse over time. Fires along the road due to other reasons are also be hazardous to the traffic on the road and nearby places. These fires need to be detected and controlled with utmost urgency in order to maintain the safety of those in the vicinity.

In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.keras import layers, optimizers, models, preprocessing, losses, callbacks
import os
import random
from PIL import Image
import tensorflow as tf
import tensorflow.keras
In [2]:
!wget ""
!unzip -qo

--2021-09-07 08:21:35--
Resolving (
Connecting to (||:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 102552780 (98M) [application/zip]
Saving to: ‘’            100%[===================>]  97.80M  97.6MB/s    in 1.0s    

2021-09-07 08:21:36 (97.6 MB/s) - ‘’ saved [102552780/102552780]

The dataset zip file has 3 folders, train, validation and test. Each of these has 2 sub folders - Fire and Non-fire.

In [3]:
# Loading the dataset

path = 'fire/'
input_shape = (256, 256, 3)    # default input shape while loading the images

batch = 64

# The train and test datasets
print("Train dataset")
train_ds = preprocessing.image_dataset_from_directory(path+'Train', batch_size=batch, label_mode='binary')

print("Test dataset")
test_ds = preprocessing.image_dataset_from_directory(path+'Test', batch_size=batch, label_mode='binary')

print("Validation dataset")
val_ds = preprocessing.image_dataset_from_directory(path+'Vali', batch_size=batch, label_mode='binary')
Train dataset
Found 6003 files belonging to 2 classes.
Test dataset
Found 2000 files belonging to 2 classes.
Validation dataset
Found 2000 files belonging to 2 classes.

Lets look into the spread of images across the categories and dataset splits.

In [4]:
# How many samples in each class

for t in ['Train', 'Test', 'Vali']:
    print('\n', t.upper())
    for x in os.listdir(path + t):
        print(x, ' - ', len(os.listdir(path + t + '/' + x)))
Non-Fire  -  3000
Fire  -  3003

Non-Fire  -  1000
Fire  -  1000

Non-Fire  -  1000
Fire  -  1000

It is a balanced dataset.

In [5]:
# Looking into the class labels

class_names = train_ds.class_names

print("Train class names: ", train_ds.class_names)
print("Test class names: ", test_ds.class_names)
print("Validation class names: ", val_ds.class_names)
Train class names:  ['Fire', 'Non-Fire']
Test class names:  ['Fire', 'Non-Fire']
Validation class names:  ['Fire', 'Non-Fire']


In [6]:
num_samples = 4    # the number of samples to be displayed in each class

for x in class_names:
    plt.figure(figsize=(20, 20))

    filenames = os.listdir(path + 'Train/' + x)

    for i in range(num_samples):
        ax = plt.subplot(1, num_samples, i + 1)
        img = +'Train/' + x + '/' + filenames[i])