代码和笔记
import cv2
import numpy as np"""
图像查找--特征匹配的应用,通过特征匹配和单应性矩阵
单应性变换:描述物体在世界坐标系(原图)和像素坐标系(对比图)之间的位置映射关系,对应的变换矩阵成为单应性矩阵
应用-图像摆正、图片替换
"""
img1 = cv2.imread('./img/ca2.jpeg')
img2 = cv2.imread('./img/cat.jpeg')gary1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gary2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(gary1, None)
kp2, des2 = sift.detectAndCompute(gary2, None)
bf = cv2.BFMatcher(cv2.NORM_L1)
match = bf.match(des1, des2)
if len(match) >= 4:src_points = np.float32([kp1[m.queryIdx].pt for m in match]).reshape(-1, 1, 2)dst_points = np.float32([kp2[m.trainIdx].pt for m in match]).reshape(-1, 1, 2)H, _ = cv2.findHomography(src_points, dst_points, cv2.RANSAC, 5)h, w = img1.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(img2, [np.int32(dst)], True, (0, 0, 255), 2)
else:exit()
ret = cv2.drawMatches(img1, kp1, img2, kp2, match, None)
cv2.imshow('ret', ret)
cv2.waitKey(0)
cv2.destroyAllWindows()