用sift使用Python完成特征匹配并缩小最后生成的特征匹配图
时间: 2023-10-09 11:13:09 浏览: 82
使用 Python 实现 SIFT 特征匹配并缩小最终生成的特征匹配图可以遵循以下步骤:
1. 导入必要的库
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
2. 读取图像
```python
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)
```
3. 初始化 SIFT 检测器
```python
sift = cv2.xfeatures2d.SIFT_create()
```
4. 检测关键点和描述符
```python
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
```
5. 匹配特征点
```python
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
```
6. 应用 Lowe's 比率测试,保留最佳匹配
```python
good = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good.append([m])
```
7. 绘制匹配图
```python
img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)
```
8. 缩小匹配图
```python
scale_percent = 50 # 缩小比例
width = int(img3.shape[1] * scale_percent / 100)
height = int(img3.shape[0] * scale_percent / 100)
dim = (width, height)
resized = cv2.resize(img3, dim, interpolation=cv2.INTER_AREA)
```
9. 显示并保存匹配图
```python
plt.imshow(resized), plt.show()
cv2.imwrite('match.jpg', resized)
```
阅读全文