Build a Weapon Detection Algorithm using YOLOv7

Ahmad Jawabreh
The Modern Scientist
7 min readApr 11, 2023

--

Design and implement a weapon detection algorithm from scratch using YOLOv7

cover

You Only Lock Once (YOLO)

YOLOv7 (You Only Look Once version 7) is a popular object detection model in computer vision, known for its speed and accuracy in real-time detection of objects in images and videos. It uses a deep neural network to predict the bounding boxes and class probabilities for objects in an input image or video frame, enabling fast and accurate object detection.

YOLOv7 is an extension of the YOLOv5 and YOLOv6 architecture, which itself was an improvement over previous versions of the YOLO model, with added features such as dynamic scaling, anchor-free object detection, and improved loss functions. YOLOv7 has been widely used in a range of applications, including self-driving cars, facial recognition, and object detection in security systems.

YOLOv7 Performance

YOLOv7 has been demonstrated to achieve state-of-the-art performance in object detection tasks, outperforming previous versions of the YOLO model and other object detection models in terms of accuracy, speed, and memory efficiency. In particular, YOLOv7 has achieved high accuracy in object detection benchmarks such as COCO and PASCAL VOC.

YOLOv7 also boasts fast inference speeds, with real-time detection of up to 120 frames per second (fps) on modern GPUs. Additionally, YOLOv7 has a relatively small model size, making it memory-efficient and well-suited for deployment on resource-limited devices. Overall, YOLOv7 offers a powerful and efficient solution for object detection tasks, with high performance across a range of metrics.

yolov7-performance
YOLOv7 Performance

Implementation

To implement gun detection using YOLOv7, I first trained the model on a large dataset of gun images using a transfer learning approach. This involved fine-tuning the pre-trained YOLOv7 model on the gun detection task using annotated images of guns. After training, I tested the model on a real-time video feed and evaluated its performance in terms of accuracy, speed, and false positives.

The gun detection algorithm was integrated into a security system that can automatically detect and alert security personnel in the event of a gun being detected in the video feed. The implementation of the gun detection algorithm using YOLOv7 offers a powerful and efficient solution for detecting guns in real-time video feeds, with high accuracy and minimal false positives.

Implementation Steps:

  1. Data Collection: data collection is a critical step in developing any object detection algorithm, including the gun detection algorithm using YOLOv7. To collect the data needed for training and testing the algorithm, I used a combination of publicly available datasets and custom datasets. I sourced publicly available datasets of gun images from websites such as Kaggle and ImageNet.

    Our plan is to obtain a comprehensive gun dataset that includes a variety of different firearms, such as rifles. Furthermore, we will need to identify distinct types of rifles, such as those that are part of the AR-15 or AK platforms. To accomplish this, we will search public platforms such as Kaggle.com for a pre-existing dataset that meets our needs, here is two gun datasets from Kaggle.com that can be used for our project,
    https://www.kaggle.com/datasets/ankan1998/weapon-detection-dataset
    https://www.kaggle.com/datasets/atulyakumar98/gundetection

    If we want to create our own gun detection dataset, we do not need to manually search and download images from the internet one by one. Instead, we can automate the process by using a Python script to download data from public resources online based on a specific keyword. By collecting a large dataset that adheres to the guidelines for our training and testing data, we can create a customized dataset for our gun detection algorithm. Here is an example of a Python script that can be used to retrieve data from the internet:
from simple_image_download import simple_image_download as simp

# from simp library call simple_image_download function
response = simp.simple_image_download

# the keywords that will be used to find pics, and each key work will create a different file
keywords = ["George Wassouf", "Donald Trump", "Selena Gomez"]

# for loop on the keywords
# (kw, 1000) means 300 sample of each keyword
for kw in keywords:
response().download(kw, 1000)

2. Data Annotation: data annotation is the process of labeling data with relevant information, such as bounding boxes, semantic segmentation masks, or keypoint annotations. In the context of object detection, data annotation involves identifying objects within an image and labeling them with bounding boxes or other annotations that define their location and attributes. This process is typically performed manually, often with the help of annotation tools that enable users to quickly and accurately label large datasets.

