Real-Time Counting People using OpenCV in Python

Real-Time Counting People using OpenCV in Python With Source Code

The Real-Time Counting People OpenCV Python was developed using Python OpenCV, in this Python project we are going to build the Human Detection and Counting System through a Webcam or you can give your own video or images.

A Counting People OpenCV Python 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.

The project in Python requires you to have basic knowledge of Python programming and the OpenCV library.

This OpenCV Python Project also includes a downloadable Python Project With Source Code for free, just find the downloadable source code below and click to start downloading.

By the way, if you are new to Python programming and don’t know how to use the Python IDE, I have here a list of the Best Python IDE for Windows, Linux, and Mac OS that will suit you.

I also have here How to Download and Install the Latest Version of Python on Windows.

To start executing Real-Time Counting People OpenCV Python With Source Code, make sure that you have installed Python 3.9 and PyCharm on your computer.

How to run the Real-Time Human Detection and Counting using OpenCV Python: Step-by-step Guide with source code

Time needed: 5 minutes

These are the steps on how to run Real-Time Counting People OpenCV Python With Source Code

  • Step 1: Download the given source code below.

    First, download the given source code below and unzip the source code.
    Count people download source code

  • Step 2: Import the project to your PyCharm IDE.

    Next, import the source code you’ve downloaded to your PyCharm IDE.
    count people open project

  • Step 3: Run the project.

    Lastly, run the project with the command “py main.py”
    count people run project

Installed Libraries

import cv2
import imutils
import numpy as np
import argparse

Complete Source Code

import cv2
import imutils
import numpy as np
import argparse
#frame
def detect(frame):
    bounding_box_cordinates, weights =  HOGCV.detectMultiScale(frame, winStride = (4, 4), padding = (8, 8), scale = 0.5)
    
    person = 1
    for x,y,w,h in bounding_box_cordinates:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
        cv2.putText(frame, f'person {person}', (x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1)
        person += 1
    
    cv2.putText(frame, 'Status : Detecting ', (40,40), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255,0,0), 2)
    cv2.putText(frame, f'Total Persons : {person-1}', (40,70), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255,0,0), 2)
    cv2.imshow('output', frame)

    return frame

def detectByPathVideo(path, writer):

    video = cv2.VideoCapture(path)
    check, frame = video.read()
    if check == False:
        print('Video Not Found. Please Enter a Valid Path (Full path of Video Should be Provided).')
        return

    print('Detecting people...')
    while video.isOpened():
        #check is True if reading was successful 
        check, frame =  video.read()

        if check:
            frame = imutils.resize(frame , width=min(800,frame.shape[1]))
            frame = detect(frame)
            
            if writer is not None:
                writer.write(frame)
            
            key = cv2.waitKey(1)
            if key== ord('q'):
                break
        else:
            break
    video.release()
    cv2.destroyAllWindows()

def detectByCamera(writer):
    video = cv2.VideoCapture(0)
    print('Detecting people...')

    while True:
        check, frame = video.read()

        frame = detect(frame)
        if writer is not None:
            writer.write(frame)

        key = cv2.waitKey(1)
        if key == ord('q'):
                break

    video.release()
    cv2.destroyAllWindows()

def detectByPathImage(path, output_path):
    image = cv2.imread(path)

    image = imutils.resize(image, width = min(800, image.shape[1])) 

    result_image = detect(image)

    if output_path is not None:
        cv2.imwrite(output_path, result_image)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


def humanDetector(args):
    image_path = args["image"]
    video_path = args['video']
    if str(args["camera"]) == 'true' : camera = True 
    else : camera = False

    writer = None
    if args['output'] is not None and image_path is None:
        writer = cv2.VideoWriter(args['output'],cv2.VideoWriter_fourcc(*'MJPG'), 10, (600,600))

    if camera:
        print('[INFO] Opening Web Cam.')
        detectByCamera(writer)
    elif video_path is not None:
        print('[INFO] Opening Video from path.')
        detectByPathVideo(video_path, writer)
    elif image_path is not None:
        print('[INFO] Opening Image from path.')
        detectByPathImage(image_path, args['output'])

