projectduniya.com

Smart Parking Management System Using OpenCV and Python: Vehicle Detection and Parking Slot Monitoring

Smart Parking Management System Using OpenCV and Python: Vehicle Detection and Parking Slot Monitoring
Smart Parking Management System Using OpenCV and Python: Vehicle Detection and Parking Slot Monitoring

Introduction

Finding an available parking space can be difficult in busy areas such as shopping centres, colleges, hospitals, office buildings, and residential complexes. Drivers may spend unnecessary time moving around a parking area because they do not know which spaces are vacant.

A Smart Parking Management System uses computer vision to monitor parking spaces and identify whether each space is occupied or available. A camera captures images or video of the parking area, and an image-processing application analyzes the parking spaces to determine their status.

In this project, you will build a Smart Parking Management System using Python and OpenCV. The application will process a parking-lot image or video, examine predefined parking-space regions, classify each space as occupied or vacant, and display the available-space count.

Project objective: Develop a computer-vision application that monitors predefined parking spaces using a fixed camera and displays their occupancy status in near real time.

1. Project Overview

Project componentDescription
Project titleSmart Parking Management System
Programming languagePython
Computer vision libraryOpenCV
Supporting librariesNumPy, Pickle
InputParking-lot image or video
Processing methodImage processing and region-based occupancy classification
OutputOccupied spaces, vacant spaces, and visual parking status
Optional interfaceStreamlit dashboard

2. Main Features of the System

The basic project can include the following features:

  • Read a parking-lot image or video from a camera.
  • Define individual parking spaces using rectangular coordinates.
  • Analyze each parking-space region using OpenCV.
  • Classify each space as occupied or vacant.
  • Display vacant and occupied spaces using different colours.
  • Calculate the total number of available spaces.
  • Show a live or repeatedly updated parking status.
  • Extend the application with a dashboard and occupancy history.

3. How the Smart Parking System Works

The system uses a fixed camera that provides a consistent view of the parking area. Each parking space is marked once, and the application checks those regions in subsequent frames.

  1. Capture an image: Read a parking-lot image or obtain a frame from a video.
  2. Define parking spaces: Store the coordinates of each parking-space region.
  3. Preprocess the frame: Convert the image to grayscale and apply smoothing.
  4. Analyze each region: Calculate image characteristics such as edge density or thresholded pixel count.
  5. Determine occupancy: Compare the calculated value with a configured threshold.
  6. Update the display: Mark occupied and vacant spaces with different colours.
  7. Calculate availability: Count the spaces classified as vacant.
Example output
  • Total parking spaces: 20
  • Occupied spaces: 13
  • Available spaces: 7

These numbers are illustrative. Actual results depend on the input image or video and the configured parking-space regions.

4. Technologies Required

Python

Python is used to implement the application logic, process image data, and connect the computer-vision components.

OpenCV

OpenCV provides functions for reading video frames, resizing images, converting colour spaces, applying thresholds, detecting edges, and drawing parking-space indicators.

NumPy

NumPy supports numerical operations on image arrays and helps calculate pixel statistics for each parking-space region.

Pickle

Pickle can store and reload parking-space coordinates so that users do not need to mark the same spaces every time the application starts.

Streamlit (optional)

Streamlit can be used to build a browser-based dashboard that displays parking availability and processed images.

5. Project Folder Structure

Create a project directory with the following structure:

smart-parking-system/
│
├── main.py
├── parking_space_selector.py
├── parking_spaces.pkl
│
├── images/
│   └── parking_lot.jpg
│
├── videos/
│   └── parking_video.mp4
│
├── output/
│
└── requirements.txt

The image and video files shown above are sample input files that you must provide. Use a fixed camera view with clearly visible parking-space boundaries for the first experiment.

6. Install Python Libraries

Create and activate a virtual environment:

python -m venv venv

On Windows:

venv\Scripts\activate

On macOS or Linux:

source venv/bin/activate

Install the required libraries:

pip install opencv-python numpy

Pickle is included in Python’s standard library, so it does not require a separate installation.

7. Define Parking Spaces

The first important task is identifying the location of every parking space in the camera image. For a beginner-friendly implementation, use rectangular regions.

Create parking_space_selector.py:

import cv2
import pickle

IMAGE_PATH = "images/parking_lot.jpg"
SAVE_PATH = "parking_spaces.pkl"

image = cv2.imread(IMAGE_PATH)

if image is None:
    raise FileNotFoundError(
        f"Could not load image: {IMAGE_PATH}"
    )

spaces = []
drawing = False
start_x, start_y = 0, 0

def mouse_callback(event, x, y, flags, param):
    global drawing, start_x, start_y, image

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        start_x, start_y = x, y

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False

        x1 = min(start_x, x)
        y1 = min(start_y, y)
        x2 = max(start_x, x)
        y2 = max(start_y, y)

        if x2 > x1 and y2 > y1:
            spaces.append((x1, y1, x2, y2))

        display = image.copy()

        for sx1, sy1, sx2, sy2 in spaces:
            cv2.rectangle(
                display,
                (sx1, sy1),
                (sx2, sy2),
                (255, 0, 0),
                2
            )

        cv2.imshow("Select Parking Spaces", display)


cv2.namedWindow("Select Parking Spaces")
cv2.setMouseCallback(
    "Select Parking Spaces",
    mouse_callback
)

while True:
    display = image.copy()

    for x1, y1, x2, y2 in spaces:
        cv2.rectangle(
            display,
            (x1, y1),
            (x2, y2),
            (255, 0, 0),
            2
        )

    cv2.imshow("Select Parking Spaces", display)

    key = cv2.waitKey(20) & 0xFF

    if key == ord("s"):
        with open(SAVE_PATH, "wb") as file:
            pickle.dump(spaces, file)

        print("Parking spaces saved.")
        break

    if key == ord("r"):
        spaces.clear()
        print("All selections cleared.")

    if key == 27:
        break

cv2.destroyAllWindows()

Run the selector:

python parking_space_selector.py

Click and drag over each parking space to draw a rectangle. Press S to save the selected coordinates. Press R to clear all selections or Esc to exit.

Camera setup matters: Select the spaces using the same camera resolution and viewpoint that you will use during detection. If the camera moves or the image is resized differently, the saved coordinates may no longer align with the parking spaces.

8. Build the Parking Occupancy Detection Module

Now create main.py. This implementation uses grayscale conversion, Gaussian smoothing, adaptive thresholding, and edge detection to estimate how much visual detail is present in each marked region.

It is a simple baseline for a fixed camera. It does not use a trained vehicle detector, and its threshold must be calibrated using representative images from your own parking area.

import cv2
import numpy as np
import pickle
import os

VIDEO_PATH = "videos/parking_video.mp4"
SPACE_FILE = "parking_spaces.pkl"

if not os.path.exists(SPACE_FILE):
    raise FileNotFoundError(
        "Run parking_space_selector.py first."
    )

with open(SPACE_FILE, "rb") as file:
    parking_spaces = pickle.load(file)

if not parking_spaces:
    raise ValueError("No parking spaces were selected.")

cap = cv2.VideoCapture(VIDEO_PATH)

if not cap.isOpened():
    raise FileNotFoundError(
        f"Could not open video: {VIDEO_PATH}"
    )

# Tune this threshold using sample frames.
OCCUPANCY_THRESHOLD = 120

def inspect_space(frame, coordinates):
    x1, y1, x2, y2 = coordinates

    height, width = frame.shape[:2]

    if not (
        0 <= x1 < x2 <= width
        and 0 <= y1 < y2 <= height
    ):
        return None

    roi = frame[y1:y2, x1:x2]

    if roi.size == 0:
        return None

    gray = cv2.cvtColor(
        roi,
        cv2.COLOR_BGR2GRAY
    )

    blurred = cv2.GaussianBlur(
        gray,
        (5, 5),
        0
    )

    threshold = cv2.adaptiveThreshold(
        blurred,
        255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
        cv2.THRESH_BINARY_INV,
        25,
        16
    )

    edges = cv2.Canny(
        blurred,
        50,
        150
    )

    threshold_pixels = cv2.countNonZero(threshold)
    edge_pixels = cv2.countNonZero(edges)

    # Combined visual activity score.
    score = threshold_pixels + edge_pixels

    return score


while True:
    success, frame = cap.read()

    if not success:
        # Restart the video for a continuous demo.
        cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
        continue

    occupied_count = 0
    available_count = 0

    for coordinates in parking_spaces:
        x1, y1, x2, y2 = coordinates

        score = inspect_space(
            frame,
            coordinates
        )

        if score is None:
            continue

        occupied = score > OCCUPANCY_THRESHOLD

        if occupied:
            occupied_count += 1
            color = (0, 0, 255)
            label = "Occupied"
        else:
            available_count += 1
            color = (0, 200, 0)
            label = "Available"

        cv2.rectangle(
            frame,
            (x1, y1),
            (x2, y2),
            color,
            2
        )

        cv2.putText(
            frame,
            label,
            (x1, max(y1 - 8, 20)),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.5,
            color,
            2
        )

    cv2.putText(
        frame,
        f"Occupied: {occupied_count}",
        (20, 35),
        cv2.FONT_HERSHEY_SIMPLEX,
        0.8,
        (0, 0, 255),
        2
    )

    cv2.putText(
        frame,
        f"Available: {available_count}",
        (20, 70),
        cv2.FONT_HERSHEY_SIMPLEX,
        0.8,
        (0, 200, 0),
        2
    )

    cv2.imshow(
        "Smart Parking Management System",
        frame
    )

    key = cv2.waitKey(30) & 0xFF

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

cap.release()
cv2.destroyAllWindows()

Run the application:

python main.py

Press Q to close the video window.

9. Understand the Occupancy Detection Logic

