OpenCV  5.0.0alpha-pre
Open Source Computer Vision
Loading...
Searching...
No Matches
samples/python/snippets/distrans.py

An example on using the distance transform in python

1#!/usr/bin/env python
2
3'''
4Distance transform sample.
5
6Usage:
7 distrans.py [<image>]
8
9Keys:
10 ESC - exit
11 v - toggle voronoi mode
12'''
13
14# Python 2/3 compatibility
15from __future__ import print_function
16
17import numpy as np
18import cv2 as cv
19
20from common import make_cmap
21
22def main():
23 import sys
24 try:
25 fn = sys.argv[1]
26 except:
27 fn = 'fruits.jpg'
28
29 fn = cv.samples.findFile(fn)
30 img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
31 if img is None:
32 print('Failed to load fn:', fn)
33 sys.exit(1)
34
35 cm = make_cmap('jet')
36 need_update = True
37 voronoi = False
38
39 def update(dummy=None):
40 global need_update
41 need_update = False
42 thrs = cv.getTrackbarPos('threshold', 'distrans')
43 mark = cv.Canny(img, thrs, 3*thrs)
44 dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)
45 if voronoi:
46 vis = cm[np.uint8(labels)]
47 else:
48 vis = cm[np.uint8(dist*2)]
49 vis[mark != 0] = 255
50 cv.imshow('distrans', vis)
51
52 def invalidate(dummy=None):
53 global need_update
54 need_update = True
55
56 cv.namedWindow('distrans')
57 cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
58 update()
59
60
61 while True:
62 ch = cv.waitKey(50)
63 if ch == 27:
64 break
65 if ch == ord('v'):
66 voronoi = not voronoi
67 print('showing', ['distance', 'voronoi'][voronoi])
68 update()
69 if need_update:
70 update()
71
72 print('Done')
73
74
75if __name__ == '__main__':
76 print(__doc__)
77 main()
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
int getTrackbarPos(const String &trackbarname, const String &winname)
Returns the trackbar position.
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
void destroyAllWindows()
Destroys all of the HighGUI windows.
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
Creates a trackbar and attaches it to the specified window.
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false)
Finds edges in an image using the Canny algorithm .
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3