您好,
会员登录 快速注册
退出 ( 条未读消息)
关于本站 意见反馈 首页

公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!
全部文章分类
  • 人工智能 >

  • 编程语言 >

  • WPF系列 >

  • ASP.NET系列 >

  • Linux >

  • 数据库 >

  • 嵌入式 >

  • WEB技术 >

  • PLC系列 >

  • 微服务与框架 >

  • 小宅DIY >

  • 学习资料 >

OpenCv基础 ANN车牌识别 yolov5车牌识别 指针式仪表识别 ROS系列 YOLO Halcon Detectron2 昇腾AI ChatGPT在线体验 英伟达JETSON ChatGLM ChatTTS FunASR 地平线 ByteTrack 魔搭社区 LangChain
C C# C++ Python Java Go
WPF
ASP.NET小功能 GPS定位系统-MVC GPS定位系统-VUE ASP.NET WebRTC
Linux Linux内核 Shell MakeFile
MySql SqlServer Oracle
STM8 STM32 51单片机
VUE入门 HTML JavaScript CSS layui镜像网站 ElementUi中文官网 element-plus 图标
三菱 欧姆龙 西门子 施耐德 松下 台达
IOTSharp IOTGateway ABP FRAMEWORK Docker
亚克力音响 编程仙途:智驭万法
面试题与技巧 Python入门技能树 微软C#教程
首页 编程之美 工具下载 全国就业 流量地图 文心一言
OpenCv基础
内容介绍与资料分享 C# OpenCv环境搭建 C++ OpenCv环境搭建 Python OpenCv环境搭建 Java OpenCv环境搭建 OpenCv组件结构解析 OpenCv命名规范 OpenCv基本专业术语与方法 OpenCV 常用函数与构造体详细说明 创建画布 打开一张图片 利用imwrite生成透明png图像 图像打开、混合显示和输出 图像腐蚀 blur图像模糊(均值滤波) sobel边缘检测 canny边缘检测 Scharr滤波器 程序性能检测及优化 视频播放 摄像头录像与播放 双摄像头操作与图像相似度检测 颜色空间转换与物体追踪 彩色目标追踪 光流法运动目标检测 OpenCV中的稠密光流 背景减除 点追踪 人脸识别 支持向量机之SVM引导 支持向量机之处理线性不可分数据 ROI矩形截取 鼠标绘制矩形 用OpenCV进行基本绘图 绘图函数(python中文显示) 把鼠标当画笔 用滑动条做调色板 图像的基础操作 图像上的算术运算 多通道图像混合 图像的亮度、对比度调整 XML和YAML文件的写入 XML和YAML文件的读取 卷积操作 三种线性滤波 两种非线性滤波 7种图像处理形态学(1) 7种图像处理形态学(2) 漫水填充 图像缩放与图像金字塔 二值化基本阈值操作 图像阈值 Laplacian图像变换(拉普拉斯算子) 霍夫变换HoughLines边缘检测与线性矢量 霍夫变换HoughLinesP边缘检测与线性矢量 霍夫变换HoughCircles边缘检测与线性矢量 LSD快速直线检测 几何变换 remap重映射 remap实现多种重映射 仿射变换综合示例 直方图均衡化 CLAHE有限对比适应性直方图均衡化 draw最大的轮廓 轮廓的性质 点到多边形的最短距离 形状匹配 椭圆拟合与直线拟合 基础轮廓查找 查找并绘制轮廓综合示例 凸缺陷/凸包检测 凸包检测 创建包围轮廓的矩形边界 创建包围轮廓的圆形边 创建包围轮廓的矩形和圆形边界框 查找和绘制图片轮廓矩 分水岭算法 图像修补 H-S二维直方图的绘制/2D直方图 一维直方图的绘制 RGB三色直方图的绘制 直方图对比 使用掩膜绘制直方图 直方图反向投影 模板匹配 多对象模板匹配 cornerHarris角点检测 cornerHarris角点检测综合示例 Shi-Tomasi角点检测 亚像素级角点检测 角点检测的FAST算法(FAST特征检测器) 颜色识别 warpPerspective透视变换 SURF/SIFT特征点检测 SURF/SIFT特征描述 使用FLANN进行特征点匹配 FLANN结合SURF/SIFT进行关键点的描述和匹配 寻找已知物体(一) 寻找已知物体(二) 目标查找与跟踪 - Meanshift与CamShift BRIEF描述符 ORB ORB算法描述与匹配 LUT 图像灰度调整 离散傅里叶变换 双目摄像头与图像拼接 环境亮度检测 stitching 全景拼接 Maze-Solver迷宫解密 使用Haar分类器之面部检测 使用Haar分类器之行人检测 OpenCv Haar/LBP/HOG分类器-人脸识别 斑点检测 使用GrabCut算法进行交互式前景提取 对极几何 摄像机标定 姿势估计 立体图像中的深度地图 OpenCv中的KNN KNN手写数字识别 ​SVM手写数字识别(使用SVM进行手写数据OCR) 英文字母的OCR 预测手写数字(预测不准) K值聚类(一) K值聚类(二) 计算摄影学-图像去噪 高动态范围成像(HDRI或HDR) MSER区域检测 二维码、条形码识别 删除图像中的水印 OpenCv深度学习dnn Kinect-深度相机 OpenCv常用数学算法 360度旋转直线绘制 向量延长线上的像素扫描 Tools工具包-窗体分配
环境亮度检测
Maze-Solver迷宫解密
激萌の小宅 小宅博客网 OpenCv基础

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

