关于SIFT算法的详解可以参考这篇博客:https://blog.csdn.net/zddblog/article/details/7521424
本文旨在使用python+opencv来实现特征点检测的内容。
opencv中已经有写好的SIFT函数cv2.xfeatures2d.SIFT_create().detectAndCompute(),直接使用就行。下面简单讲讲这个函数。
注意:opencv高版本中剔除了cv2.xfeatures2d.SIFT_create()函数,所以要用低版本的opencv,如果你的opencv版本过高,可以用pip uninstall opencv-python 卸载后,使用下面的命令重新安装低版本即可。
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
cv2.xfeatures2d.SIFT_create().detectAndCompute()的参数:
一般是image(需要检测的照片)和None(默认), 即:
cv2.xfeatures2d.SIFT_create().detectAndCompute(image,None)
cv2.xfeatures2d.SIFT_create().detectAndCompute()的返回值:
kps, des = cv2.xfeatures2d.SIFT_create().detectAndCompute()
kps 是关键点,是一个列表,记录所有检测到特征点的信息。它所包含的信息有:
print(type(kp))
#kp的类型:
print(len(kp)))
#kp的个数:8947
print(kp[0].angle)
#167.8749237060547
print(kp[0].class_id)
#-1
print(kp[0].octave)
#15926015
print(kp[0].pt)
#(2.730217695236206, 57.79762268066406)
print(kp[0].response)
#0.02118147909641266
print(kp[0].size)
#2.819002389907837
des:返回特征点的特征描述符,是一个二维列表,或者说是一个矩阵,列表元素为Dmatch类型,输出如下图所示:
print(type(des))#打印des的类型
print(des.shape)#打印des的形状
print(des)#打印des
print(des[1])#打印des[1]
out:
<class 'numpy.ndarray'>
(8947, 128)
[[ 46. 42. 5. ... 0. 0. 0.]
[ 3. 3. 2. ... 0. 0. 0.]
[119. 16. 5. ... 5. 0. 0.]
...
[ 28. 61. 59. ... 0. 0. 0.]
[ 45. 16. 1. ... 0. 0. 0.]
[ 0. 0. 0. ... 81. 66. 52.]]
[ 3. 3. 2. 1. 4. 5. 1. 1. 152. 5. 1. 1. 0. 0.
0. 3. 200. 13. 0. 0. 0. 0. 0. 4. 59. 5. 0. 0.
0. 0. 0. 1. 6. 3. 0. 2. 16. 4. 1. 2. 178. 14.
0. 0. 1. 3. 1. 4. 200. 21. 0. 0. 0. 0. 0. 4.
38. 4. 0. 0. 0. 0. 0. 0. 7. 8. 3. 7. 9. 1.
0. 2. 181. 10. 3. 0. 1. 2. 0. 17. 200. 30. 0. 0.
0. 0. 0. 18. 9. 2. 0. 0. 0. 0. 0. 0. 8. 3.
2. 3. 3. 0. 0. 3. 135. 16. 1. 2. 3. 0. 0. 3.
155. 59. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 0.
0. 0.]
使用这个函数,我们就可以进行编程:
#导入需要的库
import numpy as np
import cv2
from matplotlib import pyplot as plt
#图片地址,改为自己的
img_path = r"E:\Postgraduate project\sift_1\2.JPG"
#引入sift创建函数
sift = cv2.xfeatures2d.SIFT_create()
#读入图片
img = cv2.imread(img_path)
#进行sift特征点检测
kp,des = sift.detectAndCompute(img,None)
#画出关键点
img1=cv2.drawKeypoints(img,kp,img,color=(255,0,0))#color为标记特征点的颜色,按(B,G,R)排的
#显示图片
cv2.imshow('point',img1)
#写入图片,保存的位置改为自己的
cv2.imwrite(r"E:\Postgraduate project\sift_1\sift_2.JPG",img1)
cv2.waitKey(0)#按下任意键退出
cv2.destroyAllWindows()