samples/python/snippets/mser.py#

An example using Maximally stable extremal region(MSER) extractor in python

 1#!/usr/bin/env python
 2
 3'''
 4MSER detector demo
 5==================
 6
 7Usage:
 8------
 9    mser.py [<video source>]
10
11Keys:
12-----
13    ESC   - exit
14
15'''
16
17# Python 2/3 compatibility
18from __future__ import print_function
19
20import numpy as np
21import cv2 as cv
22
23import video
24import sys
25
26def main():
27    try:
28        video_src = sys.argv[1]
29    except:
30        video_src = 0
31
32    cam = video.create_capture(video_src)
33    mser = cv.MSER_create()
34
35    while True:
36        ret, img = cam.read()
37        if ret == 0:
38            break
39        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
40        vis = img.copy()
41
42        regions, _ = mser.detectRegions(gray)
43        hulls = [cv.convexHull(p.reshape(-1, 1, 2)) for p in regions]
44        cv.polylines(vis, hulls, 1, (0, 255, 0))
45
46        cv.imshow('img', vis)
47        if cv.waitKey(5) == 27:
48            break
49
50    print('Done')
51
52
53if __name__ == '__main__':
54    print(__doc__)
55    main()
56    cv.destroyAllWindows()