Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/python/test/test_houghcircles.py
16337 views
1
#!/usr/bin/python
2
3
'''
4
This example illustrates how to use cv.HoughCircles() function.
5
'''
6
7
# Python 2/3 compatibility
8
from __future__ import print_function
9
10
import cv2 as cv
11
import numpy as np
12
import sys
13
from numpy import pi, sin, cos
14
15
from tests_common import NewOpenCVTests
16
17
def circleApproximation(circle):
18
19
nPoints = 30
20
dPhi = 2*pi / nPoints
21
contour = []
22
for i in range(nPoints):
23
contour.append(([circle[0] + circle[2]*cos(i*dPhi),
24
circle[1] + circle[2]*sin(i*dPhi)]))
25
26
return np.array(contour).astype(int)
27
28
def convContoursIntersectiponRate(c1, c2):
29
30
s1 = cv.contourArea(c1)
31
s2 = cv.contourArea(c2)
32
33
s, _ = cv.intersectConvexConvex(c1, c2)
34
35
return 2*s/(s1+s2)
36
37
class houghcircles_test(NewOpenCVTests):
38
39
def test_houghcircles(self):
40
41
fn = "samples/data/board.jpg"
42
43
src = self.get_sample(fn, 1)
44
img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
45
img = cv.medianBlur(img, 5)
46
47
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)[0]
48
49
testCircles = [[38, 181, 17.6],
50
[99.7, 166, 13.12],
51
[142.7, 160, 13.52],
52
[223.6, 110, 8.62],
53
[79.1, 206.7, 8.62],
54
[47.5, 351.6, 11.64],
55
[189.5, 354.4, 11.64],
56
[189.8, 298.9, 10.64],
57
[189.5, 252.4, 14.62],
58
[252.5, 393.4, 15.62],
59
[602.9, 467.5, 11.42],
60
[222, 210.4, 9.12],
61
[263.1, 216.7, 9.12],
62
[359.8, 222.6, 9.12],
63
[518.9, 120.9, 9.12],
64
[413.8, 113.4, 9.12],
65
[489, 127.2, 9.12],
66
[448.4, 121.3, 9.12],
67
[384.6, 128.9, 8.62]]
68
69
matches_counter = 0
70
71
for i in range(len(testCircles)):
72
for j in range(len(circles)):
73
74
tstCircle = circleApproximation(testCircles[i])
75
circle = circleApproximation(circles[j])
76
if convContoursIntersectiponRate(tstCircle, circle) > 0.6:
77
matches_counter += 1
78
79
self.assertGreater(float(matches_counter) / len(testCircles), .5)
80
self.assertLess(float(len(circles) - matches_counter) / len(circles), .75)
81
82
83
if __name__ == '__main__':
84
NewOpenCVTests.bootstrap()
85
86