Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/morphology.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
Morphology operations.
5
6
Usage:
7
morphology.py [<image>]
8
9
Keys:
10
1 - change operation
11
2 - change structure element shape
12
ESC - exit
13
'''
14
15
# Python 2/3 compatibility
16
from __future__ import print_function
17
import sys
18
PY3 = sys.version_info[0] == 3
19
20
import numpy as np
21
import cv2 as cv
22
23
24
if __name__ == '__main__':
25
print(__doc__)
26
27
import sys
28
from itertools import cycle
29
from common import draw_str
30
31
try:
32
fn = sys.argv[1]
33
except:
34
fn = '../data/baboon.jpg'
35
36
img = cv.imread(fn)
37
38
if img is None:
39
print('Failed to load image file:', fn)
40
sys.exit(1)
41
42
cv.imshow('original', img)
43
44
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
45
str_modes = cycle(['ellipse', 'rect', 'cross'])
46
47
if PY3:
48
cur_mode = next(modes)
49
cur_str_mode = next(str_modes)
50
else:
51
cur_mode = modes.next()
52
cur_str_mode = str_modes.next()
53
54
def update(dummy=None):
55
sz = cv.getTrackbarPos('op/size', 'morphology')
56
iters = cv.getTrackbarPos('iters', 'morphology')
57
opers = cur_mode.split('/')
58
if len(opers) > 1:
59
sz = sz - 10
60
op = opers[sz > 0]
61
sz = abs(sz)
62
else:
63
op = opers[0]
64
sz = sz*2+1
65
66
str_name = 'MORPH_' + cur_str_mode.upper()
67
oper_name = 'MORPH_' + op.upper()
68
st = cv.getStructuringElement(getattr(cv, str_name), (sz, sz))
69
res = cv.morphologyEx(img, getattr(cv, oper_name), st, iterations=iters)
70
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
cv.imshow('morphology', res)
76
77
cv.namedWindow('morphology')
78
cv.createTrackbar('op/size', 'morphology', 12, 20, update)
79
cv.createTrackbar('iters', 'morphology', 1, 10, update)
80
update()
81
while True:
82
ch = cv.waitKey()
83
if ch == 27:
84
break
85
if ch == ord('1'):
86
if PY3:
87
cur_mode = next(modes)
88
else:
89
cur_mode = modes.next()
90
if ch == ord('2'):
91
if PY3:
92
cur_str_mode = next(str_modes)
93
else:
94
cur_str_mode = str_modes.next()
95
update()
96
cv.destroyAllWindows()
97
98