gabor_threads.py 1.9 KB

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