PageRenderTime 573ms CodeModel.GetById 100ms app.highlight 324ms RepoModel.GetById 139ms app.codeStats 1ms

/samples/cpp/stitching_detailed.cpp

https://github.com/NITESH21/opencv
C++ | 767 lines | 632 code | 72 blank | 63 comment | 238 complexity | a454b8c7258a901d12e69d1cc612104e MD5 | raw file
  1/*M///////////////////////////////////////////////////////////////////////////////////////
  2//
  3//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4//
  5//  By downloading, copying, installing or using the software you agree to this license.
  6//  If you do not agree to this license, do not download, install,
  7//  copy or use the software.
  8//
  9//
 10//                          License Agreement
 11//                For Open Source Computer Vision Library
 12//
 13// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 14// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 15// Third party copyrights are property of their respective owners.
 16//
 17// Redistribution and use in source and binary forms, with or without modification,
 18// are permitted provided that the following conditions are met:
 19//
 20//   * Redistribution's of source code must retain the above copyright notice,
 21//     this list of conditions and the following disclaimer.
 22//
 23//   * Redistribution's in binary form must reproduce the above copyright notice,
 24//     this list of conditions and the following disclaimer in the documentation
 25//     and/or other materials provided with the distribution.
 26//
 27//   * The name of the copyright holders may not be used to endorse or promote products
 28//     derived from this software without specific prior written permission.
 29//
 30// This software is provided by the copyright holders and contributors "as is" and
 31// any express or implied warranties, including, but not limited to, the implied
 32// warranties of merchantability and fitness for a particular purpose are disclaimed.
 33// In no event shall the Intel Corporation or contributors be liable for any direct,
 34// indirect, incidental, special, exemplary, or consequential damages
 35// (including, but not limited to, procurement of substitute goods or services;
 36// loss of use, data, or profits; or business interruption) however caused
 37// and on any theory of liability, whether in contract, strict liability,
 38// or tort (including negligence or otherwise) arising in any way out of
 39// the use of this software, even if advised of the possibility of such damage.
 40//
 41//
 42//M*/
 43
 44#include <iostream>
 45#include <fstream>
 46#include <string>
 47#include "opencv2/opencv_modules.hpp"
 48#include <opencv2/core/utility.hpp>
 49#include "opencv2/highgui.hpp"
 50#include "opencv2/stitching/detail/autocalib.hpp"
 51#include "opencv2/stitching/detail/blenders.hpp"
 52#include "opencv2/stitching/detail/camera.hpp"
 53#include "opencv2/stitching/detail/exposure_compensate.hpp"
 54#include "opencv2/stitching/detail/matchers.hpp"
 55#include "opencv2/stitching/detail/motion_estimators.hpp"
 56#include "opencv2/stitching/detail/seam_finders.hpp"
 57#include "opencv2/stitching/detail/util.hpp"
 58#include "opencv2/stitching/detail/warpers.hpp"
 59#include "opencv2/stitching/warpers.hpp"
 60
 61using namespace std;
 62using namespace cv;
 63using namespace cv::detail;
 64
 65static void printUsage()
 66{
 67    cout <<
 68        "Rotation model images stitcher.\n\n"
 69        "stitching_detailed img1 img2 [...imgN] [flags]\n\n"
 70        "Flags:\n"
 71        "  --preview\n"
 72        "      Run stitching in the preview mode. Works faster than usual mode,\n"
 73        "      but output image will have lower resolution.\n"
 74        "  --try_gpu (yes|no)\n"
 75        "      Try to use GPU. The default value is 'no'. All default values\n"
 76        "      are for CPU mode.\n"
 77        "\nMotion Estimation Flags:\n"
 78        "  --work_megapix <float>\n"
 79        "      Resolution for image registration step. The default is 0.6 Mpx.\n"
 80        "  --features (surf|orb)\n"
 81        "      Type of features used for images matching. The default is surf.\n"
 82        "  --match_conf <float>\n"
 83        "      Confidence for feature matching step. The default is 0.65 for surf and 0.3 for orb.\n"
 84        "  --conf_thresh <float>\n"
 85        "      Threshold for two images are from the same panorama confidence.\n"
 86        "      The default is 1.0.\n"
 87        "  --ba (reproj|ray)\n"
 88        "      Bundle adjustment cost function. The default is ray.\n"
 89        "  --ba_refine_mask (mask)\n"
 90        "      Set refinement mask for bundle adjustment. It looks like 'x_xxx',\n"
 91        "      where 'x' means refine respective parameter and '_' means don't\n"
 92        "      refine one, and has the following format:\n"
 93        "      <fx><skew><ppx><aspect><ppy>. The default mask is 'xxxxx'. If bundle\n"
 94        "      adjustment doesn't support estimation of selected parameter then\n"
 95        "      the respective flag is ignored.\n"
 96        "  --wave_correct (no|horiz|vert)\n"
 97        "      Perform wave effect correction. The default is 'horiz'.\n"
 98        "  --save_graph <file_name>\n"
 99        "      Save matches graph represented in DOT language to <file_name> file.\n"
100        "      Labels description: Nm is number of matches, Ni is number of inliers,\n"
101        "      C is confidence.\n"
102        "\nCompositing Flags:\n"
103        "  --warp (plane|cylindrical|spherical|fisheye|stereographic|compressedPlaneA2B1|compressedPlaneA1.5B1|compressedPlanePortraitA2B1|compressedPlanePortraitA1.5B1|paniniA2B1|paniniA1.5B1|paniniPortraitA2B1|paniniPortraitA1.5B1|mercator|transverseMercator)\n"
104        "      Warp surface type. The default is 'spherical'.\n"
105        "  --seam_megapix <float>\n"
106        "      Resolution for seam estimation step. The default is 0.1 Mpx.\n"
107        "  --seam (no|voronoi|gc_color|gc_colorgrad)\n"
108        "      Seam estimation method. The default is 'gc_color'.\n"
109        "  --compose_megapix <float>\n"
110        "      Resolution for compositing step. Use -1 for original resolution.\n"
111        "      The default is -1.\n"
112        "  --expos_comp (no|gain|gain_blocks)\n"
113        "      Exposure compensation method. The default is 'gain_blocks'.\n"
114        "  --blend (no|feather|multiband)\n"
115        "      Blending method. The default is 'multiband'.\n"
116        "  --blend_strength <float>\n"
117        "      Blending strength from [0,100] range. The default is 5.\n"
118        "  --output <result_img>\n"
119        "      The default is 'result.jpg'.\n";
120}
121
122
123// Default command line args
124vector<String> img_names;
125bool preview = false;
126bool try_gpu = false;
127double work_megapix = 0.6;
128double seam_megapix = 0.1;
129double compose_megapix = -1;
130float conf_thresh = 1.f;
131string features_type = "surf";
132string ba_cost_func = "ray";
133string ba_refine_mask = "xxxxx";
134bool do_wave_correct = true;
135WaveCorrectKind wave_correct = detail::WAVE_CORRECT_HORIZ;
136bool save_graph = false;
137std::string save_graph_to;
138string warp_type = "spherical";
139int expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
140float match_conf = 0.3f;
141string seam_find_type = "gc_color";
142int blend_type = Blender::MULTI_BAND;
143float blend_strength = 5;
144string result_name = "result.jpg";
145
146static int parseCmdArgs(int argc, char** argv)
147{
148    if (argc == 1)
149    {
150        printUsage();
151        return -1;
152    }
153    for (int i = 1; i < argc; ++i)
154    {
155        if (string(argv[i]) == "--help" || string(argv[i]) == "/?")
156        {
157            printUsage();
158            return -1;
159        }
160        else if (string(argv[i]) == "--preview")
161        {
162            preview = true;
163        }
164        else if (string(argv[i]) == "--try_gpu")
165        {
166            if (string(argv[i + 1]) == "no")
167                try_gpu = false;
168            else if (string(argv[i + 1]) == "yes")
169                try_gpu = true;
170            else
171            {
172                cout << "Bad --try_gpu flag value\n";
173                return -1;
174            }
175            i++;
176        }
177        else if (string(argv[i]) == "--work_megapix")
178        {
179            work_megapix = atof(argv[i + 1]);
180            i++;
181        }
182        else if (string(argv[i]) == "--seam_megapix")
183        {
184            seam_megapix = atof(argv[i + 1]);
185            i++;
186        }
187        else if (string(argv[i]) == "--compose_megapix")
188        {
189            compose_megapix = atof(argv[i + 1]);
190            i++;
191        }
192        else if (string(argv[i]) == "--result")
193        {
194            result_name = argv[i + 1];
195            i++;
196        }
197        else if (string(argv[i]) == "--features")
198        {
199            features_type = argv[i + 1];
200            if (features_type == "orb")
201                match_conf = 0.3f;
202            i++;
203        }
204        else if (string(argv[i]) == "--match_conf")
205        {
206            match_conf = static_cast<float>(atof(argv[i + 1]));
207            i++;
208        }
209        else if (string(argv[i]) == "--conf_thresh")
210        {
211            conf_thresh = static_cast<float>(atof(argv[i + 1]));
212            i++;
213        }
214        else if (string(argv[i]) == "--ba")
215        {
216            ba_cost_func = argv[i + 1];
217            i++;
218        }
219        else if (string(argv[i]) == "--ba_refine_mask")
220        {
221            ba_refine_mask = argv[i + 1];
222            if (ba_refine_mask.size() != 5)
223            {
224                cout << "Incorrect refinement mask length.\n";
225                return -1;
226            }
227            i++;
228        }
229        else if (string(argv[i]) == "--wave_correct")
230        {
231            if (string(argv[i + 1]) == "no")
232                do_wave_correct = false;
233            else if (string(argv[i + 1]) == "horiz")
234            {
235                do_wave_correct = true;
236                wave_correct = detail::WAVE_CORRECT_HORIZ;
237            }
238            else if (string(argv[i + 1]) == "vert")
239            {
240                do_wave_correct = true;
241                wave_correct = detail::WAVE_CORRECT_VERT;
242            }
243            else
244            {
245                cout << "Bad --wave_correct flag value\n";
246                return -1;
247            }
248            i++;
249        }
250        else if (string(argv[i]) == "--save_graph")
251        {
252            save_graph = true;
253            save_graph_to = argv[i + 1];
254            i++;
255        }
256        else if (string(argv[i]) == "--warp")
257        {
258            warp_type = string(argv[i + 1]);
259            i++;
260        }
261        else if (string(argv[i]) == "--expos_comp")
262        {
263            if (string(argv[i + 1]) == "no")
264                expos_comp_type = ExposureCompensator::NO;
265            else if (string(argv[i + 1]) == "gain")
266                expos_comp_type = ExposureCompensator::GAIN;
267            else if (string(argv[i + 1]) == "gain_blocks")
268                expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
269            else
270            {
271                cout << "Bad exposure compensation method\n";
272                return -1;
273            }
274            i++;
275        }
276        else if (string(argv[i]) == "--seam")
277        {
278            if (string(argv[i + 1]) == "no" ||
279                string(argv[i + 1]) == "voronoi" ||
280                string(argv[i + 1]) == "gc_color" ||
281                string(argv[i + 1]) == "gc_colorgrad" ||
282                string(argv[i + 1]) == "dp_color" ||
283                string(argv[i + 1]) == "dp_colorgrad")
284                seam_find_type = argv[i + 1];
285            else
286            {
287                cout << "Bad seam finding method\n";
288                return -1;
289            }
290            i++;
291        }
292        else if (string(argv[i]) == "--blend")
293        {
294            if (string(argv[i + 1]) == "no")
295                blend_type = Blender::NO;
296            else if (string(argv[i + 1]) == "feather")
297                blend_type = Blender::FEATHER;
298            else if (string(argv[i + 1]) == "multiband")
299                blend_type = Blender::MULTI_BAND;
300            else
301            {
302                cout << "Bad blending method\n";
303                return -1;
304            }
305            i++;
306        }
307        else if (string(argv[i]) == "--blend_strength")
308        {
309            blend_strength = static_cast<float>(atof(argv[i + 1]));
310            i++;
311        }
312        else if (string(argv[i]) == "--output")
313        {
314            result_name = argv[i + 1];
315            i++;
316        }
317        else
318            img_names.push_back(argv[i]);
319    }
320    if (preview)
321    {
322        compose_megapix = 0.6;
323    }
324    return 0;
325}
326
327
328int main(int argc, char* argv[])
329{
330#if ENABLE_LOG
331    int64 app_start_time = getTickCount();
332#endif
333
334    cv::setBreakOnError(true);
335
336    int retval = parseCmdArgs(argc, argv);
337    if (retval)
338        return retval;
339
340    // Check if have enough images
341    int num_images = static_cast<int>(img_names.size());
342    if (num_images < 2)
343    {
344        LOGLN("Need more images");
345        return -1;
346    }
347
348    double work_scale = 1, seam_scale = 1, compose_scale = 1;
349    bool is_work_scale_set = false, is_seam_scale_set = false, is_compose_scale_set = false;
350
351    LOGLN("Finding features...");
352#if ENABLE_LOG
353    int64 t = getTickCount();
354#endif
355
356    Ptr<FeaturesFinder> finder;
357    if (features_type == "surf")
358    {
359#ifdef HAVE_OPENCV_NONFREE
360        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
361            finder = new SurfFeaturesFinderGpu();
362        else
363#endif
364            finder = new SurfFeaturesFinder();
365    }
366    else if (features_type == "orb")
367    {
368        finder = new OrbFeaturesFinder();
369    }
370    else
371    {
372        cout << "Unknown 2D features type: '" << features_type << "'.\n";
373        return -1;
374    }
375
376    Mat full_img, img;
377    vector<ImageFeatures> features(num_images);
378    vector<Mat> images(num_images);
379    vector<Size> full_img_sizes(num_images);
380    double seam_work_aspect = 1;
381
382    for (int i = 0; i < num_images; ++i)
383    {
384        full_img = imread(img_names[i]);
385        full_img_sizes[i] = full_img.size();
386
387        if (full_img.empty())
388        {
389            LOGLN("Can't open image " << img_names[i]);
390            return -1;
391        }
392        if (work_megapix < 0)
393        {
394            img = full_img;
395            work_scale = 1;
396            is_work_scale_set = true;
397        }
398        else
399        {
400            if (!is_work_scale_set)
401            {
402                work_scale = min(1.0, sqrt(work_megapix * 1e6 / full_img.size().area()));
403                is_work_scale_set = true;
404            }
405            resize(full_img, img, Size(), work_scale, work_scale);
406        }
407        if (!is_seam_scale_set)
408        {
409            seam_scale = min(1.0, sqrt(seam_megapix * 1e6 / full_img.size().area()));
410            seam_work_aspect = seam_scale / work_scale;
411            is_seam_scale_set = true;
412        }
413
414        (*finder)(img, features[i]);
415        features[i].img_idx = i;
416        LOGLN("Features in image #" << i+1 << ": " << features[i].keypoints.size());
417
418        resize(full_img, img, Size(), seam_scale, seam_scale);
419        images[i] = img.clone();
420    }
421
422    finder->collectGarbage();
423    full_img.release();
424    img.release();
425
426    LOGLN("Finding features, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
427
428    LOG("Pairwise matching");
429#if ENABLE_LOG
430    t = getTickCount();
431#endif
432    vector<MatchesInfo> pairwise_matches;
433    BestOf2NearestMatcher matcher(try_gpu, match_conf);
434    matcher(features, pairwise_matches);
435    matcher.collectGarbage();
436    LOGLN("Pairwise matching, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
437
438    // Check if we should save matches graph
439    if (save_graph)
440    {
441        LOGLN("Saving matches graph...");
442        ofstream f(save_graph_to.c_str());
443        f << matchesGraphAsString(img_names, pairwise_matches, conf_thresh);
444    }
445
446    // Leave only images we are sure are from the same panorama
447    vector<int> indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh);
448    vector<Mat> img_subset;
449    vector<String> img_names_subset;
450    vector<Size> full_img_sizes_subset;
451    for (size_t i = 0; i < indices.size(); ++i)
452    {
453        img_names_subset.push_back(img_names[indices[i]]);
454        img_subset.push_back(images[indices[i]]);
455        full_img_sizes_subset.push_back(full_img_sizes[indices[i]]);
456    }
457
458    images = img_subset;
459    img_names = img_names_subset;
460    full_img_sizes = full_img_sizes_subset;
461
462    // Check if we still have enough images
463    num_images = static_cast<int>(img_names.size());
464    if (num_images < 2)
465    {
466        LOGLN("Need more images");
467        return -1;
468    }
469
470    HomographyBasedEstimator estimator;
471    vector<CameraParams> cameras;
472    estimator(features, pairwise_matches, cameras);
473
474    for (size_t i = 0; i < cameras.size(); ++i)
475    {
476        Mat R;
477        cameras[i].R.convertTo(R, CV_32F);
478        cameras[i].R = R;
479        LOGLN("Initial intrinsics #" << indices[i]+1 << ":\n" << cameras[i].K());
480    }
481
482    Ptr<detail::BundleAdjusterBase> adjuster;
483    if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
484    else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
485    else
486    {
487        cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
488        return -1;
489    }
490    adjuster->setConfThresh(conf_thresh);
491    Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
492    if (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
493    if (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
494    if (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
495    if (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
496    if (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
497    adjuster->setRefinementMask(refine_mask);
498    (*adjuster)(features, pairwise_matches, cameras);
499
500    // Find median focal length
501
502    vector<double> focals;
503    for (size_t i = 0; i < cameras.size(); ++i)
504    {
505        LOGLN("Camera #" << indices[i]+1 << ":\n" << cameras[i].K());
506        focals.push_back(cameras[i].focal);
507    }
508
509    sort(focals.begin(), focals.end());
510    float warped_image_scale;
511    if (focals.size() % 2 == 1)
512        warped_image_scale = static_cast<float>(focals[focals.size() / 2]);
513    else
514        warped_image_scale = static_cast<float>(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f;
515
516    if (do_wave_correct)
517    {
518        vector<Mat> rmats;
519        for (size_t i = 0; i < cameras.size(); ++i)
520            rmats.push_back(cameras[i].R);
521        waveCorrect(rmats, wave_correct);
522        for (size_t i = 0; i < cameras.size(); ++i)
523            cameras[i].R = rmats[i];
524    }
525
526    LOGLN("Warping images (auxiliary)... ");
527#if ENABLE_LOG
528    t = getTickCount();
529#endif
530
531    vector<Point> corners(num_images);
532    vector<Mat> masks_warped(num_images);
533    vector<Mat> images_warped(num_images);
534    vector<Size> sizes(num_images);
535    vector<Mat> masks(num_images);
536
537    // Preapre images masks
538    for (int i = 0; i < num_images; ++i)
539    {
540        masks[i].create(images[i].size(), CV_8U);
541        masks[i].setTo(Scalar::all(255));
542    }
543
544    // Warp images and their masks
545
546    Ptr<WarperCreator> warper_creator;
547#ifdef HAVE_OPENCV_GPUWARPING
548    if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
549    {
550        if (warp_type == "plane") warper_creator = new cv::PlaneWarperGpu();
551        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarperGpu();
552        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarperGpu();
553    }
554    else
555#endif
556    {
557        if (warp_type == "plane") warper_creator = new cv::PlaneWarper();
558        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper();
559        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper();
560        else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
561        else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
562        else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
563        else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
564        else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
565        else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
566        else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
567        else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
568        else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
569        else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
570        else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
571        else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
572    }
573
574    if (warper_creator.empty())
575    {
576        cout << "Can't create the following warper '" << warp_type << "'\n";
577        return 1;
578    }
579
580    Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(warped_image_scale * seam_work_aspect));
581
582    for (int i = 0; i < num_images; ++i)
583    {
584        Mat_<float> K;
585        cameras[i].K().convertTo(K, CV_32F);
586        float swa = (float)seam_work_aspect;
587        K(0,0) *= swa; K(0,2) *= swa;
588        K(1,1) *= swa; K(1,2) *= swa;
589
590        corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
591        sizes[i] = images_warped[i].size();
592
593        warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
594    }
595
596    vector<Mat> images_warped_f(num_images);
597    for (int i = 0; i < num_images; ++i)
598        images_warped[i].convertTo(images_warped_f[i], CV_32F);
599
600    LOGLN("Warping images, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
601
602    Ptr<ExposureCompensator> compensator = ExposureCompensator::createDefault(expos_comp_type);
603    compensator->feed(corners, images_warped, masks_warped);
604
605    Ptr<SeamFinder> seam_finder;
606    if (seam_find_type == "no")
607        seam_finder = new detail::NoSeamFinder();
608    else if (seam_find_type == "voronoi")
609        seam_finder = new detail::VoronoiSeamFinder();
610    else if (seam_find_type == "gc_color")
611    {
612#ifdef HAVE_OPENCV_GPU
613        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
614            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR);
615        else
616#endif
617            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR);
618    }
619    else if (seam_find_type == "gc_colorgrad")
620    {
621#ifdef HAVE_OPENCV_GPU
622        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
623            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR_GRAD);
624        else
625#endif
626            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR_GRAD);
627    }
628    else if (seam_find_type == "dp_color")
629        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR);
630    else if (seam_find_type == "dp_colorgrad")
631        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR_GRAD);
632    if (seam_finder.empty())
633    {
634        cout << "Can't create the following seam finder '" << seam_find_type << "'\n";
635        return 1;
636    }
637
638    seam_finder->find(images_warped_f, corners, masks_warped);
639
640    // Release unused memory
641    images.clear();
642    images_warped.clear();
643    images_warped_f.clear();
644    masks.clear();
645
646    LOGLN("Compositing...");
647#if ENABLE_LOG
648    t = getTickCount();
649#endif
650
651    Mat img_warped, img_warped_s;
652    Mat dilated_mask, seam_mask, mask, mask_warped;
653    Ptr<Blender> blender;
654    //double compose_seam_aspect = 1;
655    double compose_work_aspect = 1;
656
657    for (int img_idx = 0; img_idx < num_images; ++img_idx)
658    {
659        LOGLN("Compositing image #" << indices[img_idx]+1);
660
661        // Read image and resize it if necessary
662        full_img = imread(img_names[img_idx]);
663        if (!is_compose_scale_set)
664        {
665            if (compose_megapix > 0)
666                compose_scale = min(1.0, sqrt(compose_megapix * 1e6 / full_img.size().area()));
667            is_compose_scale_set = true;
668
669            // Compute relative scales
670            //compose_seam_aspect = compose_scale / seam_scale;
671            compose_work_aspect = compose_scale / work_scale;
672
673            // Update warped image scale
674            warped_image_scale *= static_cast<float>(compose_work_aspect);
675            warper = warper_creator->create(warped_image_scale);
676
677            // Update corners and sizes
678            for (int i = 0; i < num_images; ++i)
679            {
680                // Update intrinsics
681                cameras[i].focal *= compose_work_aspect;
682                cameras[i].ppx *= compose_work_aspect;
683                cameras[i].ppy *= compose_work_aspect;
684
685                // Update corner and size
686                Size sz = full_img_sizes[i];
687                if (std::abs(compose_scale - 1) > 1e-1)
688                {
689                    sz.width = cvRound(full_img_sizes[i].width * compose_scale);
690                    sz.height = cvRound(full_img_sizes[i].height * compose_scale);
691                }
692
693                Mat K;
694                cameras[i].K().convertTo(K, CV_32F);
695                Rect roi = warper->warpRoi(sz, K, cameras[i].R);
696                corners[i] = roi.tl();
697                sizes[i] = roi.size();
698            }
699        }
700        if (abs(compose_scale - 1) > 1e-1)
701            resize(full_img, img, Size(), compose_scale, compose_scale);
702        else
703            img = full_img;
704        full_img.release();
705        Size img_size = img.size();
706
707        Mat K;
708        cameras[img_idx].K().convertTo(K, CV_32F);
709
710        // Warp the current image
711        warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped);
712
713        // Warp the current image mask
714        mask.create(img_size, CV_8U);
715        mask.setTo(Scalar::all(255));
716        warper->warp(mask, K, cameras[img_idx].R, INTER_NEAREST, BORDER_CONSTANT, mask_warped);
717
718        // Compensate exposure
719        compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped);
720
721        img_warped.convertTo(img_warped_s, CV_16S);
722        img_warped.release();
723        img.release();
724        mask.release();
725
726        dilate(masks_warped[img_idx], dilated_mask, Mat());
727        resize(dilated_mask, seam_mask, mask_warped.size());
728        mask_warped = seam_mask & mask_warped;
729
730        if (blender.empty())
731        {
732            blender = Blender::createDefault(blend_type, try_gpu);
733            Size dst_sz = resultRoi(corners, sizes).size();
734            float blend_width = sqrt(static_cast<float>(dst_sz.area())) * blend_strength / 100.f;
735            if (blend_width < 1.f)
736                blender = Blender::createDefault(Blender::NO, try_gpu);
737            else if (blend_type == Blender::MULTI_BAND)
738            {
739                MultiBandBlender* mb = dynamic_cast<MultiBandBlender*>(static_cast<Blender*>(blender));
740                mb->setNumBands(static_cast<int>(ceil(log(blend_width)/log(2.)) - 1.));
741                LOGLN("Multi-band blender, number of bands: " << mb->numBands());
742            }
743            else if (blend_type == Blender::FEATHER)
744            {
745                FeatherBlender* fb = dynamic_cast<FeatherBlender*>(static_cast<Blender*>(blender));
746                fb->setSharpness(1.f/blend_width);
747                LOGLN("Feather blender, sharpness: " << fb->sharpness());
748            }
749            blender->prepare(corners, sizes);
750        }
751
752        // Blend the current image
753        blender->feed(img_warped_s, mask_warped, corners[img_idx]);
754    }
755
756    Mat result, result_mask;
757    blender->blend(result, result_mask);
758
759    LOGLN("Compositing, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
760
761    imwrite(result_name, result);
762
763    LOGLN("Finished, total time: " << ((getTickCount() - app_start_time) / getTickFrequency()) << " sec");
764    return 0;
765}
766
767