python opencv 图像sift配准拼接
时间: 2023-09-12 18:10:34 浏览: 240
1. 导入库
```
import cv2
import numpy as np
```
2. 读取图片
```
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
```
3. 提取关键点和特征向量
```
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
```
4. 匹配特征点
```
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)
```
5. 筛选匹配点
```
good = []
for m,n in matches:
if m.distance < 0.75*n.distance:
good.append(m)
```
6. 计算变换矩阵
```
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
```
7. 图像拼接
```
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,M)
dst = np.int32(dst)
offset = np.array([w,0])
dst += offset
result_img = cv2.polylines(img2,[dst],True,(255,0,0),3, cv2.LINE_AA)
result_img[offset[1]:h+offset[1],:w,:] = img1
```
完整代码:
```
import cv2
import numpy as np
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)
good = []
for m,n in matches:
if m.distance < 0.75*n.distance:
good.append(m)
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
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,M)
dst = np.int32(dst)
offset = np.array([w,0])
dst += offset
result_img = cv2.polylines(img2,[dst],True,(255,0,0),3, cv2.LINE_AA)
result_img[offset[1]:h+offset[1],:w,:] = img1
cv2.imshow("Result", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文