【Tadeas】图像拼接例子

cv2.xfeatures2d.SIFT_create(nfeatures=None, nOctaveLayers=None, contrastThreshold=None, edgeThreshold=None, sigma=None)-->descriptor

函数用于创建一个用于提取SIFT特征的描述符
* nfeatures,保留的最佳特性的数量。特征按其得分进行排序(以SIFT算法作为局部对比度进行测量);
* nOctavelLayers,高斯金字塔最小层级数,由图像自动计算出;
* constrastThreshold,对比度阈值用于过滤区域中的弱特征。阈值越大,检测器产生的特征越少;
* edgeThreshold ,用于过滤掉类似边缘特征的阈值。 请注意,其含义与contrastThreshold不同,即edgeThreshold越大,滤出的特征越少
* sigma,高斯输入层级, 如果图像分辨率较低,则可能需要减少数值
matcher = cv2.DescriptorMatcher_create("BruteForce")
# 使用KNN检测来自A、B图的SIFT特征匹配对,K=2
rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
参数:
* featureA和featureB 表示两个特征向量集;
* K 表示按knn匹配规则输出的最优的K个结果
在该算法中,输出的结果是:featureA(检测图像)中每个点与被匹配对象featureB(样本图像)中特征向量进行运算的匹配结果。
则,rawMatches中共有featureA条记录,每一条有最优K个匹配结果。
每个结果中包含三个非常重要的数据分别是queryIdx,trainIdx,distance

- queryIdx:特征向量的特征点描述符的下标(第几个特征点描述符),同时也是描述符对应特征点的下标
- trainIdx:样本特征向量的特征点描述符下标,同时也是描述符对应特征点的下标
- distance:代表匹配的特征点描述符的欧式距离,数值越小也就说明俩个特征点越相近
cv2.findHomography(srcPoints, dstPoints, method=None, ransacReprojThreshold=None, mask=None, maxIters=None, confidence=None) --> (H, status)
计算多个二维点对之间的最优单映射变换矩阵H(3*3),status为可选的输出掩码,0/1 表示在变换映射中无效/有效
* method(0, RANSAC, LMEDS, RHO)
* ransacReprojThreshold 最大允许冲投影错误阈值(限方法RANSAC和RHO)
* mask可选输出掩码矩阵,通常由鲁棒算法(RANSAC或LMEDS)设置,是不需要设置的
* maxIters为RANSAC算法的最大迭代次数,默认值为2000
* confidence可信度值,取值范围为0到1.

反向投影错误率计算方法参见 Ref 3
cv.warpPerspective(src, M, dsize, dst=None, flags=None, borderMode=None, borderValue=None) --> result
将图像按照变换映射M执行后返回变换后的图像result。
参数: 
* src – input image.
* dst – output image that has the size dsize and the same type as src .
* M – $ 3\cdot 3 $ transformation matrix.
* dsize – size of the output image.
* flags – combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation ( $\text{dst}\to \text{src}$ ).
* borderMode – pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE).
* borderValue – value used in case of a constant border; by default, it equals 0.
import numpy as np
import cv2


class Stitcher:
    #拼接函数
    def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
        #获取输入图片
        (imageB, imageA) = images
        #检测A、B图片的SIFT关键特征点,并计算特征描述子
        (kpsA, featuresA) = self.detectAndDescribe(imageA)
        (kpsB, featuresB) = self.detectAndDescribe(imageB)

        # 匹配两张图片的所有特征点,返回匹配结果
        M = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)

        # 如果返回结果为空,没有匹配成功的特征点,退出算法
        if M is None:
            return None

        # 否则,提取匹配结果
        # H是3x3视角变换矩阵
        (matches, H, status) = M
        # 将图片A进行视角变换,result是变换后图片
        result = cv2.warpPerspective(imageA, H, (imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
        # 将图片B传入result图片最左端
        result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB

        # 检测是否需要显示图片匹配
        if showMatches:
            # 生成匹配图片
            vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches, status)
            # 返回结果
            return (result, vis)

        # 返回匹配结果
        return result

    def detectAndDescribe(self, image):
        # 将彩色图片转换成灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 建立SIFT生成器
        descriptor = cv2.xfeatures2d.SIFT_create()
        # 检测SIFT特征点,并计算描述子
        (kps, features) = descriptor.detectAndCompute(image, None)

        # 将结果转换成NumPy数组
        kps = np.float32([kp.pt for kp in kps])

        # 返回特征点集,及对应的描述特征
        return (kps, features)

    def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh):
        # 建立暴力匹配器
        matcher = cv2.DescriptorMatcher_create("BruteForce")

        # 使用KNN检测来自A、B图的SIFT特征匹配对,K=2
        rawMatches = matcher.knnMatch(featuresA, featuresB, 2)

        matches = []
        for m in rawMatches:
            # 当最近距离跟次近距离的比值小于ratio值时,保留此匹配对
            if len(m) == 2 and m[0].distance < m[1].distance * ratio:
            # 存储两个点在featuresA, featuresB中的索引值
                matches.append((m[0].trainIdx, m[0].queryIdx))

        # 当筛选后的匹配对大于4时,计算视角变换矩阵
        if len(matches) > 4:
            # 获取匹配对的点坐标
            ptsA = np.float32([kpsA[i] for (_, i) in matches])
            ptsB = np.float32([kpsB[i] for (i, _) in matches])

            # 计算视角变换矩阵
            (H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, reprojThresh)

            # 返回结果
            return (matches, H, status)

        # 如果匹配对小于4时,返回None
        return None

    def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
        # 初始化可视化图片,将A、B图左右连接到一起
        (hA, wA) = imageA.shape[:2]
        (hB, wB) = imageB.shape[:2]
        vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
        vis[0:hA, 0:wA] = imageA
        vis[0:hB, wA:] = imageB

        # 联合遍历,画出匹配对
        for ((trainIdx, queryIdx), s) in zip(matches, status):
            # 当点对匹配成功时,画到可视化图上
            if s == 1:
                # 画出匹配对
                ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
                ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
                cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

        # 返回可视化结果
        return vis
from Stitcher import Stitcher
import cv2

# 读取拼接图片
imageA = cv2.imread("image/left_01.png")
imageB = cv2.imread("image/right_01.png")

# 把图片拼接成全景图
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)

# 显示所有图片
cv2.imshow("Image A", imageA)
cv2.imshow("Image B", imageB)
cv2.imshow("Keypoint Matches", vis)
cv2.imshow("Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Reference:

猜你喜欢

转载自www.cnblogs.com/tadeas/p/11488730.html