Users Online

· Guests Online: 40

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Python Project - Real-time Human Detection & Counting

Python Project - Real-time Human Detection & Counting

BY  · UPDATED · AUGUST 6, 2020

 

 

In this python project, we are going to build the Human Detection and Counting System through Webcam or you can give your own video or images. This is an intermediate level deep learning project on computer vision, which will help you to master the concepts and make you an expert in the field of Data Science. Let’s build an exciting project.

human detection project output

Human Detection with Computer Vision


Project Prerequisites

The project in Python requires you to have basic knowledge of python programming and the OpenCV library. We will be needing following libraries:

  • OpenCV: A strong library used for machine learning
  • Imutils: To Image Processing
  • Numpy: Used for Scientific Computing. Image is stored in a numpy array.
  • Argparse: Used to give input in command line.

To install the required library, run the following code in your terminal.

  1. pip install opencv-python
  2. pip install imutils
  3. pip install numpy

Download Project Code

Before proceeding ahead, please download the source of real-time human detection project: Human Detection & Counting Project

Histogram of Oriented Gradient Descriptor

HOG is a feature descriptor used in computer vision and image processing for the purpose of object detection. This is one of the most popular techniques for object detection, to our fortune, OpenCV has already been implemented in an efficient way to combine the HOG Descriptor algorithm with Support Vector Machine or SVM.

Steps To Build Human Detection Project

 

1. Import the libraries:

  1. import cv2
  2. import imutils
  3. import numpy as np
  4. import argparse

2. Create a model which will detect Humans:

As discussed earlier, We will use HOGDescriptor with SVM already implemented in OpenCV.  Below code will do this work:

  1. HOGCV = cv2.HOGDescriptor() 
  2. HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

cv2.HOGDescriptor_getDefaultPeopleDetector() calls the pre-trained model for Human detection of OpenCV and then we will feed our support vector machine with it.

 

 

3. Detect() method:

Here, the actual magic will happen.

Video: A video combines a sequence of images to form a moving picture. We call these images as Frame. So in general we will detect the person in the frame. And show it one after another that it looks like a video.

That is exactly what our Detect() method will do.  It will take a frame to detect a person in it. Make a box around a person and show the frame..and return the frame with person bounded by a green box.

  1. def detect(frame):
  2. bounding_box_cordinates, weights = HOGCV.detectMultiScale(frame, winStride = (4, 4), padding = (8, 8), scale = 1.03) 
  3. person = 1 
  4. for x,y,w,h in bounding_box_cordinates:
  5. cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2) 
  6. cv2.putText(frame, f'person {person}', (x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1) 
  7. person += 1 
  8. cv2.putText(frame, 'Status : Detecting ', (40,40), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255,0,0), 2) 
  9. cv2.putText(frame, f'Total Persons : {person-1}', (40,70), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255,0,0), 2) 
  10. cv2.imshow('output', frame) 
  11.  
  12. return frame

Everything will be done by detectMultiScale(). It returns 2-tuple.

  1. List containing Coordinates of bounding Box of person.
    Coordinates are in form X, Y, W, H.
    Where x,y are starting coordinates of box and w, h are width and height of box respectively.
  2. Confidence Value that it is a person.

Now, We have our detect method. Let’s Create a Detector.

 

4. HumanDetector() method

There are two ways of getting Video.

  1. Web Camera
  2. Path of file stored

In this deep learning project, we can take images also. So our method will check if a path is given then search for the video or image in the given path and operate. Otherwise, it will open the webCam.

  1. def humanDetector(args):
  2. image_path = args["image"]
  3. video_path = args['video']
  4. if str(args["camera"]) == 'true' : camera = True
  5. else : camera = False
  6. writer = None
  7. if args['output'] is not None and image_path is None:
  8. writer = cv2.VideoWriter(args['output'],cv2.VideoWriter_fourcc(*'MJPG'), 10, (600,600))
  9. if camera:
  10. print('[INFO] Opening Web Cam.')
  11. detectByCamera(ouput_path,writer)
  12. elif video_path is not None:
  13. print('[INFO] Opening Video from path.')
  14. detectByPathVideo(video_path, writer)
  15. elif image_path is not None:
  16. print('[INFO] Opening Image from path.')
  17. detectByPathImage(image_path, args['output'])

