Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OpenCV minimal example showing multithreaded video processing.
# Original code here:
# https://github.com/opencv/opencv/blob/master/samples/python/video_threaded.py
#!/usr/bin/env python3
'''
Multithreaded video processing minimal sample.
Usage:
python3 video_threaded.py
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
VIDEO_SOURCE = 0
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 = cap.read()
if frame_got:
task = pool.apply_async(process_frame, (frame.copy(),))
pending_task.append(task)
# Show preview.
if cv.waitKey(1) == 27 or not frame_got:
break
cv.destroyAllWindows()
@simonloewe
Copy link

simonloewe commented Apr 29, 2021

Isn't this just a near straight up copy from the official documentation? https://github.com/opencv/opencv/blob/master/samples/python/video_threaded.py

Loading

@yinguobing
Copy link
Author

yinguobing commented May 5, 2021

It is.

Loading

@michelcameroon
Copy link

michelcameroon commented Jul 4, 2021

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.

Loading

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