Skip to content

Uncategorized

Estimate the speed of any object | with Python and OpenCV

Access community, courses and source codes
Logo

AI Vision Academy

Access the code of this tutorial, computer vision courses and an exclusive community on AI Vision Academy

  • Access to over 50+ source codes from Pysource.com/blog
  • Dedicated video courses about computer vision
  • Access to an exclusive community of professionals
  • Real-World AI Projects – Get hands-on experience building practical AI Computer Vision solutions with a structured path.
  • Monthly Coaching Calls – get support and any of your questions answered

Subscribe to our newsletter to learn more

Speed detection isn’t just for radar guns anymore. With the power of computer vision, Python, and OpenCV, you can now estimate the speed of any moving object using just a video feed and some basic calibration. In this guide, we’ll show you how to accurately calculate vehicle speed in real time, with less than a 5% margin of error, using tools like YOLO object detection, multi-object tracking, and some smart mathematical techniques.

Requirements for Real-Time Speed Detection

You’ll need just a few things to get started:

  • A camera or recorded video: Your primary data source.
  • Two reference points with known distance: Helps translate pixels to real-world meters.
  • Basic Python knowledge: Enough to run or tweak the code.

This simple setup is sufficient to build a robust speed detection system that rivals expensive radar tools.

Step 1: Detecting and Tracking Vehicles

Object Detection with YOLO

We use YOLO-based deep learning to detect vehicles in every frame. Each vehicle is enclosed in a bounding box.

Tracking with Unique IDs

Since videos are just sequences of frames, we need to track the same object across multiple frames. This is handled using a multi-object tracker (like OCSort), assigning unique IDs to each vehicle for continuous tracking.

bboxes, labels, scores = od.detect(frame)
bboxes_ids = tracker.update(bboxes, scores, labels, frame)

Bounding boxes and center points help us locate and track vehicles in motion.

Step 2: Calibrating Real-World Distance

Converting Pixels to Meters

To estimate speed, we must first determine how far an object travels in meters, not pixels.

We set two reference points in the video and measure the real-world distance between them (e.g., 80 meters). A function converts the distance between those two points in pixels to meters-per-pixel.

meter_per_pixel = calculate_meters_per_pixel(p1=roi[0], p2=roi[2], real_distance_m=80)

This gives us the foundation to translate motion in the video into actual physical movement.

Step 3: Estimating Object Speed

Calculating Speed Using FPS

Knowing the frames per second (FPS) of the video, we can calculate how far an object moves over time and determine its speed.

fps = cap.get(cv2.CAP_PROP_FPS)
os = ObjectSpeed(fps=fps, meters_per_pixel=meter_per_pixel, warp_matrix=warp_matrix)

When a vehicle’s center point enters the region of interest (ROI), the script starts measuring its displacement frame by frame.

if cv2.pointPolygonTest(roi, (cx, cy), False) >= 0:
    speed = os.update(object_id, cx, cy)

Speed is calculated and shown on the frame in real-time:

draw_centered_text(frame, f"{speed:.2f} km/h", x1, y1, x2)

Step 4: Correcting Perspective for Accuracy

The Problem with Camera Angles

A slanted or diagonal camera angle introduces distortion. Objects near the bottom of the screen appear larger than those far away, throwing off speed calculations.

Solution: Warp Perspective

By applying a perspective transformation, we simulate a bird’s-eye (top-down) view. This removes distortion and equalizes pixel values across the frame.

warp_matrix = get_warp_matrix(roi)
warp_perspective(frame, warp_matrix)

This greatly improves speed accuracy, especially at higher vehicle speeds or when the camera is at an angle.

Original

Warped

How Accurate Is It Really?

Accuracy is influenced by:

  • FPS: Higher FPS = More frames = Better accuracy.
  • Speed of the object: Faster objects = Less time in ROI = Higher margin of error.
  • Camera angle and distortion

Here is a table that shows the margin of error based on FPS and objects speed.

These figures assume ideal detection and tracking. Real-world variables like lighting, motion blur, or detection confidence can slightly impact results.

Real-World Applications

This method isn’t just for traffic analysis:

  • Smart Traffic Monitoring
  • Sports Performance Tracking
  • Factory Conveyor Systems
  • Security Surveillance

It’s scalable, adaptable, and can be enhanced with alerts, cloud analytics, or AI integrations.

Conclusion

We’ve just walked through building a real-time speed detection system using OpenCV, YOLO, and Python. With just a video and some reference points, you can achieve a reliable, radar-like experience with less than 5% margin of error. By correcting camera perspective and increasing FPS, your system can be accurate enough for industrial or municipal use.

Whether you’re a developer, engineer, or hobbyist, this implementation provides a powerful starting point for real-world speed tracking applications.

Want to Build This Yourself?

If you’re serious about deploying high-performance computer vision systems, AI Visioni Academy is your go-to resource. You’ll get:

  • Hands-on projects in detection, tracking, classification, and more
  • Optimized models, batch configurations, and deployment guides
  • A supportive community and expert guidance

Don’t reinvent the wheel. Start building advanced, production-ready computer vision systems today.