Link API Reference .
# -*- coding: utf-8 -*-
import numpy as np
from numpy import random
import cv2
#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline
#データ生成(2特徴量)。2群。
# 25~59の整数乱数を25x2の行列で生成
a = np.random.randint(25, 60, (50,2))
# 60~84の整数乱数を25x2の行列で生成
b = np.random.randint(60, 85, (50,2))
#データの連結(v stack)。2群を連結。
in_data = np.vstack((a,b))
# np.float32に変換
in_data = np.float32(in_data)
#判断基準の設定
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
#kmeansの実行
cluster_n = 2
ret, label, center = cv2.kmeans(in_data, cluster_n, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# データを付与ラベル(0,1)で分ける
A = in_data[label.ravel()==0]
B = in_data[label.ravel()==1]
print "A center:", center[0,:], ", B center:", center[1,:]
# グラフ表示
plt.figure(figsize=(10,10))
plt.scatter(A[:,0], A[:,1])
plt.scatter(B[:,0], B[:,1], c = 'r')
plt.scatter(center[:,0], center[:,1], s = 80, c = 'y', marker = 's')
plt.xlabel('Height'),plt.ylabel('Weight')
plt.show()