import cv2
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import matplotlib as mpl
from PIL import Image
img_1 = cv2.imread("Num.jpg")
img_2 = cv2.imread("trafic_jam.jpg")
img1 = cv2.cvtColor(img_1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img_2, cv2.COLOR_BGR2GRAY)
plt.axis('off')
plt.imshow(img1, cmap='gray')
plt.show()
plt.axis('off')
plt.imshow(img2, cmap='gray')
plt.show()
#sift为实例化的sift函数
sift = cv2.xfeatures2d.SIFT_create()
#查找特征点和特征向量
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
#匹配特征向量
bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=True)
matches = bf.match(des1,des2)
#按距离大小排序
matches = sorted(matches, key = lambda x:x.distance)
print('重合的特征点', len(matches))
for i in range(0,3): #前三个
print('距离 ',matches[i].distance,' 1 ',matches[i].trainIdx,'2 ', matches[i].queryIdx)
#标出特征图像
matching_result = cv2.drawMatches(img_1, kp1, img_2, kp2, matches[:5], None, [255,0,0], flags=2)
mpl.rcParams['figure.dpi'] = 200
plt.axis('off')
plt.imshow(cv2.cvtColor(matching_result, cv2.COLOR_BGR2RGB))
plt.show()
原图:
匹配结果:
图像重建
img_1 = cv2.imread("tt_2.jpg")
img_2 = cv2.imread("tt_1.jpg")
img1 = cv2.cvtColor(img_1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img_2, cv2.COLOR_BGR2GRAY)
mpl.rcParams['figure.dpi'] = 100
plt.axis('off')
plt.imshow(cv2.cvtColor(img_1, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.imshow(cv2.cvtColor(img_2, cv2.COLOR_BGR2RGB))
#提取特征并匹配
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=True)
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x:x.distance)
#提取匹配的特征点
new1 = np.float32([kp1[m.queryIdx].pt for m in matches])
new2 = np.float32([kp2[m.trainIdx].pt for m in matches])
#根据特征点计算转换矩阵
H, status = cv2.findHomography(new1, new2, cv2.RANSAC, 4.0)
#根据转换矩阵重建
width = img1.shape[1] + img2.shape[1]
height = max(img1.shape[0],img2.shape[0])
result = cv2.warpPerspective(img_1, H, (width,height)) #Трансформируем 1-ое изображение
result[0:img2.shape[0], 0:img2.shape[1]] = img_2 #Накладываем 2-ое изображение в крайний левый угол
mpl.rcParams['figure.dpi'] = 200
plt.axis('off')
plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
plt.show()
原图:
结果: