floodfill.py sample added
authorAlexander Mordvintsev <no@email>
Sat, 2 Jul 2011 16:03:17 +0000 (16:03 +0000)
committerAlexander Mordvintsev <no@email>
Sat, 2 Jul 2011 16:03:17 +0000 (16:03 +0000)
samples/python2/floodfill.py [new file with mode: 0644]

diff --git a/samples/python2/floodfill.py b/samples/python2/floodfill.py
new file mode 100644 (file)
index 0000000..c9d3128
--- /dev/null
@@ -0,0 +1,64 @@
+import numpy as np\r
+import cv2, cv\r
+\r
+help_message = '''USAGE: floodfill.py [<image>]\r
+\r
+Click on the image to set seed point\r
+\r
+Keys:\r
+  f     - toggle floating range\r
+  c     - toggle 4/8 connectivity\r
+  ESC   - exit\r
+'''\r
+\r
+if __name__ == '__main__':\r
+    import sys\r
+    try: fn = sys.argv[1]\r
+    except: fn = '../cpp/fruits.jpg'\r
+    print help_message\r
+\r
+    img = cv2.imread(fn, True)\r
+    h, w = img.shape[:2]\r
+    mask = np.zeros((h+2, w+2), np.uint8)\r
+    seed_pt = None\r
+    fixed_range = True\r
+    connectivity = 4\r
+\r
+    def update(dummy=None):\r
+        if seed_pt is None:\r
+            cv2.imshow('floodfill', img)\r
+            return\r
+        flooded = img.copy()\r
+        mask[:] = 0\r
+        lo = cv2.getTrackbarPos('lo', 'floodfill')\r
+        hi = cv2.getTrackbarPos('hi', 'floodfill')\r
+        flags = connectivity\r
+        if fixed_range:\r
+            flags |= cv2.FLOODFILL_FIXED_RANGE\r
+        cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)\r
+        cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)\r
+        cv2.imshow('floodfill', flooded)\r
+\r
+    def onmouse(event, x, y, flags, param):\r
+        global seed_pt\r
+        if flags & cv.CV_EVENT_FLAG_LBUTTON:\r
+            seed_pt = x, y\r
+            update()\r
+\r
+    update()\r
+    cv2.setMouseCallback('floodfill', onmouse)\r
+    cv2.createTrackbar('lo', 'floodfill', 20, 255, update)\r
+    cv2.createTrackbar('hi', 'floodfill', 20, 255, update)\r
+\r
+    while True:\r
+        ch = cv2.waitKey()\r
+        if ch == 27:\r
+            break\r
+        if ch == ord('f'):\r
+            fixed_range = not fixed_range\r
+            print 'using %s range' % ('floating', 'fixed')[fixed_range]\r
+            update()\r
+        if ch == ord('c'):\r
+            connectivity = 12-connectivity\r
+            print 'connectivity =', connectivity\r
+            update()\r