Build a People Counter with Raspberry Pi — camera placement & calibration (works for tall people)

Build a People Counter with Raspberry Pi

A Raspberry Pi can do more than run applications and control electronics. With a camera and Python, you can build a people counter that detects movement and estimates how many people enter or leave a room.

In this tutorial, you will build a simple people-counting system using a Raspberry Pi, a compatible camera, and OpenCV. The program detects moving objects, tracks their approximate positions, and counts when they cross a virtual line.

This project is useful for experimenting with visitor counting in small shops, offices, classrooms, workshops, and other indoor spaces.

What you will build:

  • A camera-based people-counting system.
  • A virtual counting line displayed on the camera image.
  • Separate counters for people entering and leaving.
  • A live preview showing the current totals.
  • A CSV log containing the counting events.

The initial implementation uses motion detection and lightweight tracking rather than a machine-learning person detector. It is designed for learning and controlled environments, not as a guaranteed-accurate commercial occupancy system.

1. How the Raspberry Pi People Counter Works

The camera continuously captures images. OpenCV compares consecutive frames to identify moving objects, groups nearby pixels into motion regions, and tracks those regions as they move across the image.

When a tracked object crosses the virtual counting line, the program determines the direction of travel and increments the appropriate counter.

The process follows these steps:

  1. Capture a frame from the camera.
  2. Detect moving regions using background subtraction.
  3. Identify candidate objects based on their size.
  4. Track their approximate positions across frames.
  5. Detect crossings of the virtual line.
  6. Update the entry or exit counter.
  7. Display the totals and save counting events.

OpenCV documents background subtraction as a common technique for separating moving foreground objects from a stationary background, including in visitor-counting applications. https://opencv2-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_video/py_bg_subtraction/py_bg_subtraction.html

Important limitation

Motion detection does not reliably identify a person. A shadow, a moving bag, or two people walking together can confuse the algorithm. The tutorial therefore provides a basic prototype that works best with a fixed camera, good lighting, a clear walkway, and one person crossing at a time.

For more reliable results, see the section on improving accuracy later in this guide.

2. Hardware Requirements

You will need the following components.

ComponentPurpose
Raspberry Pi 3 Model B/B+, or newerRuns the counting software
Compatible Raspberry Pi cameraCaptures video
microSD cardStores Raspberry Pi OS and the program
Reliable power supplyPowers the Raspberry Pi
Camera ribbon cableConnects the camera to the board
Optional monitor, keyboard, and mouseUseful during initial setup

A Raspberry Pi 3 is sufficient for a basic motion-detection prototype. Use a low capture resolution, such as 640 × 480, to reduce processing requirements.

The official Raspberry Pi camera documentation explains camera compatibility and setup. https://www.raspberrypi.com/documentation/accessories/camera.html

3. Install Raspberry Pi OS

Install a supported Raspberry Pi OS release on your microSD card. Raspberry Pi OS Lite is a good option if you intend to run the counter without a desktop environment.

Boot the Raspberry Pi and update the installed packages:

sudo apt update
sudo apt full-upgrade -y
sudo reboot

After restarting, verify that the camera is detected:

rpicam-still --list-cameras

You should see information about the connected camera. If no camera is listed, check the ribbon cable, connector orientation, and camera compatibility.

On current Raspberry Pi OS releases, camera utilities use the rpicam- command names. Picamera2 is the supported Python interface for the modern Raspberry Pi camera stack. https://www.raspberrypi.com/documentation/computers/camera_software.html

4. Install Python and OpenCV

Install the required packages:

sudo apt install -y python3-picamera2 python3-opencv python3-numpy

These packages provide:

  • Picamera2: captures frames from the Raspberry Pi camera.
  • OpenCV: detects motion, finds contours, and draws the preview.
  • NumPy: supports image-array operations.

Test that Python can import the libraries:

python3 -c "import cv2, numpy; from picamera2 import Picamera2; print('Camera and OpenCV libraries are ready')"

If the command prints the confirmation message without an error, you can continue.

Install packages from Raspberry Pi OS where possible, rather than mixing system camera libraries with incompatible Python package versions.

5. Position the Camera

Mount the camera securely above or beside the entrance you want to monitor.

For the simplest setup:

  • Keep the camera stationary.
  • Frame a narrow walkway rather than a large room.
  • Ensure people cross the counting line in a consistent direction.
  • Avoid placing the line where people regularly stop or turn around.
  • Provide sufficient lighting throughout the counting period.

