7
morphology.py [<image>]
11
2 - change structure element shape
15
# Python 2/3 compatibility
16
from __future__ import print_function
18
PY3 = sys.version_info[0] == 3
24
if __name__ == '__main__':
28
from itertools import cycle
29
from common import draw_str
34
fn = '../data/baboon.jpg'
39
print('Failed to load image file:', fn)
42
cv2.imshow('original', img)
44
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
45
str_modes = cycle(['ellipse', 'rect', 'cross'])
48
cur_mode = next(modes)
49
cur_str_mode = next(str_modes)
51
cur_mode = modes.next()
52
cur_str_mode = str_modes.next()
54
def update(dummy=None):
55
sz = cv2.getTrackbarPos('op/size', 'morphology')
56
iters = cv2.getTrackbarPos('iters', 'morphology')
57
opers = cur_mode.split('/')
66
str_name = 'MORPH_' + cur_str_mode.upper()
67
oper_name = 'MORPH_' + op.upper()
68
st = cv2.getStructuringElement(getattr(cv2, str_name), (sz, sz))
69
res = cv2.morphologyEx(img, getattr(cv2, oper_name), st, iterations=iters)
71
draw_str(res, (10, 20), 'mode: ' + cur_mode)
72
draw_str(res, (10, 40), 'operation: ' + oper_name)
73
draw_str(res, (10, 60), 'structure: ' + str_name)
74
draw_str(res, (10, 80), 'ksize: %d iters: %d' % (sz, iters))
75
cv2.imshow('morphology', res)
77
cv2.namedWindow('morphology')
78
cv2.createTrackbar('op/size', 'morphology', 12, 20, update)
79
cv2.createTrackbar('iters', 'morphology', 1, 10, update)
82
ch = 0xFF & cv2.waitKey()
87
cur_mode = next(modes)
89
cur_mode = modes.next()
92
cur_str_mode = next(str_modes)
94
cur_str_mode = str_modes.next()
96
cv2.destroyAllWindows()