| OpenCV 5.0.0alpha 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'''
4 Distance transform sample.
5
6 Usage:
7 distrans.py [<image>]
8
9 Keys:
10 ESC - exit
11 v - toggle voronoi mode
12'''
13
14# Python 2/3 compatibility
15 from __future__ import print_function
16
17 import numpy as np
18 import cv2 as cv
19
20 from common import make_cmap
21
22 def 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
75 if __name__ == '__main__':
76 print(__doc__)
77 main()
78 cv.destroyAllWindows()
cv::samples::findFile
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
cv::getTrackbarPos
int getTrackbarPos(const String &trackbarname, const String &winname)
Returns the trackbar position.
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
cv::namedWindow
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
cv::destroyAllWindows
void destroyAllWindows()
Destroys all of the HighGUI windows.
cv::createTrackbar
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::imread
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
cv::Canny
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 canny86 .
main
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3