kmeans.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. '''
  3. K-means clusterization sample.
  4. Usage:
  5. kmeans.py
  6. Keyboard shortcuts:
  7. ESC - exit
  8. space - generate new distribution
  9. '''
  10. # Python 2/3 compatibility
  11. from __future__ import print_function
  12. import numpy as np
  13. import cv2 as cv
  14. from gaussian_mix import make_gaussians
  15. def main():
  16. cluster_n = 5
  17. img_size = 512
  18. # generating bright palette
  19. colors = np.zeros((1, cluster_n, 3), np.uint8)
  20. colors[0,:] = 255
  21. colors[0,:,0] = np.arange(0, 180, 180.0/cluster_n)
  22. colors = cv.cvtColor(colors, cv.COLOR_HSV2BGR)[0]
  23. while True:
  24. print('sampling distributions...')
  25. points, _ = make_gaussians(cluster_n, img_size)
  26. term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)
  27. _ret, labels, _centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)
  28. img = np.zeros((img_size, img_size, 3), np.uint8)
  29. for (x, y), label in zip(np.int32(points), labels.ravel()):
  30. c = list(map(int, colors[label]))
  31. cv.circle(img, (x, y), 1, c, -1)
  32. cv.imshow('kmeans', img)
  33. ch = cv.waitKey(0)
  34. if ch == 27:
  35. break
  36. print('Done')
  37. if __name__ == '__main__':
  38. print(__doc__)
  39. main()
  40. cv.destroyAllWindows()