File: test_kmeans.py

package info (click to toggle)
opencv 3.2.0%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 238,480 kB
  • sloc: xml: 901,650; cpp: 703,419; lisp: 20,142; java: 17,843; python: 17,641; ansic: 603; cs: 601; sh: 516; perl: 494; makefile: 117
file content (70 lines) | stat: -rw-r--r-- 1,839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python

'''
K-means clusterization test
'''

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2
from numpy import random
import sys
PY3 = sys.version_info[0] == 3
if PY3:
    xrange = range

from tests_common import NewOpenCVTests

def make_gaussians(cluster_n, img_size):
    points = []
    ref_distrs = []
    sizes = []
    for i in xrange(cluster_n):
        mean = (0.1 + 0.8*random.rand(2)) * img_size
        a = (random.rand(2, 2)-0.5)*img_size*0.1
        cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
        n = 100 + random.randint(900)
        pts = random.multivariate_normal(mean, cov, n)
        points.append( pts )
        ref_distrs.append( (mean, cov) )
        sizes.append(n)
    points = np.float32( np.vstack(points) )
    return points, ref_distrs, sizes

def getMainLabelConfidence(labels, nLabels):

    n = len(labels)
    labelsDict = dict.fromkeys(range(nLabels), 0)
    labelsConfDict = dict.fromkeys(range(nLabels))

    for i in range(n):
        labelsDict[labels[i][0]] += 1

    for i in range(nLabels):
        labelsConfDict[i] = float(labelsDict[i]) / n

    return max(labelsConfDict.values())

class kmeans_test(NewOpenCVTests):

    def test_kmeans(self):

        np.random.seed(10)

        cluster_n = 5
        img_size = 512

        points, _, clusterSizes = make_gaussians(cluster_n, img_size)

        term_crit = (cv2.TERM_CRITERIA_EPS, 30, 0.1)
        ret, labels, centers = cv2.kmeans(points, cluster_n, None, term_crit, 10, 0)

        self.assertEqual(len(centers), cluster_n)

        offset = 0
        for i in range(cluster_n):
            confidence = getMainLabelConfidence(labels[offset : (offset + clusterSizes[i])], cluster_n)
            offset += clusterSizes[i]
            self.assertGreater(confidence, 0.9)