5. DetectByCamera() method

  1. def detectByCamera(writer):
  2. video = cv2.VideoCapture(0)
  3. print('Detecting people...')
  4. while True:
  5. check, frame = video.read()
  6. frame = detect(frame)
  7. if writer is not None:
  8. writer.write(frame)
  9. key = cv2.waitKey(1)
  10. if key == ord('q'):
  11. break
  12. video.release()
  13. cv2.destroyAllWindows()

cv2.VideoCapture(0) passing 0 in this function means we want to record from a webcam. video.read() read frame by frame. It returns a check which is True if this was able to read a frame otherwise False.

Now, For each Frame, we will call detect() method. Then we write the frame in our output file.

 

6. DetectByPathVideo() method

This method is very similar to the previous method except we will give a path to the Video. First, we check if the video on the provided path is found or not.

Note – A full path must be given.

  1. def detectByPathVideo(path, writer):
  2. video = cv2.VideoCapture(path)
  3. check, frame = video.read()
  4. if check == False:
  5. print('Video Not Found. Please Enter a Valid Path (Full path of Video Should be Provided).')
  6. return
  7. print('Detecting people...')
  8. while video.isOpened():
  9. #check is True if reading was successful
  10. check, frame = video.read()
  11. if check:
  12. frame = imutils.resize(frame , width=min(800,frame.shape[1]))
  13. frame = detect(frame)
  14. if writer is not None:
  15. writer.write(frame)
  16. key = cv2.waitKey(1)
  17. if key== ord('q'):
  18. break
  19. else:
  20. break
  21. video.release()
  22. cv2.destroyAllWindows()
  23. def detectByCamera(writer):
  24. video = cv2.VideoCapture(0)
  25. print('Detecting people...')
  26. while True:
  27. check, frame = video.read()
  28. frame = detect(frame)
  29. if writer is not None:
  30. writer.write(frame)
  31. key = cv2.waitKey(1)
  32. if key == ord('q'):
  33. break
  34. video.release()
  35. cv2.destroyAllWindows()

The implementation is similar to the previous function except for each frame we will check that it successfully reads the frame or not. At the end when the frame is not read we will end the loop.

 

7. DetectByPathimage() method

This method is used if a person needs to be detected from an image.

  1. def detectByPathImage(path, output_path):
  2. image = cv2.imread(path)
  3. image = imutils.resize(image, width = min(800, image.shape[1]))
  4. result_image = detect(image)
  5. if output_path is not None:
  6. cv2.imwrite(output_path, result_image)
  7. cv2.waitKey(0)
  8. cv2.destroyAllWindows()

 

8. Argparse() method

The function argparse() simply parses and returns as a dictionary the arguments passed through your terminal to our script. There will be Three arguments within the Parser:

  1. Image: The path to the image file inside your system
  2. Video: The path to the Video file inside your system
  3. Camera: A variable that if set to ‘true’ will call the cameraDetect() method.
  1. def argsParser():
  2. arg_parse = argparse.ArgumentParser()
  3. arg_parse.add_argument("-v", "--video", default=None, help="path to Video File ")
  4. arg_parse.add_argument("-i", "--image", default=None, help="path to Image File ")
  5. arg_parse.add_argument("-c", "--camera", default=False, help="Set true if you want to use the camera.")
  6. arg_parse.add_argument("-o", "--output", type=str, help="path to optional output video file")
  7. args = vars(arg_parse.parse_args())
  8. return args

 

9. Main function

We have reached the end of our project.

  1. if __name__ == "__main__":
  2. HOGCV = cv2.HOGDescriptor()
  3. HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
  4. args = argsParser()
  5. humanDetector(args)

Instead of declaring our model above, we can declare it in our main function.

 

 

Run the Human Detection Project

To run the human detection deep learning project, please run below-mentioned commands as per requirements

1. To give video file as input:

  1. python main.py -v ‘Path_to_video’

2. To give image file as input:

  1. python main.py -i ‘Path_to-image’

3. To use the camera:

  1. python main.py -c True

4. To save the output:

  1. Python main.py -c True -o ‘file_name’

Project Output

Now, after running the human detection python project with multiple images and video, we will get:

human counting output

human counting project output 2

human detection project output

Summary

In this deep learning project, we have learned how to create a people counter using HOG and OpenCV to generate an efficient people counter. We developed the project where you can supply the input as: video, image, or even live camera. This is an intermediate level project, which will surely help you in mastering python and deep learning libraries.


Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,820,357 unique visits