Implementing k-NN in OpenCV

Using OpenCV, we can easily create a k-NN model via the cv2.ml.KNearest_create() function. Building the model then involves the following steps:

  1. Generate some training data.
  2. Create a k-NN object for a given number, k.
  1. Find the k nearest neighbors of a new data point that we want to classify.
  2. Assign the class label of the new data point by majority vote.
  3. Plot the result.

We first import all of the necessary modules: OpenCV for the k-NN algorithm, NumPy for data processing, and Matplotlib for plotting. If you are working in a Jupyter Notebook, don't forget to call the %matplotlib inline magic:

In [1]: import numpy as np
... import cv2
... import matplotlib.pyplot as plt
... %matplotlib inline
In [2]: plt.style.use('ggplot')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158