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

Pedestrian Detection using OpenCV-Python

Last Updated : 03 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 libraries for Computer Vision tasks like face recognition, motion detection, object detection, etc. In this tutorial, we are going to build a basic Pedestrian Detector for images and videos using OpenCV. Pedestrian detection is a very important area of research because it can enhance the functionality of a pedestrian protection system in Self Driving Cars. We can extract features like head, two arms, two legs, etc, from an image of a human body and pass them to train a machine learning model. After training, the model can be used to detect and track humans in images and video streams. However, OpenCV has a built-in method to detect pedestrians. It has a pre-trained HOG(Histogram of Oriented Gradients) + Linear SVM model to detect pedestrians in images and video streams.

Histogram of Oriented Gradients

This algorithm checks directly surrounding pixels of every single pixel. The goal is to check how darker is the current pixel compared to the surrounding pixels. The algorithm draws and arrows showing the direction of the image getting darker. It repeats the process for each and every pixel in the image. At last, every pixel would be replaced by an arrow, these arrows are called Gradients. These gradients show the flow of light from light to dark. By using these gradients algorithms perform further analysis. To learn more about HOG, read Navneet Dalal and Bill Triggs research paper on HOG for Human Detection..

Requirements

opencv-python 3.4.2

imutils 0.5.3

To install the above modules type the below command in the terminal.

pip install opencv-python 3.4.2
pip install imutils 0.5.3

Example 1:

Lets make the program to detect pedestrians in an Image:

Image Used: python-opncv 

Python3




import cv2
import imutils
  
# Initializing the HOG person
# detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
  
# Reading the Image
image = cv2.imread('img.png')
  
# Resizing the Image
image = imutils.resize(image,
                       width=min(400, image.shape[1]))
  
# Detecting all the regions in the
# Image that has a pedestrians inside it
(regions, _) = hog.detectMultiScale(image,
                                    winStride=(4, 4),
                                    padding=(4, 4),
                                    scale=1.05)
  
# Drawing the regions in the Image
for (x, y, w, h) in regions:
    cv2.rectangle(image, (x, y),
                  (x + w, y + h),
                  (0, 0, 255), 2)
 
# Showing the output Image
cv2.imshow("Image", image)
cv2.waitKey(0)
  
cv2.destroyAllWindows()


Output: python-opnecv-1 Example 2: Lets make the program to detect pedestrians in a video: 

Python3




import cv2
import imutils
  
# Initializing the HOG person
# detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
  
cap = cv2.VideoCapture('vid.mp4')
  
while cap.isOpened():
    # Reading the video stream
    ret, image = cap.read()
    if ret:
        image = imutils.resize(image,
                               width=min(400, image.shape[1]))
  
        # Detecting all the regions
        # in the Image that has a
        # pedestrians inside it
        (regions, _) = hog.detectMultiScale(image,
                                            winStride=(4, 4),
                                            padding=(4, 4),
                                            scale=1.05)
  
        # Drawing the regions in the
        # Image
        for (x, y, w, h) in regions:
            cv2.rectangle(image, (x, y),
                          (x + w, y + h),
                          (0, 0, 255), 2)
  
        # Showing the output Image
        cv2.imshow("Image", image)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    else:
        break
 
cap.release()
cv2.destroyAllWindows()


