对Opencv 的stitching 的使用串联匹配

前面已经对串联匹配有了一定的了解,现在用它来改进 Opencv 的stitching ,

先找来三个博文为模板,分别是:

1。《任意n张图像拼接_效果很好_计算机视觉大作业1终版》

2。《 Opencv2.4.9源码分析——Stitching(八)》

3。《图像拼接(十):OPenCV stitching和stitching_detailed》中的“stitching_detailed使用示例”

把他们中的一些Mat 转化为opencv 3.0 用到的 UMat 。

为什么不直接用3.0的示例呢?主要是示例不太友好方便,修改地方太多,自己的e文也太差。

通过测试:

1文只有一种长宽比,改变长宽比就出错。

2文速度较慢,注解不错。

3文没有中文注解,但速度较快,所以就以3文为模板修改匹配。


针对3.0修改后为:

//stitching_detailed使用 3.0
//用串联匹配代替原匹配

//
#define ENABLE_LOG 1

#include 
#include 
#include 
#include "opencv2/opencv_modules.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/detail/autocalib.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"

using namespace std;
using namespace cv;
using namespace cv::detail;


//

// 默认命令行参数
vector img_names;
bool preview = false;
bool try_gpu = true;
double work_megapix = 0.6;
double seam_megapix = 0.1;
double compose_megapix = -1;
float conf_thresh = 1.f;
string features_type = "orb";//"surf";
string ba_cost_func = "reproj";//重映射误差方法   "ray";//射线发散误差方法  
string ba_refine_mask = "xxxxx";
bool do_wave_correct = true;
WaveCorrectKind wave_correct = detail::WAVE_CORRECT_HORIZ;// 波形校验,水平 // 波校正垂直 WAVE_CORRECT_VERT
bool save_graph = false;//是否保存匹配图
std::string save_graph_to;
string warp_type = "spherical";//球面投影
int expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
float match_conf = 0.3f;
string seam_find_type = "gc_color";
int blend_type = Blender::MULTI_BAND;
float blend_strength = 5;
string result_name = "result.jpg";

void LoadImageNamesFromFile(char* name,vector& image_names);//从列表中载入图像名
void i_matcher(vector &features, vector &pairwise_matches);

