Path: blob/master/modules/python/test/test_gaussian_mix.py
16337 views
#!/usr/bin/env python12# Python 2/3 compatibility3from __future__ import print_function4import sys5PY3 = sys.version_info[0] == 367if PY3:8xrange = range910import numpy as np11from numpy import random12import cv2 as cv1314def make_gaussians(cluster_n, img_size):15points = []16ref_distrs = []17for _ in xrange(cluster_n):18mean = (0.1 + 0.8*random.rand(2)) * img_size19a = (random.rand(2, 2)-0.5)*img_size*0.120cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)21n = 100 + random.randint(900)22pts = random.multivariate_normal(mean, cov, n)23points.append( pts )24ref_distrs.append( (mean, cov) )25points = np.float32( np.vstack(points) )26return points, ref_distrs2728from tests_common import NewOpenCVTests2930class gaussian_mix_test(NewOpenCVTests):3132def test_gaussian_mix(self):3334np.random.seed(10)35cluster_n = 536img_size = 5123738points, ref_distrs = make_gaussians(cluster_n, img_size)3940em = cv.ml.EM_create()41em.setClustersNumber(cluster_n)42em.setCovarianceMatrixType(cv.ml.EM_COV_MAT_GENERIC)43em.trainEM(points)44means = em.getMeans()45covs = em.getCovs() # Known bug: https://github.com/opencv/opencv/pull/423246#found_distrs = zip(means, covs)4748matches_count = 04950meanEps = 0.0551covEps = 0.15253for i in range(cluster_n):54for j in range(cluster_n):55if (cv.norm(means[i] - ref_distrs[j][0], cv.NORM_L2) / cv.norm(ref_distrs[j][0], cv.NORM_L2) < meanEps and56cv.norm(covs[i] - ref_distrs[j][1], cv.NORM_L2) / cv.norm(ref_distrs[j][1], cv.NORM_L2) < covEps):57matches_count += 15859self.assertEqual(matches_count, cluster_n)606162if __name__ == '__main__':63NewOpenCVTests.bootstrap()646566