stitching 全景拼接

本章节内容是博主网上收集的。当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


参考博客《OpenCV-Python 图像全景拼接stitch及黑边处理》

运行前,需要准备三张图片:

1.jpg

2.jpg

3.jpg


没去掉黑边的拼接效果如下:

result2.jpg


去掉黑边的拼接效果如下:

result1.jpg


C#版本代码如下:

using OpenCvSharp;
using System.Collections.Generic;
using System;

namespace demo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //stitch1();
            stitch2();
            Cv2.WaitKey(0);
        }

        /// <summary>
        /// 全景拼接,去掉黑边
        /// </summary>
        private static void stitch1()
        {
            List<Mat> imgs = new List<Mat>();
            Mat img1 = Cv2.ImRead("../../../images/stitching1.jpg");
            Mat img2 = Cv2.ImRead("../../../images/stitching2.jpg");
            Mat img3 = Cv2.ImRead("../../../images/stitching3.jpg");
            imgs.Add(img1);
            imgs.Add(img2);
            imgs.Add(img3);
            Mat pano = new Mat();
            Stitcher stitcher = Stitcher.Create();
            Stitcher.Status status = stitcher.Stitch(imgs, pano);
            if (status != Stitcher.Status.OK)
            {
                Console.WriteLine($"Can't stitch images, error code = {status}");
                Console.Read();
                return;
            }

            // 全景图轮廓提取
            Mat stitched = new Mat();
            Mat gray = new Mat();
            Mat thresh = new Mat();
            Cv2.CopyMakeBorder(pano, stitched, 10, 10, 10, 10, BorderTypes.Constant, new Scalar(0, 0, 0));
            Cv2.CvtColor(stitched, gray, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(gray, thresh, 0, 255, ThresholdTypes.Binary);

            //定义轮廓和层次结构
            Point[][] cnts = new Point[][] { };
            HierarchyIndex[] hierarchy;
            Cv2.FindContours(thresh, out cnts, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple, null);

            // 创建单通道黑色图像, 轮廓最小正矩形
            Mat mask = new Mat(thresh.Size(), MatType.CV_8U, new Scalar(0, 0, 0));

            // 取出list中的轮廓二值图
            Rect boundRect = Cv2.BoundingRect(cnts[0]);

            //绘制矩形
            Cv2.Rectangle(mask, boundRect.TopLeft, boundRect.BottomRight, new Scalar(255, 255, 255), -1);

            // 腐蚀处理,直到minRect的像素值都为0
            Mat minRect = new Mat();
            Mat sub = new Mat();

            mask.CopyTo(minRect);
            mask.CopyTo(sub);
            while (Cv2.CountNonZero(sub) > 0)
            {
                // 行腐蚀操作 
                Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 5));
                Cv2.Erode(minRect, minRect, element);
                Cv2.Subtract(minRect, thresh, sub);
            }

            // 提取minRect轮廓并裁剪
            Cv2.FindContours(minRect, out cnts, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point(0, 0));
            boundRect = Cv2.BoundingRect(cnts[0]);
            stitched = new Mat(stitched, boundRect);

            Cv2.ImShow("result1", stitched);
        }

        /// <summary>
        /// 全景拼接,没去黑边
        /// </summary>
        private static void stitch2()
        {
            List<Mat> imgs = new List<Mat>();
            Mat img1 = Cv2.ImRead("../../../images/stitching1.jpg");
            Mat img2 = Cv2.ImRead("../../../images/stitching2.jpg");
            Mat img3 = Cv2.ImRead("../../../images/stitching3.jpg");
            imgs.Add(img1);
            imgs.Add(img2);
            imgs.Add(img3);
            Mat pano = new Mat();
            Stitcher stitcher = Stitcher.Create();
            Stitcher.Status status = stitcher.Stitch(imgs, pano);
            if (status != Stitcher.Status.OK)
            {
                Console.WriteLine($"Can't stitch images, error code = {status}");
                Console.Read();
                return;
            }
            Cv2.ImShow("result2", pano);
        }
    }
}


