| OpenCV 5.0.0alpha Open Source Computer Vision

Loading...
Searching...
No Matches
samples/python/snippets/kmeans.py

An example on k-means clustering in python

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 def main():
22 cluster_n = 5
23 img_size = 512
24
25 # generating bright palette
26 colors = np.zeros((1, cluster_n, 3), np.uint8)
27 colors[0,:] = 255
28 colors[0,:,0] = np.arange(0, 180, 180.0/cluster_n)
29 colors = cv.cvtColor(colors, cv.COLOR_HSV2BGR)[0]
30
31 while True:
32 print('sampling distributions...')
33 points, _ = make_gaussians(cluster_n, img_size)
34
35 term_crit = (cv.TERM_CRITERIA_EPS, 30, 0.1)
36 _ret, labels, _centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)
37
38 img = np.zeros((img_size, img_size, 3), np.uint8)
39 for (x, y), label in zip(np.int32(points), labels.ravel()):
40 c = list(map(int, colors[label]))
41
42 cv.circle(img, (x, y), 1, c, -1)
43
44 cv.imshow('kmeans', img)
45 ch = cv.waitKey(0)
46 if ch == 27:
47 break
48
49 print('Done')
50
51
52 if __name__ == '__main__':
53 print(__doc__)
54 main()
55 cv.destroyAllWindows()
cv::kmeans
double kmeans(InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray())
Finds centers of clusters and groups input samples around the clusters.
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
cv::destroyAllWindows
void destroyAllWindows()
Destroys all of the HighGUI windows.
cv::cvtColor
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
Converts an image from one color space to another.
cv::circle
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.
main
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3