video_threaded.py sample now uses multiprocessing module's ThreadPool

pull/2/head
Alexander Mordvintsev 13 years ago
parent a71e690b5e
commit 6116049225
  1. 70
      samples/python2/video_threaded.py

@ -1,63 +1,29 @@
import numpy as np import numpy as np
import cv2 import cv2
from Queue import Queue from multiprocessing.pool import ThreadPool
from threading import Thread
from collections import deque from collections import deque
class Worker(Thread):
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception, e: print e
self.tasks.task_done()
class ThreadPool:
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
self.tasks.put((func, args, kargs))
def wait_completion(self):
self.tasks.join()
if __name__ == '__main__': if __name__ == '__main__':
results = deque() def process_frame(frame):
# some intensive computation...
def process_frame(i, frame): frame = cv2.medianBlur(frame, 19)
global results frame = cv2.medianBlur(frame, 19)
res = cv2.medianBlur(frame, 15) frame = cv2.medianBlur(frame, 19)
results.append((i, res)) return frame
pool = ThreadPool(4) threadn = 8
cap = cv2.VideoCapture(0) cap = cv2.VideoCapture(0)
frame_count = 0 pool = ThreadPool(processes = threadn)
last_frame = None pending = deque()
last_count = -1
while True: while True:
ret, frame = cap.read() while len(pending) > 0 and pending[0].ready():
pool.add_task(process_frame, frame_count, frame.copy()) res = pending.popleft().get()
frame_count += 1 cv2.imshow('result', res)
while len(results) > 0: if len(pending) < threadn+1:
i, frame = results.popleft() ret, frame = cap.read()
if i > last_count: task = pool.apply_async(process_frame, (frame.copy(),))
last_count, last_frame = i, frame pending.append(task)
if last_frame is not None:
cv2.imshow('res', last_frame)
if cv2.waitKey(1) == 27: if cv2.waitKey(1) == 27:
break break
pool.wait_completion()

Loading…
Cancel
Save