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

作者:乐亦亦乐 时间:2021-12-04 00:36:09 

本文主要介绍了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

来源:https://blog.csdn.net/qq_41251963/article/details/103855359

标签:OpenCV,图像拼接
0
投稿

猜你喜欢

  • 通过底层源码理解YOLOv5的Backbone

    2023-07-15 20:37:01
  • 极致之美——百行代码实现全新智能语言Lisp

    2010-07-13 13:07:00
  • Python pandas DataFrame操作的实现代码

    2021-07-24 00:49:43
  • python爬取代理ip的示例

    2022-01-20 11:41:12
  • SQL 特殊语句(学习笔记)

    2012-06-06 19:51:33
  • Django模板过滤器和继承示例详解

    2023-10-25 16:52:56
  • 浅谈python中scipy.misc.logsumexp函数的运用场景

    2023-11-10 17:10:56
  • Python计算点到直线距离、直线间交点夹角

    2022-09-05 10:27:04
  • 三种不同方式连接MySQL数据库的方法及示例

    2010-06-11 13:37:00
  • 最新google pr查询接口

    2012-03-12 20:00:39
  • python画柱状图--不同颜色并显示数值的方法

    2021-12-31 17:22:18
  • Python 连连看连接算法

    2023-10-28 09:12:35
  • 教你怎么用Python生成九宫格照片

    2023-12-02 17:20:51
  • Django框架表单操作实例分析

    2022-01-27 23:43:59
  • 基于Python的身份证号码自动生成程序

    2022-11-29 02:00:33
  • 用Python实现一个简单的能够发送带附件的邮件程序的教程

    2023-04-08 11:45:48
  • MYSQL教程:查询优化之调度和锁定

    2009-02-27 15:58:00
  • 基于fastapi框架的异步解读

    2022-12-19 21:45:24
  • 深入认识javascript中的eval函数

    2008-08-03 16:44:00
  • Pytorch之Variable的用法

    2022-01-19 04:16:39
  • asp之家 网络编程 m.aspxhome.com