单应性变换之图像拼接

图像拼接技术就是将数张有重叠部分的图像(可能是不同时间、不同视角或者不同传感器获得的)拼成一幅无缝的全景图或高分辨率图像的技术。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# coding = utf-8
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from mahotas.features import surf

# 导入资源
image = cv.imread('1.png')
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)

image2 = cv.imread('2.png')
image2 = cv.cvtColor(image2, cv.COLOR_BGR2RGB)
gray2 = cv.cvtColor(image2, cv.COLOR_RGB2GRAY)

# 检测角点
orb = cv.ORB_create(200, 2.0)
keypoints1, desc1 = orb.detectAndCompute(gray, None)
keypoints2, desc2 = orb.detectAndCompute(gray2, None)

# 角点配对
bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck = True)
matches = bf.match(desc1, desc2)
# 按照相近程度进行排序
matches = sorted(matches, key = lambda x : x.distance)
goodmatches = matches[:int(len(matches)/2)]

# 图像拼接
MIN_MATCH_COUNT = 10
if len(goodmatches) > MIN_MATCH_COUNT:
src_pts = np.float32([keypoints1[m.queryIdx].pt for m in goodmatches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in goodmatches]).reshape(-1, 1, 2)
H, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 5.0)

warpImg = cv.warpPerspective(image, H, (image.shape[1] + image2.shape[1], image.shape[0]))
warpImg[0:image2.shape[0], 0:image2.shape[1]] = image2

plt.imshow(warpImg)
plt.show()

1.png

2.png

拼接结果

绘制匹配点

0%