Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/python/test/test_kmeans.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
K-means clusterization test
5
'''
6
7
# Python 2/3 compatibility
8
from __future__ import print_function
9
10
import numpy as np
11
import cv2 as cv
12
from numpy import random
13
import sys
14
PY3 = sys.version_info[0] == 3
15
if PY3:
16
xrange = range
17
18
from tests_common import NewOpenCVTests
19
20
def make_gaussians(cluster_n, img_size):
21
points = []
22
ref_distrs = []
23
sizes = []
24
for _ in xrange(cluster_n):
25
mean = (0.1 + 0.8*random.rand(2)) * img_size
26
a = (random.rand(2, 2)-0.5)*img_size*0.1
27
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
28
n = 100 + random.randint(900)
29
pts = random.multivariate_normal(mean, cov, n)
30
points.append( pts )
31
ref_distrs.append( (mean, cov) )
32
sizes.append(n)
33
points = np.float32( np.vstack(points) )
34
return points, ref_distrs, sizes
35
36
def getMainLabelConfidence(labels, nLabels):
37
38
n = len(labels)
39
labelsDict = dict.fromkeys(range(nLabels), 0)
40
labelsConfDict = dict.fromkeys(range(nLabels))
41
42
for i in range(n):
43
labelsDict[labels[i][0]] += 1
44
45
for i in range(nLabels):
46
labelsConfDict[i] = float(labelsDict[i]) / n
47
48
return max(labelsConfDict.values())
49
50
class kmeans_test(NewOpenCVTests):
51
52
def test_kmeans(self):
53
54
np.random.seed(10)
55
56
cluster_n = 5
57
img_size = 512
58
59
points, _, clusterSizes = make_gaussians(cluster_n, img_size)
60
61
term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)
62
_ret, labels, centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)
63
64
self.assertEqual(len(centers), cluster_n)
65
66
offset = 0
67
for i in range(cluster_n):
68
confidence = getMainLabelConfidence(labels[offset : (offset + clusterSizes[i])], cluster_n)
69
offset += clusterSizes[i]
70
self.assertGreater(confidence, 0.9)
71
72
73
if __name__ == '__main__':
74
NewOpenCVTests.bootstrap()
75
76