拼接前
在这里插入图片描述

拼接后在这里插入图片描述


#include <fstream>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\stitching.hpp>
#include <iostream>


using namespace cv;
using namespace std;

vector<Mat> imgs; //保存拼接的原始图像向量

//导入所有原始拼接图像函数
void parseCmdArgs()
{
    for (int i = 1; i<17; i++)
    {
        string file = "";
        /*if (i < 10)
            file = "../img/0" + to_string(i) + ".png";
        else file = "../img/" + to_string(i) + ".png";*/

        file = "data/16/" + to_string(i) + ".jpg";
        cout << " read image '" << file << "'\n";
        Mat img = imread(file);
//        cv::resize(img, img, Size(1280, 640));
        if (img.empty())
        {
            cout << "Can't read image '" << file << "'\n";
        }
        imgs.push_back(img);
    }
}

int main()
{
    //导入拼接图像
    parseCmdArgs();

    Mat pano;
    Stitcher stitcher = Stitcher::createDefault(false);
    Stitcher::Status status = stitcher.stitch(imgs, pano);//拼接
     cout << "Stitcher";
    if (status != Stitcher::OK) //判断拼接是否成功
    {
        cout << "Can't stitch images, error code = " << int(status) << endl;
        return -1;
    }

    //cv::Mat pano = cv::imread("./quanjingtuxiang.png");
    imshow("全景拼接", pano);

    imwrite("./quanjingtuxiang.png", pano);

    cv::Mat mask;
    cv::cvtColor(pano, mask, CV_RGB2GRAY);
    int h = mask.rows;
    int w = mask.cols;
    Scalar value = Scalar(0);
    cv::copyMakeBorder(mask, mask, 10, 10, 10, 10, BORDER_CONSTANT, value);

    cv::threshold(mask, mask, 0, 255, THRESH_BINARY);

    std::vector<std::vector<cv::Point> > contours;
    cv::Mat temp;
    mask.copyTo(temp);
    cv::findContours(temp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    cv::Rect box = cv::boundingRect(contours[0]);
    int x = box.x;
    int y = box.y;
    int dh = box.height;//std::memcpy(image_feature_data.data, data, size_);
    int dw = box.width;

    cv::Mat RECT(h+20, w+20, CV_8UC1, cv::Scalar(0));
    RECT(box).setTo(255);


    cv::Mat minRect;
    RECT.copyTo(minRect);
    cv::Mat sub;
    mask.copyTo(sub);
    cv::Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
    while (cv::countNonZero(sub) > 0) {
        cv::erode(minRect, minRect, element);
        cv::subtract(minRect, mask, sub);
    }


    value = Scalar(0, 0, 0);
    cv::copyMakeBorder(pano, pano, 10, 10, 10, 10, BORDER_CONSTANT, value);
    cv::findContours(minRect, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    box = cv::boundingRect(contours[0]);

    cv::Mat Result;
    pano(box).copyTo(Result);
    imwrite("./final_16.png", Result);

    waitKey();
    return 0;
}

更多推荐