Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/coherence.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
Coherence-enhancing filtering example
5
=====================================
6
7
inspired by
8
Joachim Weickert "Coherence-Enhancing Shock Filters"
9
http://www.mia.uni-saarland.de/Publications/weickert-dagm03.pdf
10
'''
11
12
# Python 2/3 compatibility
13
from __future__ import print_function
14
import sys
15
PY3 = sys.version_info[0] == 3
16
17
if PY3:
18
xrange = range
19
20
import numpy as np
21
import cv2 as cv
22
23
def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
24
h, w = img.shape[:2]
25
26
for i in xrange(iter_n):
27
print(i)
28
29
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
30
eigen = cv.cornerEigenValsAndVecs(gray, str_sigma, 3)
31
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
32
x, y = eigen[:,:,1,0], eigen[:,:,1,1]
33
34
gxx = cv.Sobel(gray, cv.CV_32F, 2, 0, ksize=sigma)
35
gxy = cv.Sobel(gray, cv.CV_32F, 1, 1, ksize=sigma)
36
gyy = cv.Sobel(gray, cv.CV_32F, 0, 2, ksize=sigma)
37
gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy
38
m = gvv < 0
39
40
ero = cv.erode(img, None)
41
dil = cv.dilate(img, None)
42
img1 = ero
43
img1[m] = dil[m]
44
img = np.uint8(img*(1.0 - blend) + img1*blend)
45
print('done')
46
return img
47
48
49
if __name__ == '__main__':
50
import sys
51
try:
52
fn = sys.argv[1]
53
except:
54
fn = '../data/baboon.jpg'
55
56
src = cv.imread(fn)
57
58
def nothing(*argv):
59
pass
60
61
def update():
62
sigma = cv.getTrackbarPos('sigma', 'control')*2+1
63
str_sigma = cv.getTrackbarPos('str_sigma', 'control')*2+1
64
blend = cv.getTrackbarPos('blend', 'control') / 10.0
65
print('sigma: %d str_sigma: %d blend_coef: %f' % (sigma, str_sigma, blend))
66
dst = coherence_filter(src, sigma=sigma, str_sigma = str_sigma, blend = blend)
67
cv.imshow('dst', dst)
68
69
cv.namedWindow('control', 0)
70
cv.createTrackbar('sigma', 'control', 9, 15, nothing)
71
cv.createTrackbar('blend', 'control', 7, 10, nothing)
72
cv.createTrackbar('str_sigma', 'control', 9, 15, nothing)
73
74
75
print('Press SPACE to update the image\n')
76
77
cv.imshow('src', src)
78
update()
79
while True:
80
ch = cv.waitKey()
81
if ch == ord(' '):
82
update()
83
if ch == 27:
84
break
85
cv.destroyAllWindows()
86
87