opencv/samples/python/morphology.py

90 lines
2.2 KiB
Python
Raw Normal View History

2013-03-06 14:41:02 +08:00
#!/usr/bin/env python
2012-10-17 07:18:30 +08:00
'''
Morphology operations.
Usage:
morphology.py [<image>]
Keys:
1 - change operation
2 - change structure element shape
ESC - exit
'''
import numpy as np
import cv2 as cv
2012-10-17 07:18:30 +08:00
def main():
2012-10-17 07:18:30 +08:00
import sys
from itertools import cycle
from common import draw_str
2013-03-06 14:41:02 +08:00
try:
fn = sys.argv[1]
except:
2018-11-14 23:56:21 +08:00
fn = 'baboon.jpg'
2018-11-14 23:56:21 +08:00
img = cv.imread(cv.samples.findFile(fn))
2013-03-06 14:41:02 +08:00
if img is None:
print('Failed to load image file:', fn)
2013-03-06 14:41:02 +08:00
sys.exit(1)
cv.imshow('original', img)
2012-10-17 07:18:30 +08:00
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
str_modes = cycle(['ellipse', 'rect', 'cross'])
2023-07-13 21:07:10 +08:00
cur_mode = next(modes)
cur_str_mode = next(str_modes)
2012-10-17 07:18:30 +08:00
def update(dummy=None):
2021-06-30 03:15:37 +08:00
try: # do not get trackbar position while trackbar is not created
sz = cv.getTrackbarPos('op/size', 'morphology')
iters = cv.getTrackbarPos('iters', 'morphology')
except:
return
2012-10-17 07:18:30 +08:00
opers = cur_mode.split('/')
if len(opers) > 1:
sz = sz - 10
op = opers[sz > 0]
sz = abs(sz)
else:
op = opers[0]
sz = sz*2+1
str_name = 'MORPH_' + cur_str_mode.upper()
oper_name = 'MORPH_' + op.upper()
st = cv.getStructuringElement(getattr(cv, str_name), (sz, sz))
res = cv.morphologyEx(img, getattr(cv, oper_name), st, iterations=iters)
2012-10-17 07:18:30 +08:00
draw_str(res, (10, 20), 'mode: ' + cur_mode)
draw_str(res, (10, 40), 'operation: ' + oper_name)
draw_str(res, (10, 60), 'structure: ' + str_name)
draw_str(res, (10, 80), 'ksize: %d iters: %d' % (sz, iters))
cv.imshow('morphology', res)
2012-10-17 07:18:30 +08:00
cv.namedWindow('morphology')
cv.createTrackbar('op/size', 'morphology', 12, 20, update)
cv.createTrackbar('iters', 'morphology', 1, 10, update)
2012-10-17 07:18:30 +08:00
update()
while True:
ch = cv.waitKey()
2012-10-17 07:18:30 +08:00
if ch == 27:
break
if ch == ord('1'):
2023-07-13 21:07:10 +08:00
cur_mode = next(modes)
2012-10-17 07:18:30 +08:00
if ch == ord('2'):
2023-07-13 21:07:10 +08:00
cur_str_mode = next(str_modes)
2012-10-17 07:18:30 +08:00
update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()