Person Counting Made Easy with YOLOv7 Object Detection
Introduction
In recent years, object detection has gained significant attention and is being used in various fields like self-driving cars, facial recognition, and many more. YOLOv7 is a popular object detection model that can detect and locate objects in an image or video. In this blog post, we will explore how to use YOLOv7 to count the number of people in an image or video.
1. What is YOLOv7?
- YOLOv7 or You Only Look Once version 7, is a real-time object detection algorithm developed by Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao. It is an improvement over previous versions of YOLO, which is known for its speed and accuracy in detecting objects in images and videos.
2. Dataset Preparation
- In this case, you can use the pre-trained model yolov7.pt that yolov7 provided.
- Move to 5. Using the Trained Model for Person Counting
- If you want to prepare your own dataset then you should first collect images on these classes and annotate all these images.
- you can use this tool for annotations 👇🏻.
3. Training YOLOv7 model for Person Counting
- Clone this repository from GitHub and open it on any IDE.
git clone https://github.com/WongKinYiu/yolov7.git
2. Now create a conda environment for yolov7 & install requirements.
conda create -n yolov5
conda activate yolov5
python -m pip install --upgrade pip
pip install -r requirements.txt
3. Prepare the custom.yaml file, copy coco.yaml file and modify it according to your insert.
data/custom.yaml
train: ./train/
val: ./val/
test: ./test/
nc: 1
# class names
names: ['person']
4. Using the train.py file we can start training.
python train.py --workers 8 --device 0 --batch-size 32 --data data/custom.yaml --img 640 640 --cfg cfg/training/yolov7-custom.yaml --weights 'yolov7_training.pt' --name yolov7-custom --hyp data/hyp.scratch.custom.yaml
These are default parameters that yolov7 provided you can play with this and improve your training.
4. Evaluating the Trained Model
- Using the detect.py file, Test how the model was performing on testing images and videos.
- you can find best.pt file in runs/train/exp/weight/best.pt
python detect.py --weights best.pt --conf 0.25 --img-size 640 --source yourvideo.mp4
These are the default parameters that yolov7 provided you can play with this and test your images and videos.
5. Using the Trained Model for Person Counting
- In people counting we need a tracking algorithm.
- There is multiple optimized algorithm available on markets that we will use directly in our project without worrying about low-level concepts.
- Clone this yolov7 object-tracking algorithm.
git clone https://github.com/RizwanMunawar/yolov7-object-tracking.git
2. Now create a conda environment for yolov7-object-tracking & install requirements.
conda create -n yolov7-object-tracking
conda activate yolov7-object-tracking
python -m pip install --upgrade pip
pip install -r requirements.txt
3. This code is provide only tracking and detection we will change the code so that we can count persons or objects as per our needs.
Add the trackbleobject.py file to the yolov7-object-tracking directory.
trackbleobject.py
class TrackableObject:
def __init__(self, objectID, centroid):
# store the object ID, then initialize a list of centroids
# using the current centroid
self.objectID = objectID
self.centroids = [centroid]
# initialize a boolean used to indicate if the object has
# already been counted or not
self.counted = False
detect_and_track.py
# add this variable trackableObjects globally
trackableObjects = {}
# add this variables above dataset for loop
totalDownPerson = 0
totalUpPerson = 0
Using tracked_dets list calculate the directions of the objects.
# add this code after tracked_dets initialized
if len(tracked_dets) > 0:
bbox_xyxy = tracked_dets[:, :4]
identities = tracked_dets[:, 8]
categories = tracked_dets[:, 4]
for cord in tracked_dets:
x_c = (cord[0] + [2]) // 2
y_c = (cord[1] + cord[3]) // 2
to = trackableObjects.get(cord[8], None)
if to is None:
to = TrackableObject(cord[8], (x_c, y_c))
else:
y = [c[1] for c in to.centroids]
direction = y_c - np.mean(y)
to.centroids.append((x_c, y_c))
if not to.counted:
idx = int(cord[4])
if direction < 0 and middle > y_c > height // 2.3:
if(idx == 0):
totalUpPerson += 1
to.counted = True
elif direction > 0 and middle < y_c < height // 1.8:
if(idx == 0):
totalDownPerson += 1
to.counted = True
trackableObjects[cord[8]] = to
draw_boxes(im0, bbox_xyxy, identities, categories, names)
cv2.line(im0, (0, height // 2), (width, height // 2), (0, 255, 255), 2)
cv2.putText(im0, 'Up Person : ' + str(totalUp), (int(width * 0.1), int(height * 0.05)),
cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 0, 100), 2)
cv2.putText(im0, 'Down person : ' + str(totalDown), (int(width * 0.1), int(height * 0.1)),
cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 0, 100), 2)
Conclusion:
In this blog post, we explored how to use YOLOv7 for person counting. With its efficient and accurate object detection capabilities, YOLOv7 has the potential to be a valuable tool in various applications that require person counting. By following the steps outlined in this post, you can easily use YOLOv7 for person counting in your projects.
Reference :
[1] https://github.com/RizwanMunawar/yolov7-object-tracking.git
[2] https://github.com/WongKinYiu/yolov7.git
Feel free to connect:
LinkedIN : https://www.linkedin.com/in/gopalkatariya44/
Github : https://github.com/gopalkatariya44/
Instagram : https://www.instagram.com/_gk_44/
Thanks !