import numpy as np
import cv2
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
img1 = cv2.imread("D:/data/North/0007.JPG",0)
img2 = cv2.imread("D:/data/North/0019.JPG",0)
img1 = cv2.resize(img1, (1920, 1080))
img2 = cv2.resize(img2, (1920, 1080))
surf = cv2.xfeatures2d.SURF_create(1200)
kp1 = surf.detect(img1, None)
kp2 = surf.detect(img2, None)
# kp:检测到的特征点 des:描述子矩阵
kp1, des1 = surf.compute(img1, kp1)
kp2, des2 = surf.compute(img2, kp2)
# img2=cv2.drawKeypoints(img,kp,None,(255,0,0),4)
bf = cv2.BFMatcher(cv2.NORM_L2)
matchesknn = bf.knnMatch(des1, des2, k=2) # knn 匹配可以返回k个最佳的匹配项、bf返回所有的匹配项
good = []
for m, n in matchesknn:
if m.distance < 0.7 * n.distance:
good.append(m)
img32 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matchesknn, img2, flags=2)
imgknnfilter = cv2.drawMatches(img1, kp1, img2, kp2, good, img2, flags=2)
imgsurfshowkp = cv2.drawKeypoints(img2, kp2, img2, flags=4)
print('matchesknn' + str(len(matchesknn)))
print(matchesknn)
print('good' + str(len(good)))
# plt.title('SURF特征点提取',fontsize=12)
plt.imshow(imgsurfshowkp)
plt.axis('off')
plt.savefig('featureExtract.png', dpi=300, bbox_inches='tight', pad_inches=0.0)
plt.show()
# plt.figure(figsize=(10,10))
# plt.title('knn法匹配(noFilter)',fontsize=12)
plt.figure(dpi=300, figsize=(16,9))
plt.imshow(img32)
plt.axis('off')
plt.savefig('knnNoFilter.png', dpi=300, bbox_inches='tight', pad_inches=0.0)
plt.show()
# plt.title('knn法匹配(withFilter)',fontsize=12)
plt.figure(dpi=300, figsize=(16,9))
plt.imshow(imgknnfilter)
plt.axis('off')
plt.savefig('knnWithFilter.png', dpi=300, bbox_inches='tight', pad_inches=0.0)
plt.show()
#
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# match
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
# draw
img12 = cv2.drawMatches(img1, kp1, img2, kp2, matches[: 50], img2, flags=2)
# plt.figure(figsize=(10,10))
# plt.title('surf检测特征点',fontsize=20)
plt.title('暴力法匹配',fontsize=12)
plt.axis('off')
plt.imshow(img12)
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
出现
SyntaxError: (unicode error) 'unicodeescape' `在这里插入代码片`codec can't decode bytes in position 7-8: malformed \N character escape
问题,使用反斜杠更改路径
算法被申请了专利,将opencv版本退到3.4.2即可解决,必须小于等于Python3.7
遇到这个问题 首先检查自己配置的python版本python --version ,这里要求是3.7版本的。
如果高版本无法转换到3.7的话建议重新创建一个虚拟环境。
conda安装虚拟环境
#这样就创建了一个名字为my_env_name,基于python版本3.7的一个虚拟环境了。
conda create -n my_env_name python=3.7
conda虚拟环境的激活脚本
activate my_env_name
安装虚拟环境的激活脚本3.4.2.17
#?卸载opencv
pip uninstall opencv-python
#安装3.4.2.16
pip install opencv-python==3.4.2.16 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install opencv-contrib-python==3.4.2.16 -i https://pypi.tuna.tsinghua.edu.cn/simple
在pycharm中添加解释器,找到Anaconda目录下的envs文件夹,进去找到自己配置的虚拟环境文件夹,再找到python.exe文件,点击选中即可。点击确定。
pip install matplotlib -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com