A slightly elevated camera angle can help separate people from the background. However, the best position depends on the room and the direction in which people move.

For a doorway, position the counting line across the path through which visitors enter and leave. You will adjust the line’s coordinates in the Python program.

6. Create the People-Counter Program

Create a project directory:

mkdir -p ~/people-counter
cd ~/people-counter

Create a Python file:

nano people_counter.py

Paste the following code:

import csv
import time
from datetime import datetime
from pathlib import Path

import cv2
from picamera2 import Picamera2


# -----------------------------
# Configuration
# -----------------------------

WIDTH = 640
HEIGHT = 480

# Horizontal counting line.
LINE_Y = HEIGHT // 2

# Count only objects with a contour area above this value.
MIN_AREA = 2500

# Maximum vertical movement between consecutive detections.
MAX_MATCH_DISTANCE = 55

# Avoid repeatedly counting the same track.
TRACK_TIMEOUT = 1.5

# Background subtraction settings.
MIN_DETECTION_GAP = 0.15

OUTPUT_DIR = Path.home() / "people-counter"
CSV_FILE = OUTPUT_DIR / "events.csv"

OUTPUT_DIR.mkdir(parents=True, exist_ok=True)


# -----------------------------
# Initialize camera
# -----------------------------

camera = Picamera2()

camera.configure(
    camera.create_video_configuration(
        main={
            "size": (WIDTH, HEIGHT),
            "format": "RGB888",
        }
    )
)

camera.start()
time.sleep(2)


# -----------------------------
# Initialize detection
# -----------------------------

background = cv2.createBackgroundSubtractorMOG2(
    history=300,
    varThreshold=40,
    detectShadows=True,
)

# Track format:
# id -> {"x": center_x, "y": center_y, "time": timestamp}
tracks = {}

next_track_id = 1

entered = 0
exited = 0

last_detection_time = 0

# Create the CSV file and header if necessary.
if not CSV_FILE.exists():
    with CSV_FILE.open("w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow([
            "timestamp",
            "direction",
            "entered_total",
            "exited_total",
        ])


def log_event(direction):
    """Append a counting event to the CSV file."""
    with CSV_FILE.open("a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow([
            datetime.now().isoformat(timespec="seconds"),
            direction,
            entered,
            exited,
        ])


def update_tracks(detections, now):
    """Match detections to existing tracks by proximity."""
    global next_track_id

    matched = set()

    for x, y, box in detections:
        best_id = None
        best_distance = MAX_MATCH_DISTANCE

        for track_id, track in tracks.items():
            if track_id in matched:
                continue

            distance = (
                (track["x"] - x) ** 2
                + (track["y"] - y) ** 2
            ) ** 0.5

            if distance < best_distance:
                best_distance = distance
                best_id = track_id

        if best_id is None:
            track_id = next_track_id
            next_track_id += 1

            tracks[track_id] = {
                "x": x,
                "y": y,
                "time": now,
                "box": box,
                "counted": False,
            }
        else:
            track_id = best_id

            old_y = tracks[track_id]["y"]
            new_y = y

            # Count a crossing of the horizontal line.
            if not tracks[track_id]["counted"]:
                if old_y < LINE_Y <= new_y:
                    count_event("IN")
                    tracks[track_id]["counted"] = True

                elif old_y > LINE_Y >= new_y:
                    count_event("OUT")
                    tracks[track_id]["counted"] = True

            tracks[track_id].update({
                "x": x,
                "y": y,
                "time": now,
                "box": box,
            })

        matched.add(track_id)


def count_event(direction):
    """Update totals and save a crossing event."""
    global entered, exited

    if direction == "IN":
        entered += 1
    else:
        exited += 1

    log_event(direction)

    print(
        f"{datetime.now():%H:%M:%S} | "
        f"{direction} | "
        f"Entered: {entered} | "
        f"Exited: {exited}"
    )


