在opencv官方提供了一种定位的思路,就是通过匹配的点来获取透视变换矩阵,然后经过透视变换后就能够获得对应的目标的坐标了。
import cv2
import numpy as np
# 打开两个文件
img1 = cv2.imread('321.png')
img2 = cv2.imread('3.png')
# 灰度化
g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 他建ORB特征检测器
orb = cv2.ORB_create()
# 计算描述子与特征点
kp1, des1 = orb.detectAndCompute(g1, None)
kp2, des2 = orb.detectAndCompute(g2, None)
# bf创建匹配器
bf = cv2.BFMatcher_create()
# 对描述子进行匹配计算
matchs = bf.knnMatch(des1, des2, k=2)
good = []
for i, (m, n) in enumerate(matchs):
if m.distance < 0.1 * n.distance:
good.append(m)
if len(good) >= 4:
srcPts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dstPts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
# 查找单应性矩阵
H, mask = cv2.findHomography(dstPts, srcPts, cv2.RANSAC,5)
h, w = img2.shape[:2]
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, H)
cv2.polylines(img1, [np.int32(dst)], True, (0, 0, 255),4,16)
else:
print('the number of good is less than 4.')
exit()
ret = cv2.drawMatchesKnn(img1, kp1, img2, kp2, [good], None)
cv2.imshow('result', ret)
cv2.waitKey(0)
cv2.destroyAllWindows()
但是可以通过上一章的方法,利用坐标点来直接定位到目标,而不通过透视变换进行定位。
代码如下:
import cv2
import numpy as np
import matplotlib.pyplot as plt
#读取图片
img=cv2.imread('./3123.png')
tem=cv2.imread('./3.png')
newimg=np.copy(img)
#创建特征点检测器
orb=cv2.ORB_create()
#创建BF特征点匹配器
bf=cv2.BFMatcher_create()
#检测原图特征点
kp1,des1=orb.detectAndCompute(img,mask=None)
#检测模板图特征点
kp2,des2=orb.detectAndCompute(tem,mask=None)
#进行匹配
res=bf.knnMatch(des1,des2,k=2)
good_res=[]
for m,n in res:
if m.distance < 0.1 *n.distance:
good_res.append(m)
def get_rect(res,kp1,kp2):
h,w=tem.shape[0:2]
rect=[]
for i in res:
#获得坐标
point1=cv2.KeyPoint_convert(kp1,keypointIndexes=[i.queryIdx])
point2 = cv2.KeyPoint_convert(kp2, keypointIndexes=[i.trainIdx])
point1=[int(np.ravel(point1)[0]),int(np.ravel(point1)[1])]
point2 = [int(np.ravel(point2)[0]), int(np.ravel(point2)[1])]
#获得目标框左上角的坐标
minx = point1[0] - point2[0]
miny = point1[1] - point2[1]
#消除多余的目标框
if [minx, miny, w, h] not in rect:
rect.append([minx, miny, w, h])
return rect
rect=get_rect(good_res,kp1,kp2)
#画出目标框
for i in range(len(rect)):
cv2.rectangle(newimg,rect[i],[255,0,0],4,16)
#将最相近的10个点绘画出来
newimg=cv2.drawMatches(newimg,kp1,tem,kp2,good_res,None)
#绘制原图特征点
img=cv2.drawKeypoints(img,kp1,None,color=[0,0,255])
tem=cv2.drawKeypoints(tem,kp2,None,color=[0,255,0])
cv2.imshow('frams',newimg)
cv2.waitKey(0)
cv2.destroyAllWindows()