1#!/usr/bin/env python 2 3''' 4Morphology operations. 5 6Usage: 7 morphology.py [<image>] 8 9Keys: 10 1 - change operation 11 2 - change structure element shape 12 ESC - exit 13''' 14 15import numpy as np 16import cv2 17 18 19if __name__ == '__main__': 20 print __doc__ 21 22 import sys 23 from itertools import cycle 24 from common import draw_str 25 26 try: 27 fn = sys.argv[1] 28 except: 29 fn = '../data/baboon.jpg' 30 31 img = cv2.imread(fn) 32 33 if img is None: 34 print 'Failed to load image file:', fn 35 sys.exit(1) 36 37 cv2.imshow('original', img) 38 39 modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient']) 40 str_modes = cycle(['ellipse', 'rect', 'cross']) 41 cur_mode = modes.next() 42 cur_str_mode = str_modes.next() 43 44 def update(dummy=None): 45 sz = cv2.getTrackbarPos('op/size', 'morphology') 46 iters = cv2.getTrackbarPos('iters', 'morphology') 47 opers = cur_mode.split('/') 48 if len(opers) > 1: 49 sz = sz - 10 50 op = opers[sz > 0] 51 sz = abs(sz) 52 else: 53 op = opers[0] 54 sz = sz*2+1 55 56 str_name = 'MORPH_' + cur_str_mode.upper() 57 oper_name = 'MORPH_' + op.upper() 58 st = cv2.getStructuringElement(getattr(cv2, str_name), (sz, sz)) 59 res = cv2.morphologyEx(img, getattr(cv2, oper_name), st, iterations=iters) 60 61 draw_str(res, (10, 20), 'mode: ' + cur_mode) 62 draw_str(res, (10, 40), 'operation: ' + oper_name) 63 draw_str(res, (10, 60), 'structure: ' + str_name) 64 draw_str(res, (10, 80), 'ksize: %d iters: %d' % (sz, iters)) 65 cv2.imshow('morphology', res) 66 67 cv2.namedWindow('morphology') 68 cv2.createTrackbar('op/size', 'morphology', 12, 20, update) 69 cv2.createTrackbar('iters', 'morphology', 1, 10, update) 70 update() 71 while True: 72 ch = 0xFF & cv2.waitKey() 73 if ch == 27: 74 break 75 if ch == ord('1'): 76 cur_mode = modes.next() 77 if ch == ord('2'): 78 cur_str_mode = str_modes.next() 79 update() 80 cv2.destroyAllWindows() 81