import cv2 import numpy as np MAX_FEATURES = 500 # 最大的特性 GOOD_MATCH_PERCENT = 0.15 # 好的匹配百分比 # '模板对比' def alignImages(im1, im2): # 将图像转换为灰度 im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) # 检测ORB特性和计算描述符 orb = cv2.ORB_create(MAX_FEATURES) keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None) keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None) # 匹配特性 matcher = cv2.DescriptorMatcher_create( cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING) matches = matcher.match(descriptors1, descriptors2, None) # 按分数对匹配进行排序 matches.sort(key=lambda x: x.distance, reverse=False) # 删除不太好的匹配 numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT) matches = matches[:numGoodMatches] # 画上匹配 imMatches = cv2.drawMatches( im1, keypoints1, im2, keypoints2, matches, None) cv2.imwrite("matches.jpg", imMatches) # 提取好匹配的位置 points1 = np.zeros((len(matches), 2), dtype=np.float32) points2 = np.zeros((len(matches), 2), dtype=np.float32) for i, match in enumerate(matches): points1[i, :] = keypoints1[match.queryIdx].pt points2[i, :] = keypoints2[match.trainIdx].pt # 发现单应性 h, mask = cv2.findHomography(points1, points2, cv2.RANSAC) # Use homography height, width, channels = im2.shape im1Reg = cv2.warpPerspective(im1, h, (width, height)) return im1Reg, h if __name__ == '__main__': # 读取参考图像 refFilename = "./img/1.png" print("Reading reference image : ", refFilename) imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR) # 读取要对齐的图像 imFilename = "./img/3.png" print("Reading image to align : ", imFilename) im = cv2.imread(imFilename, cv2.IMREAD_COLOR) print("Aligning images ...") # 注册的图像将在imReg中被重新定位。 # 估计的单应式存储在h中。 imReg, h = alignImages(im, imReference) # 将对齐的图像写入磁盘 outFilename = "aligned.jpg" print("Saving aligned image : ", outFilename) cv2.imwrite(outFilename, imReg) # Print estimated homography print("Estimated homography : \n", h)