Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/kmeans.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
K-means clusterization sample.
5
Usage:
6
kmeans.py
7
8
Keyboard shortcuts:
9
ESC - exit
10
space - generate new distribution
11
'''
12
13
# Python 2/3 compatibility
14
from __future__ import print_function
15
16
import numpy as np
17
import cv2 as cv
18
19
from gaussian_mix import make_gaussians
20
21
if __name__ == '__main__':
22
cluster_n = 5
23
img_size = 512
24
25
print(__doc__)
26
27
# generating bright palette
28
colors = np.zeros((1, cluster_n, 3), np.uint8)
29
colors[0,:] = 255
30
colors[0,:,0] = np.arange(0, 180, 180.0/cluster_n)
31
colors = cv.cvtColor(colors, cv.COLOR_HSV2BGR)[0]
32
33
while True:
34
print('sampling distributions...')
35
points, _ = make_gaussians(cluster_n, img_size)
36
37
term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)
38
ret, labels, centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)
39
40
img = np.zeros((img_size, img_size, 3), np.uint8)
41
for (x, y), label in zip(np.int32(points), labels.ravel()):
42
c = list(map(int, colors[label]))
43
44
cv.circle(img, (x, y), 1, c, -1)
45
46
cv.imshow('gaussian mixture', img)
47
ch = cv.waitKey(0)
48
if ch == 27:
49
break
50
cv.destroyAllWindows()
51
52