C++版本代码如下:

#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching.hpp"
#include<Windows.h>

using namespace std;
using namespace cv;

/// <summary>
/// 全景拼接,去掉黑边
/// </summary>
void stitch1()
{
    vector<Mat> imgs;
    Mat img1 = imread("../images/stitching1.jpg");
    Mat img2 = imread("../images/stitching2.jpg");
    Mat img3 = imread("../images/stitching3.jpg");
    imgs.push_back(img1);
    imgs.push_back(img2);
    imgs.push_back(img3);
    Mat pano;
    Ptr<Stitcher> stitcher = Stitcher::create();
    Stitcher::Status status = stitcher->stitch(imgs, pano);
    if (status != Stitcher::OK)
    {
        cout << "Can't stitch images, error code = " << status << endl;
        return;
    }

    // 全景图轮廓提取
    Mat stitched, gray, thresh;
    copyMakeBorder(pano, stitched, 10, 10, 10, 10, BORDER_CONSTANT, (0, 0, 0));
    cvtColor(stitched, gray, COLOR_BGR2GRAY);

    threshold(gray, thresh, 0, 255, THRESH_BINARY);

    //定义轮廓和层次结构
    vector<vector<Point>> cnts;
    vector<Vec4i> hierarchy;
    findContours(thresh, cnts, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    // 创建单通道黑色图像, 轮廓最小正矩形
    Mat mask(thresh.rows, thresh.cols, CV_8U);
    mask = Scalar::all(0);

    // 取出list中的轮廓二值图
    Rect boundRect = boundingRect(Mat(cnts[0]));

    //绘制矩形
    rectangle(mask, boundRect.tl(), boundRect.br(), Scalar(255, 255, 255), -1, 8, 0);

    // 腐蚀处理,直到minRect的像素值都为0
    Mat minRect, sub;
    mask.copyTo(minRect);
    mask.copyTo(sub);
    while (countNonZero(sub) > 0) {
        // 行腐蚀操作 
        Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
        erode(minRect, minRect, element);
        subtract(minRect, thresh, sub);
    }

    // 提取minRect轮廓并裁剪
    findContours(minRect, cnts, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
    boundRect = boundingRect(cnts[0]);
    // 裁剪
    stitched = stitched(boundRect);
    imshow("result1", stitched);
    imwrite("result1.jpg", stitched);
}

/// <summary>
/// 全景拼接,没去黑边
/// </summary>
void stitch2()
{
    vector<Mat> imgs;
    Mat img1 = imread("../images/stitching1.jpg");
    Mat img2 = imread("../images/stitching2.jpg");
    Mat img3 = imread("../images/stitching3.jpg");
    imgs.push_back(img1);
    imgs.push_back(img2);
    imgs.push_back(img3);
    Mat pano;
    Ptr<Stitcher> stitcher = Stitcher::create();
    Stitcher::Status status = stitcher->stitch(imgs, pano);
    if (status != Stitcher::OK)
    {
        cout << "Can't stitch images, error code = " << status << endl;
        return;
    }
    imshow("result2", pano);
    imwrite("result2.jpg", pano);
}

int main()
{
    stitch1();
    stitch2();
    waitKey();
    destroyAllWindows();
    return 0;
}


Python版本代码如下:

import cv2
import numpy as np


# 全景拼接,去掉黑边
def stitch1(image):
    # 图像拼接
    # stitcher = cv2.createStitcher(False)  # OpenCV 3.X.X.X使用该方法
    stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)  # OpenCV 4.X.X.X使用该方法,cv2.Stitcher_create()也可以
    status, pano = stitcher.stitch(image)

    # 黑边处理
    if status == cv2.Stitcher_OK:
        # 全景图轮廓提取
        stitched = cv2.copyMakeBorder(pano, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0, 0, 0))
        gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY)
        thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
        cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

        # 轮廓最小正矩形
        mask = np.zeros(thresh.shape, dtype="uint8")
        (x, y, w, h) = cv2.boundingRect(cnts[0])  # 取出list中的轮廓二值图,类型为numpy.ndarray
        cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)

        # 腐蚀处理,直到minRect的像素值都为0
        minRect = mask.copy()
        sub = mask.copy()
        while cv2.countNonZero(sub) > 0:
            minRect = cv2.erode(minRect, None)
            sub = cv2.subtract(minRect, thresh)

        # 提取minRect轮廓并裁剪
        cnts = cv2.findContours(minRect, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
        (x, y, w, h) = cv2.boundingRect(cnts[0])
        stitched = stitched[y:y + h, x:x + w]

        cv2.imshow('stitched1', stitched)
    else:
        print('图像匹配的特征点不足')


# 全景拼接,没去黑边
def stitch2(image):
    # 图像拼接
    # stitcher = cv2.createStitcher(False)  # OpenCV 3.X.X.X使用该方法
    stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)  # OpenCV 4.X.X.X使用该方法,cv2.Stitcher_create()也可以
    status, pano = stitcher.stitch(image)

    if status == cv2.Stitcher_OK:
        cv2.imshow('stitched2', pano)
    else:
        print('图像匹配的特征点不足')


