lappyr.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. ''' An example of Laplacian Pyramid construction and merging.
  3. Level : Intermediate
  4. Usage : python lappyr.py [<video source>]
  5. References:
  6. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.54.299
  7. Alexander Mordvintsev 6/10/12
  8. '''
  9. # Python 2/3 compatibility
  10. from __future__ import print_function
  11. import sys
  12. PY3 = sys.version_info[0] == 3
  13. if PY3:
  14. xrange = range
  15. import numpy as np
  16. import cv2 as cv
  17. import video
  18. from common import nothing, getsize
  19. def build_lappyr(img, leveln=6, dtype=np.int16):
  20. img = dtype(img)
  21. levels = []
  22. for _i in xrange(leveln-1):
  23. next_img = cv.pyrDown(img)
  24. img1 = cv.pyrUp(next_img, dstsize=getsize(img))
  25. levels.append(img-img1)
  26. img = next_img
  27. levels.append(img)
  28. return levels
  29. def merge_lappyr(levels):
  30. img = levels[-1]
  31. for lev_img in levels[-2::-1]:
  32. img = cv.pyrUp(img, dstsize=getsize(lev_img))
  33. img += lev_img
  34. return np.uint8(np.clip(img, 0, 255))
  35. def main():
  36. import sys
  37. try:
  38. fn = sys.argv[1]
  39. except:
  40. fn = 0
  41. cap = video.create_capture(fn)
  42. leveln = 6
  43. cv.namedWindow('level control')
  44. for i in xrange(leveln):
  45. cv.createTrackbar('%d'%i, 'level control', 5, 50, nothing)
  46. while True:
  47. _ret, frame = cap.read()
  48. pyr = build_lappyr(frame, leveln)
  49. for i in xrange(leveln):
  50. v = int(cv.getTrackbarPos('%d'%i, 'level control') / 5)
  51. pyr[i] *= v
  52. res = merge_lappyr(pyr)
  53. cv.imshow('laplacian pyramid filter', res)
  54. if cv.waitKey(1) == 27:
  55. break
  56. print('Done')
  57. if __name__ == '__main__':
  58. print(__doc__)
  59. main()
  60. cv.destroyAllWindows()