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