python-opencv中的KNN简单使用算法举例

# reference: https://docs.opencv.org/3.1.0/d5/d26/tutorial_py_knn_understanding.html
#            opencv-3.3.0/doc/py_tutorials/py_ml/py_knn/py_knn_opencv
import cv2
import numpy as np
import matplotlib.pyplot as plt
 
#创建0-99范围内25行2列类型为FLOAT32类型的随机二维数组
trainData = np.random.randint(0, 100, (25,2)).astype(np.float32)
#创建0-1范围内25行1列类型为FLOAT32类型的随机二维数组(值只包含0和1)
responses = np.random.randint(0, 2, (25,1)).astype(np.float32)
 
# 取出trainData下标对应responses为0的数据
# 也就是把训练集train_data中的某部分数据取出来当作红方标签数据
red = trainData[responses.ravel() == 0]
plt.scatter(red[:,0], red[:,1], 80, 'r', '^')
 
# 取出trainData下标对应responses为1的数据
# 也就是把训练集train_data中的某部分数据取出来当作蓝方标签数据
blue = trainData[responses.ravel() == 1]
plt.scatter(blue[:,0], blue[:,1], 80, 'b', 's')
 
#plt.show()
 
#随机生成一个目标测试数据(一行两列的二维数据,也就是一个随机点)
newcomer = np.random.randint(0, 100, (1,2)).astype(np.float32)
plt.scatter(newcomer[:,0], newcomer[:,1], 80, 'g', 'o')
 
#创建KNN近邻解析器
knn = cv2.ml.KNearest_create()
knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)
#系数K为3,也就是取出欧式距离最近的前3个点
ret, results, neighbours ,dist = knn.findNearest(newcomer, 3)
 
print("result: ", results,"\n")
print("neighbours: ", neighbours,"\n")
print("distance: ", dist)
 
plt.show()

python-opencv中的KNN简单使用算法举例_第1张图片

你可能感兴趣的:(opencv)