The Wayback Machine - https://web.archive.org/web/20240725233411/https://www.geeksforgeeks.org/gun-detection-using-python-opencv/
Open In App

Gun Detection using Python-OpenCV

Last Updated : 01 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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:

  • We collect positive images containing the object we want to detect and negative images that do not contain the object.
  • We ensure that the positive images are annotated with bounding boxes around the objects of interest.

Create a positive samples file:

  • Then we will use the positive images and their annotations to create a positive samples file. This file will contain information about the positive images and their corresponding object-bounding boxes. We can use the opencv_createsamples utility to generate the positive samples file.

Create a negative samples file:

  • We will create a negative samples file that lists the paths to the negative images. This file will provide information about the images that do not contain the object.

Train the cascade classifier:

  • Also, we will use the positive and negative sample files to train the cascade classifier using the opencv_traincascade utility.
  • Specify various parameters like the number of stages, the desired false positive rate, and the minimum and maximum object size.
  • The training process will iteratively train the cascade classifier, evaluating its performance at each stage. The training may take a significant amount of time, depending on the complexity of the object and the size of the dataset.

Evaluate the trained classifier:

  • After the training is complete, we can evaluate the performance of the trained cascade classifier on a separate test dataset.
  • Also, we can adjust the parameters and retrain if necessary to improve the detection accuracy is needed.

Use the trained Haar cascade file:

  • Once the training is successful, we will have a trained Haar cascade XML file.
  • We can load this file using the cv2.CascadeClassifier class in OpenCV and use it to detect the object of interest in images or video streams.

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



Previous Article
Next Article

Similar Reads

Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Python | Smile detection using OpenCV
Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw
3 min read
Circle Detection using OpenCV | Python
Circle detection finds a variety of uses in biomedical applications, ranging from iris detection to white blood cell segmentation. The technique followed is similar to the one used to detect lines, as discussed in this article. Basics of Circle Detection A circle can be described by the following equation: To detect circles, we may fix a point (x,
3 min read
Pedestrian Detection using OpenCV-Python
OpenCV is an open-source library, which is aimed at real-time computer vision. This library is developed by Intel and is cross-platform - it can support Python, C++, Java, etc. Computer Vision is a cutting edge field of Computer Science that aims to enable computers to understand what is being seen in an image. OpenCV is one of the most widely used
3 min read
Multiple Color Detection in Real-Time using Python-OpenCV
For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important. Why this is important? : Some Real-world Applications In self-driving car, to detect the traffic signals. Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating d
4 min read
Contour Detection with Custom Seeds using Python - OpenCV
This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition. This program uses OpenCV, Numpy, and Matplotlib libraries. It also uses a built-in OpenCV Watershed algorithm to
3 min read
Automating Scrolling using Python-Opencv by Color Detection
Prerequisites: OpencvPyAutoGUI It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own. App
2 min read
three90RightbarBannerImg