int main(int argc, char* argv[])
{
    //读入图像
    double ttt = getTickCount();

    cout<<"读出文件名..."<(img_names.size());
	cout<<"有 "< finder;
    if (features_type == "surf")
    {
#if defined(HAVE_OPENCV_NONFREE) && defined(HAVE_OPENCV_GPU)
        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
            finder = new SurfFeaturesFinderGpu();
        else
#endif
            finder = new SurfFeaturesFinder();
    }
    else if (features_type == "orb")
    {
        finder = new OrbFeaturesFinder();
    }
    else
    {
        cout << "Unknown 2D features type: '" << features_type << "'.\n";
        return -1;
    }

    Mat full_img, img;
    vector features(num_images);
    vector images(num_images);
    vector full_img_sizes(num_images);
    double seam_work_aspect = 1;



    for (int i = 0; i < num_images; ++i)
    {
        full_img = imread(img_names[i]);
        full_img_sizes[i] = full_img.size();

        if (full_img.empty())
        {
            LOGLN("Can't open image " << img_names[i]);
            return -1;
        }
        if (work_megapix < 0)
        {
            img = full_img;
            work_scale = 1;
            is_work_scale_set = true;
        }
        else
        {
            if (!is_work_scale_set)
            {
                work_scale = min(1.0, sqrt(work_megapix * 1e6 / full_img.size().area()));
                is_work_scale_set = true;
            }
            resize(full_img, img, Size(), work_scale, work_scale);
        }
        if (!is_seam_scale_set)
        {
            seam_scale = min(1.0, sqrt(seam_megapix * 1e6 / full_img.size().area()));
            seam_work_aspect = seam_scale / work_scale;
            is_seam_scale_set = true;
        }

        (*finder)(img, features[i]);
        features[i].img_idx = i;
        //LOGLN("Features in image #" << i+1 << ": " << features[i].keypoints.size());
        cout<<"图像 #" << i+1 << "特征数: " << features[i].keypoints.size()<collectGarbage();
    full_img.release();
    img.release();

    //LOGLN("Finding features, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
	cout<<"寻找特征用时:"<< ((getTickCount() - t) / getTickFrequency()) << " 秒"< pairwise_matches;
    BestOf2NearestMatcher matcher(try_gpu, match_conf);

    //matcher(features, pairwise_matches);
    //matcher.collectGarbage();
	//这里用我们自己的匹配代替
	i_matcher(features, pairwise_matches);

	//LOGLN("Pairwise matching, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
	cout<<"成对匹配用时:"<< ((getTickCount() - t) / getTickFrequency()) << " 秒"< is_img_names;//string转化为Strig。
		for(size_t i=0;i indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh);
    vector img_subset;
    vector img_names_subset;
    vector full_img_sizes_subset;
    for (size_t i = 0; i < indices.size(); ++i)
    {
        img_names_subset.push_back(img_names[indices[i]]);
        img_subset.push_back(images[indices[i]]);
        full_img_sizes_subset.push_back(full_img_sizes[indices[i]]);
    }

    images = img_subset;
    img_names = img_names_subset;
    full_img_sizes = full_img_sizes_subset;

    // 检查我们是否还有足够的图像
    num_images = static_cast(img_names.size());
	cout << "要拼接的图像数:" < cameras;//表示相机参数矢量队列 
    estimator(features, pairwise_matches, cameras);//相机参数评估 

    for (size_t i = 0; i < cameras.size(); ++i)
    {
        Mat R;
        cameras[i].R.convertTo(R, CV_32F);
        cameras[i].R = R;
        //LOGLN("Initial intrinsics #" << indices[i]+1 << ":\n" << cameras[i].K());
        //cout<<"初始内参 #" << indices[i]+1 << ":\n" << cameras[i].K()< adjuster;
 //   if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
 //   else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
 //   else
 //   {
 //       cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
 //       return -1;
 //   }
 //   adjuster->setConfThresh(conf_thresh);
 //   Mat_ refine_mask = Mat::zeros(3, 3, CV_8U);
 //   if (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
 //   if (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
 //   if (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
 //   if (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
 //   if (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
 //   adjuster->setRefinementMask(refine_mask);
 //   (*adjuster)(features, pairwise_matches, cameras);

    // 求出的焦距取中值

    vector focals;
    for (size_t i = 0; i < cameras.size(); ++i)
    {
        //LOGLN("Camera #" << indices[i]+1 << ":\n" << cameras[i].K());
        focals.push_back(cameras[i].focal);
    }

    sort(focals.begin(), focals.end());
    float warped_image_scale;
    if (focals.size() % 2 == 1)
        warped_image_scale = static_cast(focals[focals.size() / 2]);
    else
        warped_image_scale = static_cast(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f;

    if (do_wave_correct)
    {
        vector rmats;
        for (size_t i = 0; i < cameras.size(); ++i)
            rmats.push_back(cameras[i].R.clone());
        waveCorrect(rmats, wave_correct);
        for (size_t i = 0; i < cameras.size(); ++i)
            cameras[i].R = rmats[i];
    }

    //LOGLN("Warping images (auxiliary)... ");
	cout<<"正在扭曲图像(辅助)..."< corners(num_images);
    vector masks_warped(num_images);
    vector images_warped(num_images);
    vector sizes(num_images);
    vector masks(num_images);

    // Preapre images masks
    for (int i = 0; i < num_images; ++i)
    {
        masks[i].create(images[i].size(), CV_8U);
        masks[i].setTo(Scalar::all(255));
    }

    // Warp images and their masks

    Ptr warper_creator;
#if defined(HAVE_OPENCV_GPU)
    if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
    {
        if (warp_type == "plane") warper_creator = new cv::PlaneWarperGpu();
        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarperGpu();
        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarperGpu();
    }
    else
#endif
    {
        if (warp_type == "plane") warper_creator = new cv::PlaneWarper();
        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper();
        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper();
        else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
        else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
        else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
        else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
        else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
        else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
        else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
        else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
        else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
        else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
        else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
        else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
    }

    if (warper_creator.empty())
    {
        cout << "Can't create the following warper '" << warp_type << "'\n";
        return 1;
    }

    Ptr warper = warper_creator->create(static_cast(warped_image_scale * seam_work_aspect));

    for (int i = 0; i < num_images; ++i)
    {
        Mat_ K;
        cameras[i].K().convertTo(K, CV_32F);
        float swa = (float)seam_work_aspect;
        K(0,0) *= swa; K(0,2) *= swa;
        K(1,1) *= swa; K(1,2) *= swa;

        corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
        sizes[i] = images_warped[i].size();

        warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
    }

    vector images_warped_f(num_images);
    for (int i = 0; i < num_images; ++i)
        images_warped[i].convertTo(images_warped_f[i], CV_32F);

    //LOGLN("Warping images, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
	cout<<"扭曲图像用时:"<< ((getTickCount() - t) / getTickFrequency()) << " 秒"< compensator = ExposureCompensator::createDefault(expos_comp_type);
	//Mat转变为UMat----------------------------------------------------------开始
	vector u_images_warped; //复制一个
    for (unsigned int i = 0; i < images_warped.size(); ++i)  
		u_images_warped.push_back(images_warped[i].getUMat(cv::ACCESS_READ));
    vector u_masks_warped; //复制一个
    for (unsigned int i = 0; i < masks_warped.size(); ++i)  
		u_masks_warped.push_back(masks_warped[i].getUMat(cv::ACCESS_READ));
	//Mat转变为UMat----------------------------------------------------------结束
    compensator->feed(corners, u_images_warped, u_masks_warped);
    //compensator->feed(corners, images_warped, masks_warped);

	cout<<"正在寻找接缝..."< seam_finder;
    if (seam_find_type == "no")
        seam_finder = new detail::NoSeamFinder();
    else if (seam_find_type == "voronoi")
        seam_finder = new detail::VoronoiSeamFinder();
    else if (seam_find_type == "gc_color")
    {
#if defined(HAVE_OPENCV_GPU)
        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR);
        else
#endif
            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR);
    }
    else if (seam_find_type == "gc_colorgrad")
    {
#if defined(HAVE_OPENCV_GPU)
        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR_GRAD);
        else
#endif
            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR_GRAD);
    }
    else if (seam_find_type == "dp_color")
        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR);
    else if (seam_find_type == "dp_colorgrad")
        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR_GRAD);
    if (seam_finder.empty())
    {
        cout << "Can't create the following seam finder '" << seam_find_type << "'\n";
        return 1;
    }

	//Mat转变为UMat----------------------------------------------------------开始
	vector u_images_warped_f; //images_warped_f 转化为 u_images_warped_f
    for (unsigned int i = 0; i < images_warped_f.size(); ++i)  
		u_images_warped_f.push_back(images_warped_f[i].getUMat(cv::ACCESS_READ));
	//Mat转变为UMat----------------------------------------------------------结束
    //seam_finder->find(images_warped_f, corners, masks_warped);
    seam_finder->find(u_images_warped_f, corners, u_masks_warped);   //

    // 释放不再使用的内存
    images.clear();
    images_warped.clear();
    images_warped_f.clear();
    masks.clear();

    //LOGLN("Compositing...");
	cout<<"正在合成图像..." < blender;
    //double compose_seam_aspect = 1;
    double compose_work_aspect = 1;

    for (int img_idx = 0; img_idx < num_images; ++img_idx)
    {
        //LOGLN("Compositing image #" << indices[img_idx]+1);
		cout<<"合成图像 #" << indices[img_idx]+1< 0)
                compose_scale = min(1.0, sqrt(compose_megapix * 1e6 / full_img.size().area()));
            is_compose_scale_set = true;

            // 计算相对比例
            //compose_seam_aspect = compose_scale / seam_scale;
            compose_work_aspect = compose_scale / work_scale;

            // 更新扭曲图像比例
            warped_image_scale *= static_cast(compose_work_aspect);
            warper = warper_creator->create(warped_image_scale);

            // 更新角和尺寸
            for (int i = 0; i < num_images; ++i)
            {
                // 更新本质
                cameras[i].focal *= compose_work_aspect;
                cameras[i].ppx *= compose_work_aspect;
                cameras[i].ppy *= compose_work_aspect;

                // Update corner and size
                Size sz = full_img_sizes[i];
                if (std::abs(compose_scale - 1) > 1e-1)
                {
                    sz.width = cvRound(full_img_sizes[i].width * compose_scale);
                    sz.height = cvRound(full_img_sizes[i].height * compose_scale);
                }

                Mat K;
                cameras[i].K().convertTo(K, CV_32F);
                Rect roi = warper->warpRoi(sz, K, cameras[i].R);
                corners[i] = roi.tl();
                sizes[i] = roi.size();
            }
        }
        if (abs(compose_scale - 1) > 1e-1)
            resize(full_img, img, Size(), compose_scale, compose_scale);
        else
            img = full_img;
        full_img.release();
        Size img_size = img.size();

        Mat K;
        cameras[img_idx].K().convertTo(K, CV_32F);

        // 扭曲当前图像
        warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped);

        // 扭曲当前图像掩码
        mask.create(img_size, CV_8U);
        mask.setTo(Scalar::all(255));
        warper->warp(mask, K, cameras[img_idx].R, INTER_NEAREST, BORDER_CONSTANT, mask_warped);

        // 曝光补偿
        compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped);

        img_warped.convertTo(img_warped_s, CV_16S);
        img_warped.release();
        img.release();
        mask.release();

        dilate(masks_warped[img_idx], dilated_mask, Mat());
        resize(dilated_mask, seam_mask, mask_warped.size());
        mask_warped = seam_mask & mask_warped;

        if (blender.empty())
        {
            blender = Blender::createDefault(blend_type, try_gpu);
            Size dst_sz = resultRoi(corners, sizes).size();
            float blend_width = sqrt(static_cast(dst_sz.area())) * blend_strength / 100.f;
            if (blend_width < 1.f)
                blender = Blender::createDefault(Blender::NO, try_gpu);
            else if (blend_type == Blender::MULTI_BAND)
            {
                MultiBandBlender* mb = dynamic_cast(static_cast(blender));
                mb->setNumBands(static_cast(ceil(log(blend_width)/log(2.)) - 1.));
                //LOGLN("Multi-band blender, number of bands: " << mb->numBands());
				cout<<" 多频段图像融合, 分段数: " << mb->numBands()<(static_cast(blender));
                fb->setSharpness(1.f/blend_width);
                //LOGLN("Feather blender, sharpness: " << fb->sharpness());
				cout<<"羽化融合,清晰度:" << fb->sharpness() <prepare(corners, sizes);
        }

        // 混合当前图像
        blender->feed(img_warped_s, mask_warped, corners[img_idx]);
    }

    Mat result, result_mask;

    blender->blend(result, result_mask);

    //LOGLN("Compositing, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
	cout<<"图像混合用时:"<< ((getTickCount() - t) / getTickFrequency()) << " 秒"<

