Fire and Smoke Detection Using PyTorch (with Full Code)

Deepak N R
3 min readAug 7, 2023

--

In recent years, artificial intelligence and machine learning advancements have revolutionized various industries, including public safety. One area where these technologies have made significant strides is in fire and smoke detection, which is crucial for early warning systems and efficient emergency response. In this article, we will explore the various aspects of fire and smoke detection using PyTorch.

Introduction to Fire and Smoke Detection:

Fire and smoke detection systems play an important role in preventing disasters and minimizing property damage. Traditionally, these devices have relied on the use of sensors and cameras to monitor environments for signs of fire or smoke. However, these methods may only sometimes be efficient, especially in complex and large-scale settings. AI-powered solutions such as those built using PyTorch can help solve this problem by providing faster analysis speeds with fewer errors than traditional methods.

Code Walkthrough

We will be using Google Colaboratory. Watch the below video for a basic introduction to the web IDE.

Installing Torfusion Utils

!pip3 install torchfusion_utils

Torchfusion Utils is a PyTorch helper library for Mixed Precision Training, Metrics and more utilities to simplify the training of deep learning models. Read the document of TorchFusion here.

Importing necessary packages

from torchfusion_utils.fp16 import convertToFP16
from PIL import Image
from torchfusion_utils.initializers import *
from torchfusion_utils.metrics import Accuracy
from torchfusion_utils.models import load_model,save_model
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms, models
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from torch.autograd import Variable
import cv2
from google.colab.patches import cv2_imshow
from PIL import Image
import glob

Download Pre-trained weight

!wget https://github.com/DeepQuestAI/Fire-Smoke-Dataset/releases/download/v1/fire-flame.pt

Pre-trained weights are downloaded from DeepQuest AI’s Github account.

Load the Pytorch model

load_saved_model = torch.load('fire-flame.pt')

Inferencing

transformer = transforms.Compose([transforms.Resize(225),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5],
[0.5, 0.5, 0.5])])
for img_path in glob.glob("/content/img_folder/*"):
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img.astype('uint8'))
orig = img.copy()
img_processed = transformer(img).unsqueeze(0)
img_var = Variable(img_processed, requires_grad= False)
img_var = img_var.cuda()
load_saved_model.eval()
logp = load_saved_model(img_var)
expp = torch.softmax(logp, dim=1)
confidence, clas = expp.topk(1, dim=1)

co = confidence.item() * 100


class_no = str(clas).split(',')[0]
class_no = class_no.split('(')
class_no = class_no[1].rstrip(']]')
class_no = class_no.lstrip('[[')


orig = np.array(orig)
orig = cv2.cvtColor(orig,cv2.COLOR_BGR2RGB)
orig = cv2.resize(orig,(800,500))

if class_no == '1':
label = "Nuetral: " + str(co)+"%"
cv2.putText(orig, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)

elif class_no =='2':
label = "Smoke: " + str(co)+"%"
cv2.putText(orig, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)

elif class_no == '0':
label = "Fire: " + str(co)+"%"
cv2.putText(orig, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)


cv2.imwrite("/content/output/{}".format(img_path.split("/")[-1]), orig)

Output:

Fire-Smoke-Neutral detected in Images

Get the full version of the code and input images here

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

Deepak N R

As a computer vision and deep learning enthusiast, I have a strong passion for developing algorithms that can understand and interpret the visual world.