Output:



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
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 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
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 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
White and black dot detection using OpenCV | Python
Image processing using Python is one of the hottest topics in today's world. But image processing is a bit complex and beginners get bored in their first approach. So in this article, we have a very basic image processing python program to count black dots in white surface and white dots in the black surface using OpenCV functions (cv2.imread, cv2.
4 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
Gun Detection using Python-OpenCV
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 Re
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
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
Brightness Control With Hand Detection using OpenCV in Python
In this article, we are going to make a Python project that uses OpenCV and Mediapipe to see hand gesture and accordingly set the brightness of the system from a range of 0-100. We have used a HandTracking module that tracks all points on the hand and detects hand landmarks, calculate the distance between thumb tip and index fingertip and maps the
6 min read
Detection of a specific color(blue here) using OpenCV with Python
The following code in python uses OpenCV library which is employed for image processing techniques. The program allows the detection of a specific color in a live stream video content. A video is composed of infinite frames at different time instants. We will detect the colour of every frame one by one. The code will only compile in linux environme
4 min read
Vehicle detection using OpenCV Python
Object Detection means identifying the objects in a video or image. In this article, we will learn how to detect vehicles using the Haar Cascade classifier and OpenCV. We will implement the vehicle detection on an image and as a result, we will get a video in which vehicles will be detected and it will be represented by a rectangular frame around i
3 min read
Real time object color detection using OpenCV
In this article, we will discuss how to detect a monochromatic colour object using python and OpenCV. Monochromatic color means light of a single wavelength. We will use the video, captured using a webcam as input and try to detect objects of a single color, especially Blue. But you can detect any color if you set the range properly, we'll discuss
4 min read
Blob Detection Using OpenCV
Blob detection is a basic method in computer vision used to locate areas of interest in a picture. These "blobs" frequently depict elements or items that have similar characteristics, like color, texture, or intensity. In this post, we explore the realm of blob identification with OpenCV, an effective computer vision toolkit. In this article, we lo
5 min read
Text Detection and Extraction using OpenCV and OCR
OpenCV (Open source computer vision) is a library of programming functions mainly aimed at real-time computer vision. OpenCV in python helps to process an image and apply various functions like resizing image, pixel manipulations, object detection, etc. In this article, we will learn how to use contours to detect the text in an image and save it to
5 min read
Age Detection using Deep Learning in OpenCV
In this tutorial, we are going to see the entire process of creating an Age predictor and Gender classifier project using OpenCV. Age Detection Our goal here is to create a program that will predict the gender and age of the person using an image.  But predicting age might not be as simple as you think, why? You might be thinking that age predictio
5 min read
Feature detection and matching with OpenCV-Python
In this article, we are going to see about feature detection in computer vision with OpenCV in Python. Feature detection is the process of checking the important features of the image in this case features of the image can be edges, corners, ridges, and blobs in the images. In OpenCV, there are a number of methods to detect the features of the imag
5 min read
Python OpenCV - Roberts Edge Detection
Edge detection refers to a set of mathematical techniques for recognizing points in a digital image where the image brightness abruptly changes or, more formally, where there are discontinuities. The sharp fluctuations in image brightness are usually grouped into a collection of curved line segments called edges. Roberts Edge DetectionThe Roberts o
3 min read
Eye blink detection with OpenCV, Python, and dlib
In this article, we are going to see how to detect eye blink using OpenCV, Python, and dlib. This is a fairly simple task and it requires you to have a basic understanding of OpenCV and how to implement face landmark detection programs using OpenCV and dlib, since we'll be using that as the base for today's project. Stepwise ImplementationStep 1: I
6 min read
Python OpenCV - Drowsiness Detection
The number of fatalities on the road due to drowsiness is very high. Thus python allows the model of deep learning algorithm via including the use of OpenCV. Drowsiness Detection is the detection of a person to check whether the person is feeling sleepy while performing a significant task. This detection has many applications in medical and safety
9 min read
Line detection in python with OpenCV | Houghline method
The Hough Transform is a method that is used in image processing to detect any shape, if that shape can be represented in mathematical form. It can detect the shape even if it is broken or distorted a little bit.We will see how Hough transform works for line detection using the HoughLine transform method. To apply the Houghline method, first an edg
6 min read
Opencv Python program for Face Detection
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects. Here is the steps to download th
2 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
OpenCV C++ Program for coin detection
The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV. Things to know: The code will only compile in Linux environment. To run in windows, please use the file: 'coin.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious ch
4 min read
Region Proposal Object Detection with OpenCV, Keras, and TensorFlow
In this article, we'll learn how to implement Region proposal object detection with OpenCV, Keras and TensorFlow. Install all the dependencies Use the pip command for installing all the dependencies pip install tensorflow keras imutils pip install opencv-contrib-python Note: Make sure about installing the above OpenCV package otherwise you might fa
9 min read
OpenCV Selective Search For Object Detection
OpenCV is a Python library that is used to study images and video streams. It basically extracts the pixels from the images and videos (stream of image) so as to study the objects and thus obtain what they contain. It contains low-level image processing and high-level algorithms for object detection, feature matching etc. In this article, we will d
14 min read
Article Tags :
Practice Tags :