由于光束平差太卡,也去掉了

串联匹配以博文《Opencv2.4.9源码分析——Stitching(二)》为模板作为一个单独cpp,

比便简单,直接看吧:

//串联匹配
#define ENABLE_LOG 1

#include 
#include "opencv2/stitching/detail/autocalib.hpp"  
#include "opencv2/stitching/detail/blenders.hpp"  
#include "opencv2/stitching/detail/camera.hpp"  
#include "opencv2/stitching/detail/exposure_compensate.hpp"  
#include "opencv2/stitching/detail/matchers.hpp"  
#include "opencv2/stitching/detail/motion_estimators.hpp"  
#include "opencv2/stitching/detail/seam_finders.hpp"  
#include "opencv2/stitching/detail/util.hpp"  
#include "opencv2/stitching/detail/warpers.hpp"  
#include "opencv2/stitching/warpers.hpp"  
  
#include   
#include    
#include   
#include    
using namespace cv;  
using namespace std;  
using namespace detail;  

void f2_matcher(vector &features,vector &f2_matches)
{

   //vector f2_matches;    //特征匹配  
   BestOf2NearestMatcher matcher(false, 0.3f, 6, 6);    //定义特征匹配器,2NN方法  
   matcher(features, f2_matches);    //进行特征匹配  
  

}

void i_matcher(vector &features, vector &pairwise_matches)
{
	int num_images=features.size ();
	//1。串联匹配
	vector> f2_2;//f2_2[i] 表示 i 和 i+1 的匹配关系(0 开头,比图像数小 1)
    for (int i = 1; i < num_images; ++i)
    {
		vector f2;
		vector m2;
		f2.push_back (features[i-1]);
		f2.push_back (features[i]);
		f2_matcher(f2,m2);
		f2_2.push_back(m2);

	}


	//2。把串联匹配 ----按opencv stitching 拼接的匹配关系组在一起
	MatchesInfo f;//大小: n x n (n个图)
    for (int i = 0; i < num_images; ++i)
    {
		for (int j = 0; j < num_images; ++j)
		{
			//cout<<"i,j:"<

用前面的83个图来测试下,到曝光补偿这步就内存溢出而出错了,当减少到40个图时就出来了

对Opencv 的stitching 的使用串联匹配_第1张图片

用时 408.58 秒,6分多,7分钟不到



你可能感兴趣的:(拼接全景图,opencv,opencv,stitching改进,串联快速匹配)