def argsParser():
    arg_parse = argparse.ArgumentParser()
    arg_parse.add_argument("-v", "--video", default=None, help="path to Video File ")#command
    arg_parse.add_argument("-i", "--image", default=None, help="path to Image File ")#command
    arg_parse.add_argument("-c", "--camera", default=False, help="Set true if you want to use the camera.")#command
    arg_parse.add_argument("-o", "--output", type=str, help="path to optional output video file")#command
    args = vars(arg_parse.parse_args())

    return args

if __name__ == "__main__":
    HOGCV = cv2.HOGDescriptor()
    HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

    args = argsParser()
    humanDetector(args)

#main module of the system

Download the Source Code below

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 a 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.

Related Articles

Inquiries

If you have any questions or suggestions about Real-Time Counting People OpenCV Python With Source Code, please feel free to leave a comment below.

Frequently Asked Questions

How does the real-time people counter work?

Pedestrian detection via Haar (haarcascade_fullbody.xml) or a deeper model (YOLO, MobileNet-SSD) finds bounding boxes for each person per frame. A simple object tracker (CSRT or KCF) gives each box a stable ID across frames. When a centroid crosses a virtual counting line (e.g. the middle of the frame), increment in/out counters. Useful for shop foot-traffic, transit hubs, classroom attendance.

What Python and library versions do I need?

Python 3.10, 3.11, or 3.12 (avoid 3.13 until all DL wheels catch up). Install with: pip install opencv-python numpy. For deep learning models add: tensorflow keras (CPU build is fine for most demos), torch torchvision (PyTorch alternative), mediapipe (for face/hand/pose). Some projects also need: pytesseract for OCR, pyzbar for barcode, dlib for legacy face-landmark predictor.

Do I need a GPU to run this deep learning project?

For inference on a pretrained model: no, CPU runs at 10-30 FPS for most computer-vision tasks. For TRAINING a custom model: GPU strongly recommended (CPU works but slow). Free GPU options for training: Google Colab Free (12-hour sessions, sufficient for most BSIT capstones), Kaggle Notebooks Free. Buying a $1000+ GPU just for capstone is overkill.

Can I use this deep learning project for a BSIT or CSE capstone?

Yes, but extend it. A single OpenCV deep-learning demo (face detection, object detection alone) is too narrow for full capstone scope. Combine with a real domain wrapper: an attendance system using face recognition, a traffic monitoring system using vehicle detection, a wildlife camera using object detection, a driver-monitoring app using drowsiness detection. Add database logging, simple UI, and Chapter 1-5 manuscript.

Why does my model give wrong predictions or low accuracy?

Three most common causes: (1) Input preprocessing mismatch: the model expects 224×224 RGB normalized to [0,1] or [-1,1]; using BGR (OpenCV default) or wrong size produces garbage. (2) Insufficient training data: if you trained your own model on under 1,000 samples per class, accuracy plateaus low. Augment with cv2.flip, rotate, brightness shifts. (3) Lighting and angle drift between training and live use: train on data that matches the deployment environment.

Where can I find more deep learning project ideas with source code?

Browse our Deep Learning Projects hub for 19+ vision demos. For broader AI / ML / RAG / NLP capstones see 100+ AI Capstone Project Ideas. For pure ML (no deep learning) see Machine Learning Projects.

Angel Jude Suarez

Full-Stack Developer at PIES IT Solution

Focuses on Python development, machine learning, and AI integration. Has built production AI systems including OpenAI Whisper integration for medical transcription and GPT-4o-powered diagnosis assistance. Strong background in pandas, scikit-learn, and TensorFlow.

Expertise: Python · PHP · Java · VB.NET · ASP.NET · Machine Learning · AI Integration · OpenCV · Django · CodeIgniter  · View all posts by Angel Jude Suarez →

2 thoughts on “Real-Time Counting People using OpenCV in Python”

Leave a Comment