欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OpenCV全景图像拼接的实现示例

程序员文章站 2022-03-26 15:45:06
本文主要介绍了opencv全景图像拼接的实现示例,分享给大家,具体如下:left_01.jpgright_01.jpgstitcher.pyimport numpy as npimport cv2 c...

本文主要介绍了opencv全景图像拼接的实现示例,分享给大家,具体如下:

left_01.jpg

OpenCV全景图像拼接的实现示例

right_01.jpg

OpenCV全景图像拼接的实现示例

stitcher.py

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]))
        self.cv_show('result', result)
        # 将图片b传入result图片最左端
        result[0:imageb.shape[0], 0:imageb.shape[1]] = imageb
        self.cv_show('result', result)
        # 检测是否需要显示图片匹配
        if showmatches:
            # 生成匹配图片
            vis = self.drawmatches(imagea, imageb, kpsa, kpsb, matches, status)
            # 返回结果
            return (result, vis)
 
        # 返回匹配结果
        return result
    def cv_show(self,name,img):
        cv2.imshow(name, img)
        cv2.waitkey(0)
        cv2.destroyallwindows()
 
    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.bfmatcher()
  
        # 使用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

imagestiching.py

from stitcher import stitcher
import cv2
 
# 读取拼接图片
imagea = cv2.imread("left_01.jpg")
imageb = cv2.imread("right_01.jpg")
 
# 把图片拼接成全景图
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()

运行结果:

OpenCV全景图像拼接的实现示例

OpenCV全景图像拼接的实现示例

如遇以下错误:

cv2.error: opencv(3.4.3) c:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:the function/feature is not implemented) this algorithm is patented and is excluded in this configuration; set opencv_enable_nonfree cmake option and rebuild the library in function ‘cv::xfeatures2d::sift::create'

如果运行opencv程序提示算法版权问题可以通过安装低版本的opencv-contrib-python解决:

pip install --user opencv-contrib-python==3.3.0.10

到此这篇关于opencv全景图像拼接的实现示例的文章就介绍到这了,更多相关opencv 图像拼接内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: OpenCV 图像拼接