if __name__ == "__main__":
    image1 = cv2.imread('ng1.jpg')
    image2 = cv2.imread('ng2.jpg')
    image3 = cv2.imread('ng3.jpg')
    image = image1, image2, image3
    stitch1(image)
    # stitch2(image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


环境亮度检测
Maze-Solver迷宫解密

友情链接: CSDN激萌の小宅 95知识库 自考题库 罗分明个人网络博客 精益编程leanboot

小宅博客  www.bilibili996.com All Rights Reserved. 备案号: 闽ICP备2024034575号

网站经营许可证  福建省福州市 Copyright©2021-2025 版权所有

小宅博客
首页 智能家居 地图定位
公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

stitching 全景拼接

本章节内容是博主网上收集的。当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


参考博客《OpenCV-Python 图像全景拼接stitch及黑边处理》

运行前,需要准备三张图片:

1.jpg

2.jpg

3.jpg


没去掉黑边的拼接效果如下:

result2.jpg


去掉黑边的拼接效果如下:

result1.jpg


C#版本代码如下:

using OpenCvSharp;
using System.Collections.Generic;
using System;

namespace demo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //stitch1();
            stitch2();
            Cv2.WaitKey(0);
        }

        /// <summary>
        /// 全景拼接,去掉黑边
        /// </summary>
        private static void stitch1()
        {
            List<Mat> imgs = new List<Mat>();
            Mat img1 = Cv2.ImRead("../../../images/stitching1.jpg");
            Mat img2 = Cv2.ImRead("../../../images/stitching2.jpg");
            Mat img3 = Cv2.ImRead("../../../images/stitching3.jpg");
            imgs.Add(img1);
            imgs.Add(img2);
            imgs.Add(img3);
            Mat pano = new Mat();
            Stitcher stitcher = Stitcher.Create();
            Stitcher.Status status = stitcher.Stitch(imgs, pano);
            if (status != Stitcher.Status.OK)
            {
                Console.WriteLine($"Can't stitch images, error code = {status}");
                Console.Read();
                return;
            }

            // 全景图轮廓提取
            Mat stitched = new Mat();
            Mat gray = new Mat();
            Mat thresh = new Mat();
            Cv2.CopyMakeBorder(pano, stitched, 10, 10, 10, 10, BorderTypes.Constant, new Scalar(0, 0, 0));
            Cv2.CvtColor(stitched, gray, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(gray, thresh, 0, 255, ThresholdTypes.Binary);

            //定义轮廓和层次结构
            Point[][] cnts = new Point[][] { };
            HierarchyIndex[] hierarchy;
            Cv2.FindContours(thresh, out cnts, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple, null);

            // 创建单通道黑色图像, 轮廓最小正矩形
            Mat mask = new Mat(thresh.Size(), MatType.CV_8U, new Scalar(0, 0, 0));

            // 取出list中的轮廓二值图
            Rect boundRect = Cv2.BoundingRect(cnts[0]);

            //绘制矩形
            Cv2.Rectangle(mask, boundRect.TopLeft, boundRect.BottomRight, new Scalar(255, 255, 255), -1);

            // 腐蚀处理,直到minRect的像素值都为0
            Mat minRect = new Mat();
            Mat sub = new Mat();

            mask.CopyTo(minRect);
            mask.CopyTo(sub);
            while (Cv2.CountNonZero(sub) > 0)
            {
                // 行腐蚀操作 
                Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 5));
                Cv2.Erode(minRect, minRect, element);
                Cv2.Subtract(minRect, thresh, sub);
            }

            // 提取minRect轮廓并裁剪
            Cv2.FindContours(minRect, out cnts, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point(0, 0));
            boundRect = Cv2.BoundingRect(cnts[0]);
            stitched = new Mat(stitched, boundRect);

            Cv2.ImShow("result1", stitched);
        }

        /// <summary>
        /// 全景拼接,没去黑边
        /// </summary>
        private static void stitch2()
        {
            List<Mat> imgs = new List<Mat>();
            Mat img1 = Cv2.ImRead("../../../images/stitching1.jpg");
            Mat img2 = Cv2.ImRead("../../../images/stitching2.jpg");
            Mat img3 = Cv2.ImRead("../../../images/stitching3.jpg");
            imgs.Add(img1);
            imgs.Add(img2);
            imgs.Add(img3);
            Mat pano = new Mat();
            Stitcher stitcher = Stitcher.Create();
            Stitcher.Status status = stitcher.Stitch(imgs, pano);
            if (status != Stitcher.Status.OK)
            {
                Console.WriteLine($"Can't stitch images, error code = {status}");
                Console.Read();
                return;
            }
            Cv2.ImShow("result2", pano);
        }
    }
}


