morphology.py 2.6 KB

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