Path: blob/master/modules/python/test/test_kmeans.py
16337 views
#!/usr/bin/env python12'''3K-means clusterization test4'''56# Python 2/3 compatibility7from __future__ import print_function89import numpy as np10import cv2 as cv11from numpy import random12import sys13PY3 = sys.version_info[0] == 314if PY3:15xrange = range1617from tests_common import NewOpenCVTests1819def make_gaussians(cluster_n, img_size):20points = []21ref_distrs = []22sizes = []23for _ in xrange(cluster_n):24mean = (0.1 + 0.8*random.rand(2)) * img_size25a = (random.rand(2, 2)-0.5)*img_size*0.126cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)27n = 100 + random.randint(900)28pts = random.multivariate_normal(mean, cov, n)29points.append( pts )30ref_distrs.append( (mean, cov) )31sizes.append(n)32points = np.float32( np.vstack(points) )33return points, ref_distrs, sizes3435def getMainLabelConfidence(labels, nLabels):3637n = len(labels)38labelsDict = dict.fromkeys(range(nLabels), 0)39labelsConfDict = dict.fromkeys(range(nLabels))4041for i in range(n):42labelsDict[labels[i][0]] += 14344for i in range(nLabels):45labelsConfDict[i] = float(labelsDict[i]) / n4647return max(labelsConfDict.values())4849class kmeans_test(NewOpenCVTests):5051def test_kmeans(self):5253np.random.seed(10)5455cluster_n = 556img_size = 5125758points, _, clusterSizes = make_gaussians(cluster_n, img_size)5960term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)61_ret, labels, centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)6263self.assertEqual(len(centers), cluster_n)6465offset = 066for i in range(cluster_n):67confidence = getMainLabelConfidence(labels[offset : (offset + clusterSizes[i])], cluster_n)68offset += clusterSizes[i]69self.assertGreater(confidence, 0.9)707172if __name__ == '__main__':73NewOpenCVTests.bootstrap()747576