try:
    while True:
        now = time.monotonic()

        frame = camera.capture_array()

        # Reduce color processing by working in grayscale.
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        gray = cv2.GaussianBlur(gray, (5, 5), 0)

        mask = background.apply(gray)

        # Remove shadows and small noise.
        _, mask = cv2.threshold(
            mask, 200, 255, cv2.THRESH_BINARY
        )

        kernel = cv2.getStructuringElement(
            cv2.MORPH_RECT, (5, 5)
        )

        mask = cv2.morphologyEx(
            mask, cv2.MORPH_OPEN, kernel
        )

        mask = cv2.dilate(mask, kernel, iterations=2)

        detections = []

        contours, _ = cv2.findContours(
            mask,
            cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE,
        )

        for contour in contours:
            area = cv2.contourArea(contour)

            if area < MIN_AREA:
                continue

            x, y, w, h = cv2.boundingRect(contour)

            center_x = x + w // 2
            center_y = y + h // 2

            detections.append((
                center_x,
                center_y,
                (x, y, w, h),
            ))

        # Update approximate object tracks.
        update_tracks(detections, now)

        # Remove tracks that have disappeared.
        expired = [
            track_id
            for track_id, track in tracks.items()
            if now - track["time"] > TRACK_TIMEOUT
        ]

        for track_id in expired:
            del tracks[track_id]

        # Draw the counting line.
        cv2.line(
            frame,
            (0, LINE_Y),
            (WIDTH, LINE_Y),
            (255, 0, 0),
            2,
        )

        # Draw detected objects and their IDs.
        for track_id, track in tracks.items():
            x, y, w, h = track["box"]

            cv2.rectangle(
                frame,
                (x, y),
                (x + w, y + h),
                (0, 255, 0),
                2,
            )

            cv2.putText(
                frame,
                f"ID {track_id}",
                (x, max(20, y - 8)),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                (0, 255, 0),
                1,
            )

        # Display totals.
        cv2.putText(
            frame,
            f"IN: {entered}  OUT: {exited}",
            (10, 30),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.8,
            (255, 255, 255),
            2,
        )

        cv2.imshow("Raspberry Pi People Counter", frame)

        key = cv2.waitKey(1) & 0xFF

        if key == ord("q"):
            break

        # Optional frame-rate limit for the Pi 3.
        elapsed = time.monotonic() - now
        remaining = MIN_DETECTION_GAP - elapsed

        if remaining > 0:
            time.sleep(remaining)

finally:
    camera.stop()
    cv2.destroyAllWindows()

Save the file and exit the editor.

How the code works

The program uses OpenCV’s MOG2 background subtractor to identify moving regions. It then filters small contours and assigns approximate track IDs based on the distance between detected centers.

When a track moves from above the line to below it, the counter records an entry. Movement in the opposite direction records an exit.

The totals are displayed in the preview window and printed to the terminal. Each crossing is also appended to events.csv.

Important: This is a simplified tracker, not a person-recognition algorithm. It can lose track IDs, merge nearby people into one contour, or count non-human movement. It is best treated as an educational prototype.

7. Run the People Counter

Start the program:

cd ~/people-counter
python3 people_counter.py

A window should appear showing the camera image, a horizontal counting line, detected motion regions, and the current entry and exit totals.

Walk through the monitored area to test it.

  • Cross from the upper side of the line to the lower side to test the entry count.
  • Cross in the opposite direction to test the exit count.
  • Press q to close the preview and stop the program.

If you are using Raspberry Pi OS Lite without a graphical desktop, cv2.imshow() will not provide a local window. You can instead remove the preview-related calls and use the terminal and CSV log, or adapt the program to display the camera feed through a web page.

8. Configure the Counting Line

The line is configured near the beginning of the program:

LINE_Y = HEIGHT // 2

With a frame height of 480 pixels, this places the line at vertical coordinate 240.

To move the line higher:

LINE_Y = 180

To move it lower:

LINE_Y = 300

The correct position depends on the camera angle and the doorway. Put the line where visitors have a clear direction of travel and are unlikely to stop or turn around.

The example uses a horizontal line. For a different camera orientation, you can implement a vertical line or a line at an angle.

9. View the Counting Log

The program creates a CSV file at:

/home/YOUR_USERNAME/people-counter/events.csv

Replace YOUR_USERNAME with your Linux username.

Display the file:

cat ~/people-counter/events.csv

Example:

timestamp,direction,entered_total,exited_total
2026-10-11T10:15:20,IN,1,0
2026-10-11T10:17:04,OUT,1,1
2026-10-11T10:20:12,IN,2,1

The CSV can be opened in a spreadsheet application to review activity over time.