C++版本代码如下:

#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching.hpp"
#include<Windows.h>

using namespace std;
using namespace cv;

/// <summary>
/// 全景拼接,去掉黑边
/// </summary>
void stitch1()
{
    vector<Mat> imgs;
    Mat img1 = imread("../images/stitching1.jpg");
    Mat img2 = imread("../images/stitching2.jpg");
    Mat img3 = imread("../images/stitching3.jpg");
    imgs.push_back(img1);
    imgs.push_back(img2);
    imgs.push_back(img3);
    Mat pano;
    Ptr<Stitcher> stitcher = Stitcher::create();
    Stitcher::Status status = stitcher->stitch(imgs, pano);
    if (status != Stitcher::OK)
    {
        cout << "Can't stitch images, error code = " << status << endl;
        return;
    }

    // 全景图轮廓提取
    Mat stitched, gray, thresh;
    copyMakeBorder(pano, stitched, 10, 10, 10, 10, BORDER_CONSTANT, (0, 0, 0));
    cvtColor(stitched, gray, COLOR_BGR2GRAY);

    threshold(gray, thresh, 0, 255, THRESH_BINARY);

    //定义轮廓和层次结构
    vector<vector<Point>> cnts;
    vector<Vec4i> hierarchy;
    findContours(thresh, cnts, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    // 创建单通道黑色图像, 轮廓最小正矩形
    Mat mask(thresh.rows, thresh.cols, CV_8U);
    mask = Scalar::all(0);

    // 取出list中的轮廓二值图
    Rect boundRect = boundingRect(Mat(cnts[0]));

    //绘制矩形
    rectangle(mask, boundRect.tl(), boundRect.br(), Scalar(255, 255, 255), -1, 8, 0);

    // 腐蚀处理,直到minRect的像素值都为0
    Mat minRect, sub;
    mask.copyTo(minRect);
    mask.copyTo(sub);
    while (countNonZero(sub) > 0) {
        // 行腐蚀操作 
        Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
        erode(minRect, minRect, element);
        subtract(minRect, thresh, sub);
    }

    // 提取minRect轮廓并裁剪
    findContours(minRect, cnts, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
    boundRect = boundingRect(cnts[0]);
    // 裁剪
    stitched = stitched(boundRect);
    imshow("result1", stitched);
    imwrite("result1.jpg", stitched);
}

/// <summary>
/// 全景拼接,没去黑边
/// </summary>
void stitch2()
{
    vector<Mat> imgs;
    Mat img1 = imread("../images/stitching1.jpg");
    Mat img2 = imread("../images/stitching2.jpg");
    Mat img3 = imread("../images/stitching3.jpg");
    imgs.push_back(img1);
    imgs.push_back(img2);
    imgs.push_back(img3);
    Mat pano;
    Ptr<Stitcher> stitcher = Stitcher::create();
    Stitcher::Status status = stitcher->stitch(imgs, pano);
    if (status != Stitcher::OK)
    {
        cout << "Can't stitch images, error code = " << status << endl;
        return;
    }
    imshow("result2", pano);
    imwrite("result2.jpg", pano);
}

int main()
{
    stitch1();
    stitch2();
    waitKey();
    destroyAllWindows();
    return 0;
}


Python版本代码如下:

import cv2
import numpy as np


# 全景拼接,去掉黑边
def stitch1(image):
    # 图像拼接
    # stitcher = cv2.createStitcher(False)  # OpenCV 3.X.X.X使用该方法
    stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)  # OpenCV 4.X.X.X使用该方法,cv2.Stitcher_create()也可以
    status, pano = stitcher.stitch(image)

    # 黑边处理
    if status == cv2.Stitcher_OK:
        # 全景图轮廓提取
        stitched = cv2.copyMakeBorder(pano, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0, 0, 0))
        gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY)
        thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
        cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

        # 轮廓最小正矩形
        mask = np.zeros(thresh.shape, dtype="uint8")
        (x, y, w, h) = cv2.boundingRect(cnts[0])  # 取出list中的轮廓二值图,类型为numpy.ndarray
        cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)

        # 腐蚀处理,直到minRect的像素值都为0
        minRect = mask.copy()
        sub = mask.copy()
        while cv2.countNonZero(sub) > 0:
            minRect = cv2.erode(minRect, None)
            sub = cv2.subtract(minRect, thresh)

        # 提取minRect轮廓并裁剪
        cnts = cv2.findContours(minRect, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
        (x, y, w, h) = cv2.boundingRect(cnts[0])
        stitched = stitched[y:y + h, x:x + w]

        cv2.imshow('stitched1', stitched)
    else:
        print('图像匹配的特征点不足')


# 全景拼接,没去黑边
def stitch2(image):
    # 图像拼接
    # stitcher = cv2.createStitcher(False)  # OpenCV 3.X.X.X使用该方法
    stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)  # OpenCV 4.X.X.X使用该方法,cv2.Stitcher_create()也可以
    status, pano = stitcher.stitch(image)

    if status == cv2.Stitcher_OK:
        cv2.imshow('stitched2', pano)
    else:
        print('图像匹配的特征点不足')


if __name__ == "__main__":
    image1 = cv2.imread('ng1.jpg')
    image2 = cv2.imread('ng2.jpg')
    image3 = cv2.imread('ng3.jpg')
    image = image1, image2, image3
    stitch1(image)
    # stitch2(image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()