3
# Python 2/3 compatibility
4
from __future__ import print_function
6
PY3 = sys.version_info[0] == 3
12
from numpy import random
15
def make_gaussians(cluster_n, img_size):
18
for i in xrange(cluster_n):
19
mean = (0.1 + 0.8*random.rand(2)) * img_size
20
a = (random.rand(2, 2)-0.5)*img_size*0.1
21
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
22
n = 100 + random.randint(900)
23
pts = random.multivariate_normal(mean, cov, n)
25
ref_distrs.append( (mean, cov) )
26
points = np.float32( np.vstack(points) )
27
return points, ref_distrs
29
def draw_gaussain(img, mean, cov, color):
31
w, u, vt = cv2.SVDecomp(cov)
32
ang = np.arctan2(u[1, 0], u[0, 0])*(180/np.pi)
33
s1, s2 = np.sqrt(w)*3.0
34
cv2.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv2.LINE_AA)
37
if __name__ == '__main__':
41
print('press any key to update distributions, ESC - exit\n')
44
print('sampling distributions...')
45
points, ref_distrs = make_gaussians(cluster_n, img_size)
47
print('EM (opencv) ...')
48
em = cv2.ml.EM_create()
49
em.setClustersNumber(cluster_n)
50
em.setCovarianceMatrixType(cv2.ml.EM_COV_MAT_GENERIC)
53
covs = em.getCovs() # Known bug: https://github.com/Itseez/opencv/pull/4232
54
found_distrs = zip(means, covs)
57
img = np.zeros((img_size, img_size, 3), np.uint8)
58
for x, y in np.int32(points):
59
cv2.circle(img, (x, y), 1, (255, 255, 255), -1)
60
for m, cov in ref_distrs:
61
draw_gaussain(img, m, cov, (0, 255, 0))
62
for m, cov in found_distrs:
63
draw_gaussain(img, m, cov, (0, 0, 255))
65
cv2.imshow('gaussian mixture', img)
66
ch = 0xFF & cv2.waitKey(0)
69
cv2.destroyAllWindows()