The difference between the two totals gives an estimate of the number of people who entered minus the number who exited during the period being measured. It does not necessarily represent the actual occupancy if the system started counting after people were already inside, or if it missed or duplicated events.

10. Run the Counter Without a Monitor

If you use Raspberry Pi OS Lite, you may want to run the program through SSH without a desktop.

The simplest adjustment is to remove or disable the following preview lines:

cv2.imshow("Raspberry Pi People Counter", frame)
key = cv2.waitKey(1) & 0xFF

if key == ord("q"):
    break

Also remove the cv2.destroyAllWindows() call from the cleanup block. The program will then run without displaying a local window, while still writing events to the CSV file.

For a production-style headless setup, add signal handling and run the program through a systemd service so it can restart after a failure or reboot.

11. Improve Accuracy

A basic motion-based counter is easy to build, but it has several limitations. These improvements can make the system more useful.

Use a person detector

A person detector identifies people rather than simply detecting moving regions. A lightweight model can reduce false detections caused by shadows and other objects, although overlapping people can still be difficult to count accurately.

For a Raspberry Pi 3, choose a model and input resolution carefully to avoid excessive processing latency.

Improve object tracking

The example uses nearest-center matching. This is simple but can fail when people walk close together or temporarily disappear behind one another.

A more robust tracker can use bounding-box overlap, velocity estimates, or a dedicated tracking algorithm. The counter should preserve a person’s track long enough to determine whether that person actually crossed the line.

Use a better camera angle

Avoid a camera position where people completely overlap in the image. A clear view of the crossing area often improves results more than increasing image resolution.

Tune the detection threshold

The value of MIN_AREA controls which moving regions are considered large enough to track.

MIN_AREA = 2500

If the program ignores people, try lowering the value. If it detects small moving objects or noise, increase it. The appropriate value depends on camera distance, resolution, and the size of people in the frame.

Test before relying on the results

Compare the program’s totals against a manual count during different conditions:

  • One person entering at a time.
  • Two people walking close together.
  • People stopping or turning around.
  • Changes in lighting.
  • Busy periods with overlapping movement.

Do not use this prototype as the sole source of safety-critical occupancy information.

12. Protect Privacy

A people counter can often be designed to record only counting events rather than storing video. This reduces the amount of sensitive information collected.

Consider these precautions:

  • Avoid recording or retaining video unless necessary.
  • Inform visitors when monitoring is used, where required by local law.
  • Restrict access to the Raspberry Pi and its logs.
  • Keep the operating system updated.
  • Do not expose the camera or control interface directly to the public internet.
  • Establish a retention policy for counting logs.

If you add a web dashboard for remote monitoring, use authenticated access and a VPN or properly secured reverse proxy.

13. Troubleshooting

The camera is not detected

Check the ribbon cable and run:

rpicam-still --list-cameras

Confirm that your Raspberry Pi OS version supports Picamera2 and that the camera is compatible. The official camera documentation provides installation and troubleshooting guidance: https://www.raspberrypi.com/documentation/computers/camera_software.html

The preview window does not open

The cv2.imshow() function requires a graphical environment. On Raspberry Pi OS Lite, use a headless version of the script or provide a web-based dashboard.

People are not counted

Check whether the person creates a sufficiently large contour. Try adjusting MIN_AREA, improve the lighting, and make sure people cross the line fully rather than stopping on it.

The counter counts one person several times

The basic tracking algorithm can create a new track when detections disappear or change position abruptly. Improve the tracking method, increase the allowed matching distance where appropriate, and tune the camera position. Simply increasing the track timeout will not fix every duplicate count.

The Raspberry Pi 3 is slow

Reduce the frame size, keep the camera fixed, avoid unnecessary image processing, and close other CPU-intensive programs. If you need reliable multi-person tracking at a high frame rate, consider a newer Raspberry Pi or a more capable vision-processing setup.

Conclusion

Building a people counter with Raspberry Pi is a practical way to learn about computer vision, camera capture, motion detection, object tracking, and data logging.

The prototype in this guide uses Picamera2 and OpenCV to detect motion, track candidate objects, and count crossings of a virtual line. It can run on a Raspberry Pi 3 under suitable conditions, but its accuracy is limited because it does not reliably distinguish people from other moving objects.

For a more advanced project, add a lightweight person-detection model, improve tracking, and create a web dashboard showing hourly or daily totals. This can turn the prototype into a useful visitor-analytics experiment for a small space.