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

An example using the Hough circle detector in python

1#!/usr/bin/python
2
3'''
4This example illustrates how to use cv.HoughCircles() function.
5
6Usage:
7 houghcircles.py [<image_name>]
8 image argument defaults to board.jpg
9'''
10
11# Python 2/3 compatibility
12from __future__ import print_function
13
14import numpy as np
15import cv2 as cv
16
17import sys
18
19def main():
20 try:
21 fn = sys.argv[1]
22 except IndexError:
23 fn = 'board.jpg'
24
26 img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
27 img = cv.medianBlur(img, 5)
28 cimg = src.copy() # numpy function
29
30 circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
31
32 if circles is not None: # Check if circles have been found and only then iterate over these and add them to the image
33 circles = np.uint16(np.around(circles))
34 _a, b, _c = circles.shape
35 for i in range(b):
36 cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv.LINE_AA)
37 cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv.LINE_AA) # draw center of circle
38
39 cv.imshow("detected circles", cimg)
40
41 cv.imshow("source", src)
42 cv.waitKey(0)
43 print('Done')
44
45
46if __name__ == '__main__':
47 print(__doc__)
48 main()
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
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 destroyAllWindows()
Destroys all of the HighGUI windows.
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
Converts an image from one color space to another.
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.
void HoughCircles(InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0)
Finds circles in a grayscale image using the Hough transform.
void medianBlur(InputArray src, OutputArray dst, int ksize)
Blurs an image using the median filter.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3