|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Time : 2017/8/8 12:33 |
| 3 | +# @Author : play4fun |
| 4 | +# @File : knn-find_nearest.py |
| 5 | +# @Software: PyCharm |
| 6 | + |
| 7 | +""" |
| 8 | +knn-find_nearest.py: |
| 9 | +http://www.bogotobogo.com/python/OpenCV_Python/python_opencv3_Machine_Learning_Classification_K-nearest_neighbors_k-NN.php |
| 10 | +""" |
| 11 | + |
| 12 | +import cv2 |
| 13 | +import numpy as np |
| 14 | +import matplotlib.pyplot as plt |
| 15 | + |
| 16 | +# Feature set containing (x,y) values of 25 known/training data |
| 17 | +trainData = np.random.randint(0, 100, (25, 2)).astype(np.float32) |
| 18 | + |
| 19 | +# Labels each one either Red or Blue with numbers 0 and 1 |
| 20 | +responses = np.random.randint(0, 2, (25, 1)).astype(np.float32) |
| 21 | + |
| 22 | +# plot Reds |
| 23 | +red = trainData[responses.ravel() == 0] |
| 24 | +plt.scatter(red[:, 0], red[:, 1], 80, 'r', '^') |
| 25 | + |
| 26 | +# plot Blues |
| 27 | +blue = trainData[responses.ravel() == 1] |
| 28 | +plt.scatter(blue[:, 0], blue[:, 1], 80, 'b', 's') |
| 29 | + |
| 30 | +# CvKNearest instance |
| 31 | +# knn = cv2.KNearest() |
| 32 | +knn = cv2.ml.KNearest_create() |
| 33 | +# trains the model |
| 34 | +knn.train(trainData, responses)#TODO |
| 35 | +#TypeError: only length-1 arrays can be converted to Python scalars |
| 36 | + |
| 37 | + |
| 38 | +# New sample : (x,y) |
| 39 | +newcomer = np.random.randint(0, 100, (1, 2)).astype(np.float32) |
| 40 | +plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o') |
| 41 | + |
| 42 | +# Finds the 3nearest neighbors and predicts responses for input vectors |
| 43 | +ret, results, neighbours, dist = knn.find_nearest(newcomer, 3) |
| 44 | + |
| 45 | +print("result: ", results, "\n") |
| 46 | +print("neighbours: ", neighbours, "\n") |
| 47 | +print("distance: ", dist) |
| 48 | + |
| 49 | +plt.show() |
0 commit comments