gaussian_mix.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. # Python 2/3 compatibility
  3. from __future__ import print_function
  4. import sys
  5. PY3 = sys.version_info[0] == 3
  6. if PY3:
  7. xrange = range
  8. import numpy as np
  9. import cv2 as cv
  10. from numpy import random
  11. def make_gaussians(cluster_n, img_size):
  12. points = []
  13. ref_distrs = []
  14. for _i in xrange(cluster_n):
  15. mean = (0.1 + 0.8*random.rand(2)) * img_size
  16. a = (random.rand(2, 2)-0.5)*img_size*0.1
  17. cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
  18. n = 100 + random.randint(900)
  19. pts = random.multivariate_normal(mean, cov, n)
  20. points.append( pts )
  21. ref_distrs.append( (mean, cov) )
  22. points = np.float32( np.vstack(points) )
  23. return points, ref_distrs
  24. def draw_gaussain(img, mean, cov, color):
  25. x, y = mean
  26. w, u, _vt = cv.SVDecomp(cov)
  27. ang = np.arctan2(u[1, 0], u[0, 0])*(180/np.pi)
  28. s1, s2 = np.sqrt(w)*3.0
  29. cv.ellipse(img, (int(x), int(y)), (int(s1), int(s2)), ang, 0, 360, color, 1, cv.LINE_AA)
  30. def main():
  31. cluster_n = 5
  32. img_size = 512
  33. print('press any key to update distributions, ESC - exit\n')
  34. while True:
  35. print('sampling distributions...')
  36. points, ref_distrs = make_gaussians(cluster_n, img_size)
  37. print('EM (opencv) ...')
  38. em = cv.ml.EM_create()
  39. em.setClustersNumber(cluster_n)
  40. em.setCovarianceMatrixType(cv.ml.EM_COV_MAT_GENERIC)
  41. em.trainEM(points)
  42. means = em.getMeans()
  43. covs = em.getCovs() # Known bug: https://github.com/opencv/opencv/pull/4232
  44. found_distrs = zip(means, covs)
  45. print('ready!\n')
  46. img = np.zeros((img_size, img_size, 3), np.uint8)
  47. for x, y in np.int32(points):
  48. cv.circle(img, (x, y), 1, (255, 255, 255), -1)
  49. for m, cov in ref_distrs:
  50. draw_gaussain(img, m, cov, (0, 255, 0))
  51. for m, cov in found_distrs:
  52. draw_gaussain(img, m, cov, (0, 0, 255))
  53. cv.imshow('gaussian mixture', img)
  54. ch = cv.waitKey(0)
  55. if ch == 27:
  56. break
  57. print('Done')
  58. if __name__ == '__main__':
  59. print(__doc__)
  60. main()
  61. cv.destroyAllWindows()