The example uses a combined image-processing score to estimate whether a parking space contains a vehicle. The main operations are:

  • Grayscale conversion: Converts the region into a single intensity channel.
  • Gaussian blur: Reduces some image noise before thresholding and edge detection.
  • Adaptive thresholding: Separates brighter and darker image regions using a locally calculated threshold.
  • Canny edge detection: Identifies edges and visual boundaries within the parking-space region.
  • Pixel counting: Counts the detected threshold and edge pixels to create a simple score.

The application compares this score with a configured threshold. If the score exceeds the threshold, the region is classified as occupied. Otherwise, it is classified as available.

Important limitation: This score is a heuristic, not a trained occupancy classifier. Shadows, sunlight, pavement markings, reflections, rain, and camera movement can change the score. A fixed threshold may fail when lighting conditions change. Calibrate it with labelled empty and occupied examples, and evaluate it on separate test frames.

10. Improve Detection with a Vehicle Detection Model

For a more advanced version, replace or supplement the pixel-based method with an object detection model such as YOLO. A detector can identify vehicle bounding boxes, which can then be mapped to the predefined parking spaces.

The improved workflow is:

  1. Read a frame from the camera.
  2. Run a vehicle detector on the frame.
  3. Collect the bounding boxes for relevant vehicle classes.
  4. Compare each vehicle box with the predefined parking-space regions.
  5. Mark a parking space occupied when a vehicle overlaps it sufficiently.
  6. Use tracking or multiple consecutive frames to reduce unstable status changes.

For example, the following overlap function can estimate how much of a parking-space rectangle is covered by a vehicle detection box:

def overlap_ratio(vehicle_box, parking_box):
    vx1, vy1, vx2, vy2 = vehicle_box
    px1, py1, px2, py2 = parking_box

    ix1 = max(vx1, px1)
    iy1 = max(vy1, py1)
    ix2 = min(vx2, px2)
    iy2 = min(vy2, py2)

    if ix2 <= ix1 or iy2 <= iy1:
        return 0.0

    intersection = (
        (ix2 - ix1) * (iy2 - iy1)
    )

    parking_area = (
        (px2 - px1) * (py2 - py1)
    )

    return intersection / parking_area


def is_space_occupied(
    vehicle_boxes,
    parking_box,
    minimum_overlap=0.20
):
    for vehicle_box in vehicle_boxes:
        ratio = overlap_ratio(
            vehicle_box,
            parking_box
        )

        if ratio >= minimum_overlap:
            return True

    return False

This function assumes that both boxes use the same image coordinate system. The overlap threshold is an example starting value and must be tuned for the camera angle and parking-space geometry.

For an actual YOLO implementation, you must load a suitable trained model, select vehicle classes, configure a confidence threshold, and verify that the model performs well on your camera’s viewpoint. A general street-scene detector may struggle with top-down or distant vehicles.

11. Dataset Collection and Research

To evaluate the system properly, use images that show different parking conditions rather than relying on a single demonstration video.

Useful research datasets include:

  • PKLot: A parking-lot dataset used in research on occupied and vacant parking-space classification.
  • CNRPark-EXT: A dataset containing parking-space images captured across different camera views and environmental conditions.
  • MetaPKLot: A newer harmonized benchmark that extends existing parking datasets and supports occupancy recognition, dwell-time estimation, and parking-space extraction.

Before using any dataset, review its licence, download instructions, annotation format, and permitted uses. The basic code in this article expects manually selected parking-space coordinates and a video or image sequence; public datasets may require an adapter to their annotation format.

12. Evaluate the System

Do not evaluate the project only by showing a video in which the coloured rectangles appear to work. Prepare labelled examples of occupied and vacant parking spaces and compare the predictions with the correct labels.

Useful evaluation measures include:

  • Accuracy: Percentage of parking-space predictions that are correct.
  • Precision: Of the spaces predicted as occupied, how many are actually occupied?
  • Recall: Of all occupied spaces, how many did the system identify?
  • F1-score: A combined measure of precision and recall.
  • Processing speed: Frames processed per second on the test hardware.

Test the application under different conditions, including:

  • Bright sunlight and cloudy weather.
  • Morning, afternoon, and evening lighting.
  • Partially visible vehicles.
  • Shadows covering empty spaces.
  • Different vehicle sizes and colours.
  • Camera vibration or changes in viewpoint.

Use separate training or calibration examples and test examples. If the same video frames are used to tune and report the final performance, the evaluation may be overly optimistic.

13. Advantages of the Project

  • Demonstrates practical computer-vision concepts using Python.
  • Can process recorded video and, with suitable camera access, live feeds.
  • Displays occupied and vacant spaces visually.
  • Can be developed initially without training a deep-learning model.
  • Provides a foundation for adding vehicle detection and tracking.
  • Can be extended into a parking dashboard or management application.

14. Limitations of the Basic System

The basic image-processing approach has several limitations:

  • It depends on a fixed camera position and predefined parking-space coordinates.
  • Lighting changes can affect the threshold

Want a project like this built for you?

Leave a reply

Your email address will not be published.