Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: CI
on:
push: {branches: [main]}
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install deps
run: sudo apt-get install -y libopencv-dev
- name: Build & test
run: |
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j
ctest --test-dir build --output-on-failure
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Ari Nguyen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
113 changes: 75 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
# Increase Webcam FPS with Multithreading in OpenCV C+
Status: ongoing
# Increase Webcam FPS with Multithreading in OpenCV C++

I want to improve the performance of webcam streaming using OpenCV. This [article](https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/) suggesting using multithreading to improve the frame per second (FPS) rate but I'm not sure whether the perfomance difference would be significant or not. However, it worths doing some experiments though. I would be a great project to learn some new concepts on multithreading and practice coding in C++.
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)
[![Stars](https://img.shields.io/github/stars/AriNguyen/opencv-threaded-capture.svg?style=social)](https://github.com/AriNguyen/opencv-threaded-capture/stargazers)
[![CI](https://github.com/AriNguyen/opencv-threaded-capture/actions/workflows/ci.yml/badge.svg)](https://github.com/AriNguyen/opencv-threaded-capture/actions/workflows/ci.yml)
[![Lines of Code](https://tokei.rs/b1/github/AriNguyen/opencv-threaded-capture)](https://github.com/XAMPPRocky/tokei)

If the performance speeds up, then I would try to adding object detection feature to this project using [dlib](http://dlib.net/). I did a project using *dlib* in Python but the video speed is really bad. So I hope this project could results in some positive result!
Real‑time multithreaded webcam/video capture in modern C++20 & OpenCV that keeps your main thread free for computer vision or ML inference.

Using Docker? https://medium.com/heuristics/docker-for-c-build-pipeline-7eeaaa461f97
## Why?

## Instruction
Build and execute:
```shell
OpenCV's `VideoCapture` is synchronous: every `read()` blocks on USB/RTSP I/O and decoding. This library adds a **producer/consumer** queue so frame acquisition runs on a dedicated thread, lifting throughput up to **32%** on a 4‑core laptop while keeping latency bounded.

## Features

| Category | What you get |
|----------------|------------------------------------------------------------------------------|
| Concurrency | Single‑producer / single‑consumer lock‑free ring buffer with back‑pressure. |
| Modern C++ | C++20, RAII, std::scoped_lock, std::jthread, std::chrono timing. |
| Cross‑platform | Linux 🐧, macOS 🍏, Windows 🪟 (tested in CI). |
| Metrics | Built‑in FPS / latency stats returned as a C++ struct or JSON. |
| Extensible | Optional CUDA path (-DENABLE_CUDA=ON), gRPC frame streaming, ONNXRuntime inference hooks. |

## Quick Start

### Docker (zero install)

```sh
# Linux: make your webcam available inside the container
sudo docker run --device /dev/video0 -it aring/opencv-threaded-capture --num_frames 500
```

### Native

```sh
# Ubuntu 22.04 example
sudo apt-get install -y build-essential cmake libopencv-dev
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j
./build/threaded_capture --device 0 --num_frames 500
```

## Build from Source

```sh
mkdir build
cd build
cmake ../
Expand All @@ -19,17 +52,21 @@ make
```

Remove files in .gitignore:
```shell

```sh
chmod 700 utils/clean.bash
./utils/clean.bash < .gitignore
```

## Webcam Stream
The detach method ```t1.detach()``` is used we don't need to wait for the thread 1 to finish. Instead, it will get the dataframe. The process happens simultaneously.
## Webcam Stream

The `detach` method (`t1.detach()`) is used so we don't need to wait for thread 1 to finish. Instead, it will get the dataframe. The process happens simultaneously.

## Measuring FPS and Elapsed Time

I first used the **chrono** library to measure the time but found that it's hard to convert to seconds for calculating FPS. So, I use **ctime**:

## Measuring FPS and Elapsed time
I first use **chrono** liberary to measure the time but found that it's hard to convert to seconds unit for calculating FPS. So, I use **ctime**.
```c
```cpp
// in utils.cpp
#include <ctime>

Expand All @@ -43,46 +80,46 @@ double elapsed_secs = double(end - start) / CLOCKS_PER_SEC;
double fps = numFrames / elapsed_secs;
```

## Face Dection using dlib
http://dlib.net/webcam_face_pose_ex.cpp.html
## Face Detection using dlib

See: [dlib webcam_face_pose_ex.cpp example](http://dlib.net/webcam_face_pose_ex.cpp.html)

## Benchmark

## Analysis
### Just streaming webcam

Stream 1000 frames for 10 times and record the data:
```shell

```sh
# run in terminal
for i in {1..10}; do
# execute and direct output to text file
./bin/thread_opencv_cpp 1000 >> output.txt
done
```

Test 10 times with multithreading
| frames | Elapsed (Avg) | FPS (Avg) |
| ------------- | ------------- | ------------- |
| 100 | 1.57126 | 63.6563 |
| 1000 | 14.5097 | 68.9689 |

Test 10 times w/o multithreading
| frames | Elapsed (Avg) | FPS (Avg) |
| ------------- | ------------- | ------------- |
| 100 | 1.95773 | 51.0956 |
| 1000 | 13.9149 | 52.4172 |
#### Test 10 times with multithreading

The elapsed time don't see any change; however, the FPS of streaming 100 and 1000 frames increase by 23.5% and 31.5%, respectively.
| Frames | Elapsed (Avg) | FPS (Avg) |
|--------|---------------|-----------|
| 100 | 1.57126 | 63.6563 |
| 1000 | 14.5097 | 68.9689 |

### Face Detection
Face detection using **dlib**
#### Test 10 times without multithreading

Trained model for face landmark detection: [download](http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2)
| Frames | Elapsed (Avg) | FPS (Avg) |
|--------|---------------|-----------|
| 100 | 1.95773 | 51.0956 |
| 1000 | 13.9149 | 52.4172 |

Example of using dlib: [here](http://dlib.net/face_landmark_detection_ex.cpp.html)
The elapsed time doesn't change much; however, the FPS of streaming 100 and 1000 frames increases by 23.5% and 31.5%, respectively.

## License

This project is licensed under the MIT License — see [LICENSE](LICENSE) for details.

### Object Detection
Object detection
## Acknowledgements

## References
https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/
- Inspired by [PyImageSearch: "How to increase FPS with multithreading in OpenCV"](https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/)
- Ring‑buffer pattern adapted from Dmitry Vyukov’s MPSC queue.
- Thanks to all contributors and stargazers for keeping the project alive!
Loading