# -*- encoding=utf-8 -*-
__author__ = 'Jeff.xie'
#这个方法识别度更高,比cv2.matchTemplate更好,
#cv2.matchTemplate无定位的图片,这个方法可以
import cv2
# bgPath='D:\\Reg_Card_007_IOS_02.png'
# desPath='D:\\ReportLostCard.png'
bgPath='D:\\Setting.png'
desPath='D:\\Connect.png'
img1=cv2.imread(bgPath) #大图
img2=cv2.imread(desPath)
#使用SIFT算法获取图像特征的关键点和描述符
sift=cv2.xfeatures2d.SIFT_create()
kp1,des1=sift.detectAndCompute(img1,None)
kp2,des2=sift.detectAndCompute(img2,None)
#定义FLANN匹配器
indexParams=dict(algorithm=0,trees=10)
searchParams=dict(checks=50)
flann=cv2.FlannBasedMatcher(indexParams,searchParams)
#使用KNN算法实现图像匹配,并对匹配结果排序
matches=flann.knnMatch(des1,des2,k=2)
matches=sorted(matches,key=lambda x:x[0].distance)
#去除错误匹配,0.5是系数,系数大小不同,匹配的结果页不同
goodMatches=[]
for m,n in matches:
if m.distance<0.5*n.distance:
goodMatches.append(m)
print(len(matches))
print(len(goodMatches))
#获取某个点的坐标位置
#index是获取匹配结果的中位数
index=int(len(goodMatches)/2)
#queryIdx是目标图像的描述符索引
x,y=kp1[goodMatches[0].queryIdx].pt #获取小图片中心点
#将坐标位置勾画在2.png图片上,并显示
src_img = cv2.imread(bgPath,cv2.IMREAD_GRAYSCALE)
height,width = src_img.shape
print("width:",width)
print("height:",height)
des_img = cv2.imread(desPath,cv2.IMREAD_GRAYSCALE)
des_height,des_width = des_img.shape
print("des_width:",des_width)
print("des_height:",des_height)
print(x)
print(y)
xper = int(x/width*100)
yper = int(y/height*100)
print("xper",xper)
print("yper",yper)
x1 = int(x-des_width/2)
y1 = int(y-des_height/2)
x2 = int(x+des_width/2)
y2 = int(y+des_height/2)
# cv2.rectangle(img1,(int(x),int(y)),(int(x)+50,int(y)+50),(0,255,0),2)
cv2.rectangle(img1,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow('baofeng',img1)
cv2.waitKey()