1 #!/usr/bin/env python 2 3 ''' 4 gabor_threads.py 5 ========= 6 7 Sample demonstrates: 8 - use of multiple Gabor filter convolutions to get Fractalius-like image effect (http://www.redfieldplugins.com/filterFractalius.htm) 9 - use of python threading to accelerate the computation 10 11 Usage 12 ----- 13 gabor_threads.py [image filename] 14 15 ''' 16 17 import numpy as np 18 import cv2 19 from multiprocessing.pool import ThreadPool 20 21 22 def build_filters(): 23 filters = [] 24 ksize = 31 25 for theta in np.arange(0, np.pi, np.pi / 16): 26 kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F) 27 kern /= 1.5*kern.sum() 28 filters.append(kern) 29 return filters 30 31 def process(img, filters): 32 accum = np.zeros_like(img) 33 for kern in filters: 34 fimg = cv2.filter2D(img, cv2.CV_8UC3, kern) 35 np.maximum(accum, fimg, accum) 36 return accum 37 38 def process_threaded(img, filters, threadn = 8): 39 accum = np.zeros_like(img) 40 def f(kern): 41 return cv2.filter2D(img, cv2.CV_8UC3, kern) 42 pool = ThreadPool(processes=threadn) 43 for fimg in pool.imap_unordered(f, filters): 44 np.maximum(accum, fimg, accum) 45 return accum 46 47 if __name__ == '__main__': 48 import sys 49 from common import Timer 50 51 print __doc__ 52 try: 53 img_fn = sys.argv[1] 54 except: 55 img_fn = '../data/baboon.jpg' 56 57 img = cv2.imread(img_fn) 58 if img is None: 59 print 'Failed to load image file:', img_fn 60 sys.exit(1) 61 62 filters = build_filters() 63 64 with Timer('running single-threaded'): 65 res1 = process(img, filters) 66 with Timer('running multi-threaded'): 67 res2 = process_threaded(img, filters) 68 69 print 'res1 == res2: ', (res1 == res2).all() 70 cv2.imshow('img', img) 71 cv2.imshow('result', res2) 72 cv2.waitKey() 73 cv2.destroyAllWindows() 74