Gun Detection using PythonOpenCV (original) (raw)

Gun Detection using Python-OpenCV

Last Updated : 25 Apr, 2025

Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations.

Prerequisites: Python OpenCV

OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Real-Time Applications.

Approach for Gun Detection using OpenCV

Creation of Haarcascade file of Guns:

In OpenCV, creating a Haar cascade file involves the following steps:

Prepare positive and negative images:

Create a positive samples file:

Create a negative samples file:

Train the cascade classifier:

Evaluate the trained classifier:

Use the trained Haar cascade file:

It’s important to note that training a Haar cascade classifier requires a significant amount of positive and negative samples, careful parameter tuning, and computational resources. For the simplicity of this project, we have already our cascade file.

Note: For The Gun haar cascade created – click here.

Python Code for Detection of Guns using OpenCV

OpenCV comes with a trainer as well as a detector. If you want to train your own classifier for any object like a car, plane, etc. We can use OpenCV to create one. Here we are only dealing with the detection of Guns.

First, we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode. Now we find the guns in the image. If guns are found, it returns the positions of detected guns as Rect(x, y, w, h). Once we get these locations, we can create an ROI(Region of Interest) for the gun.

Python3

import numpy as np

import cv2

import imutils

import datetime

gun_cascade = cv2.CascadeClassifier( 'cascade.xml' )

camera = cv2.VideoCapture( 0 )

firstFrame = None

gun_exist = False

while True :

`` ret, frame = camera.read()

`` if frame is None :

`` break

`` frame = imutils.resize(frame, width = 500 )

`` gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

`` gun = gun_cascade.detectMultiScale(gray, 1.3 , 20 , minSize = ( 100 , 100 ))

`` if len (gun) > 0 :

`` gun_exist = True

`` for (x, y, w, h) in gun:

`` frame = cv2.rectangle(frame, (x, y), (x + w, y + h), ( 255 , 0 , 0 ), 2 )

`` roi_gray = gray[y:y + h, x:x + w]

`` roi_color = frame[y:y + h, x:x + w]

`` if firstFrame is None :

`` firstFrame = gray

`` continue

`` cv2.putText(frame, datetime.datetime.now().strftime( "%A %d %B %Y %I:%M:%S %p" ),

`` ( 10 , frame.shape[ 0 ] - 10 ),

`` cv2.FONT_HERSHEY_SIMPLEX,

`` 0.35 , ( 0 , 0 , 255 ), 1 )

`` if gun_exist:

`` print ( "Guns detected" )

`` plt.imshow(frame)

`` break

`` else :

`` cv2.imshow( "Security Feed" , frame)

`` key = cv2.waitKey( 1 ) & 0xFF

`` if key = = ord ( 'q' ):

`` break

camera.release()

cv2.destroyAllWindows()

Output:

Gun detection using opencv

Gun detection using OpenCV