Python OpenCV3 KNN Algorithm

Foreword

Next, i’ll introduce a classification algoriithm—KNN,and of course i’ll show you how to use it in Python.

What’s the KNN?

KNN is the abbreviation of K-Nearest Neighbor .This algorithm is not only a relatively mature in theory ,but also one of the simplest machine learning algorithm.Next,i’ll give you an exanple to help you understang the idea of this algorithm.
KNN
Which kind of green circle in the above figure should be divided into ?Red triangle or blue square?In KNN algorithm, if k = 3, because the proportion of red triangle is two-thirds, the green circle is divided into red triangle.If k=5,because the proportion of blue square is three-fifths,the green circle is divided into blue square.If k=4,the green circle will be divided into red triangle because the shorter the distance, the greater the weight.

Library

pip install opencv-python

Python code

import cv2
# 按照灰度圖像的方式讀入兩幅圖片
img1 = cv2.imread("./8.jpg", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("./9.jpg", cv2.IMREAD_GRAYSCALE)
# 創建ORB特徵檢測器和描述符
orb = cv2.ORB_create()
# 對兩幅圖像檢測特徵和描述符
keypoint1, descriptor1 = orb.detectAndCompute(img1, None)
keypoint2, descriptor2 = orb.detectAndCompute(img2, None)

# 獲得一個暴力匹配器的對象
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
maches = bf.knnMatch(descriptor1, descriptor2, k=1)
# 畫出匹配項
img3 = cv2.drawMatchesKnn(img1, keypoint1, img2, keypoint2, maches[0:70], img2, flags=2)

cv2.imshow("KNN", img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

Display

The result of KNN algorithm is almost the same as that of BF algorithm,but KNN runs longer.It’s suitable for rare events classification,especially for polyphenol problems.

在這裏插入圖片描述

In the next blog, i’ll introduce a faster classification algorithm—FLANN.

我希望我這樣一本正經地做出要離開的樣子,會引起你的注意。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章