If we plan to use our own dataset, we will need to label each piece of data individually. Even if we use a pre-existing dataset, we cannot always rely on the accuracy of the existing annotations. As a result, we will use the data without pre-existing labels and manually re-label each piece of data ourselves. However, in most cases, the dataset obtained from the internet will include both the data and the labels in a single file. Manually removing the labels can be a time-consuming process, particularly if we are working with a large dataset of over 5000 images. To automate this process, we can use a Python script to delete the labels. Here is an example of a Python script that can perform this task.

import os

directory = '/home/jawabreh/Desktop/Temp/' # replace with the dataset path

for filename in os.listdir(directory):
if filename.endswith('.txt'):
file_path = os.path.join(directory, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))

To begin annotating your training data, you can use LabelImg, a graphical image annotation tool designed specifically for object detection tasks. First, you will need to download LabelImg using pip. If you are using Linux or macOS, you can run the command “pip install labelImg” to download it. Once you have downloaded LabelImg, you can run the application by executing the command “labelImg” in your terminal. This will launch the LabelImg interface, allowing you to begin annotating your images with bounding boxes.

LabelImg-gui
labelImg GUI

To begin annotating the training data using labelImg, open the directory containing the training images. Then select the “Create RectBox” option from the side menu and draw a rectangle around the gun in the image. After that, assign a name to your class. Next, click on the “PascalVOC” option from the side menu and select “YOLO”. Repeat these steps for all the images in the dataset by clicking on the “Next Image” button.

3. Training: To start the training process, we need to run it on the GPU. If you have an Nvidia GPU, you can run the training process on your local machine. However, if you do not have one, you can use Google Colab, which provides a free account to train your model. In this case, we will be using Google Colab, so first create a google colab account and follow the following steps:

  • Connect your google drive to your google colab

# connect to google drive
from google.colab import drive
drive.mount("/content/gdrive")
# change directory
%cd /content/gdrive/MyDrive
  • Create a directory for the project on google drive
# create file it's not exist 
import os
if not os.path.isdir("MediumProject"):
os.makedirs("MediumProject")
  • Move to the project directory
%cd /content/gdrive/MyDrive/MediumProject
  • Clone the official repo of YOLOv7
!git clone https://github.com/WongKinYiu/yolov7
!wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7x.pt
!wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt
  • Move to yolov7 directory
%cd yolov7
  • Uploade your training and testing data to your google drive and place it inside the project directory using google drive GUI
  • Start Training
!python train.py --device 0 --batch-size 16 --epochs 100 --img 640 640 --data data/custom_data.yaml --hyp data/hyp.scratch.custom.yaml --cfg cfg/training/yolov7-custom.yaml --weight yolov7.pt --name yolov7-custom

4. Testing

!python detect.py --weight /content/gdrive/MyDrive/MediumProject/yolov7/runs/train/yolov7-custom/weights/best.pt --conf 0.4 --img-size 640 --source data/testSamples/12.png

5. Evaluation

This process involves measuring the accuracy of the model in detecting guns in test images. One common metric used for object detection models like YOLO is the mean average precision (mAP). This metric takes into account the precision and recall of the model’s predictions and provides a single numerical score for the model’s performance.

Other metrics that can be used include precision, recall, and F1 score. In addition to evaluating the performance of the model on the test set, it is important to analyze the types of errors the model makes to understand where improvements can be made. This can be done by analyzing the confusion matrix, which shows the number of true positives, false positives, true negatives, and false negatives for each class.

Conclusion

In conclusion, gun detection using YOLOv7 is a promising solution for enhancing public safety and security. With the increasing incidents of gun violence around the world, developing efficient and accurate gun detection algorithms is crucial.

The YOLOv7 algorithm offers high performance, speed, and accuracy in detecting guns in images and videos, making it an effective tool for law enforcement agencies, public places, and private organizations. The process of building a gun detection system using YOLOv7 involves data collection, annotation, training, and evaluation. It requires a good understanding of computer vision, deep learning, and object detection techniques. However, with the help of open-source tools and online resources, anyone can develop a gun detection system using YOLOv7.

Overall, the implementation of gun detection using YOLOv7 is a significant step towards promoting public safety and reducing gun violence.

The project github repo: https://github.com/Jawabreh0/Gun-Detection
Follow me on github for more AI projects: https://github.com/Jawabreh0

--

--