Skip to content

Instantly share code, notes, and snippets.

Last active May 8, 2022 01:38
What would you like to do?
OpenCV minimal example showing multithreaded video processing.
# Original code here:
#!/usr/bin/env python3
Multithreaded video processing minimal sample.
Shows how python threading capabilities can be used
to organize parallel captured frame processing pipeline
for smoother playback.
Keyboard shortcuts:
ESC - exit
from collections import deque
from multiprocessing.pool import ThreadPool
import cv2 as cv
def process_frame(frame):
# some intensive computation...
frame = cv.medianBlur(frame, 19)
return frame
if __name__ == '__main__':
# Setup.
cap = cv.VideoCapture(VIDEO_SOURCE)
thread_num = cv.getNumberOfCPUs()
pool = ThreadPool(processes=thread_num)
pending_task = deque()
while True:
# Consume the queue.
while len(pending_task) > 0 and pending_task[0].ready():
res = pending_task.popleft().get()
cv.imshow('threaded video', res)
# Populate the queue.
if len(pending_task) < thread_num:
frame_got, frame =
if frame_got:
task = pool.apply_async(process_frame, (frame.copy(),))
# Show preview.
if cv.waitKey(1) == 27 or not frame_got:
Copy link

Isn't this just a near straight up copy from the official documentation?

Copy link

It is.

Copy link

i have tested the scipt and add to disolay the FPS but i get 8, when i move my hand the fps goes up to 17. i measure it in the while loop

    while len(pending_task) > 0 and pending_task[0].ready():
        res = pending_task.popleft().get()

        # fps calulation

may be i make a mistake, fps is low.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment