import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('E:/python/1.jpg',0)
img2 = cv2.imread('E:/python/2.jpg',0)
#orb寻找特征点
orb = cv2.ORB_create(5000)
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
#bf匹配
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
matches = bf.knnMatch(des1, trainDescriptors = des2, k = 2)
good = [m for (m,n) in matches if m.distance < 0.35*n.distance]
min_match_count=5
if len(good)>min_match_count:
#匹配点
src_pts=np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
dst_pts=np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
#找到变换矩阵m
m,mask=cv2.findHomography(src_pts,dst_pts,cv2.RANSAC,5,0)
matchmask=mask.ravel().tolist()
h,w=img1.shape
pts=np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)
dst=cv2.perspectiveTransform(pts,m)
cv2.polylines(img2,[np.int32(dst)],True,255,10,cv2.LINE_AA)
else:
print('not enough matches are found -- %d/%d'(len(good),min_match_count))
matchmask=None
draw_params=dict(matchColor=(0,255,0),singlePointColor=None,
matchesMask=matchmask,flags=2)
img3=cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
plt.imshow(img3,'gray')
plt.show()

