coherence.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python
  2. '''
  3. Coherence-enhancing filtering example
  4. =====================================
  5. inspired by
  6. Joachim Weickert "Coherence-Enhancing Shock Filters"
  7. http://www.mia.uni-saarland.de/Publications/weickert-dagm03.pdf
  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. def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
  18. h, w = img.shape[:2]
  19. for i in xrange(iter_n):
  20. print(i)
  21. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  22. eigen = cv.cornerEigenValsAndVecs(gray, str_sigma, 3)
  23. eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
  24. x, y = eigen[:,:,1,0], eigen[:,:,1,1]
  25. gxx = cv.Sobel(gray, cv.CV_32F, 2, 0, ksize=sigma)
  26. gxy = cv.Sobel(gray, cv.CV_32F, 1, 1, ksize=sigma)
  27. gyy = cv.Sobel(gray, cv.CV_32F, 0, 2, ksize=sigma)
  28. gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy
  29. m = gvv < 0
  30. ero = cv.erode(img, None)
  31. dil = cv.dilate(img, None)
  32. img1 = ero
  33. img1[m] = dil[m]
  34. img = np.uint8(img*(1.0 - blend) + img1*blend)
  35. print('done')
  36. return img
  37. def main():
  38. import sys
  39. try:
  40. fn = sys.argv[1]
  41. except:
  42. fn = 'baboon.jpg'
  43. src = cv.imread(cv.samples.findFile(fn))
  44. def nothing(*argv):
  45. pass
  46. def update():
  47. sigma = cv.getTrackbarPos('sigma', 'control')*2+1
  48. str_sigma = cv.getTrackbarPos('str_sigma', 'control')*2+1
  49. blend = cv.getTrackbarPos('blend', 'control') / 10.0
  50. print('sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend))
  51. dst = coherence_filter(src, sigma=sigma, str_sigma = str_sigma, blend = blend)
  52. cv.imshow('dst', dst)
  53. cv.namedWindow('control', 0)
  54. cv.createTrackbar('sigma', 'control', 9, 15, nothing)
  55. cv.createTrackbar('blend', 'control', 7, 10, nothing)
  56. cv.createTrackbar('str_sigma', 'control', 9, 15, nothing)
  57. print('Press SPACE to update the image\n')
  58. cv.imshow('src', src)
  59. update()
  60. while True:
  61. ch = cv.waitKey()
  62. if ch == ord(' '):
  63. update()
  64. if ch == 27:
  65. break
  66. print('Done')
  67. if __name__ == '__main__':
  68. print(__doc__)
  69. main()
  70. cv.destroyAllWindows()