PageRenderTime 564ms CodeModel.GetById 111ms app.highlight 326ms RepoModel.GetById 117ms app.codeStats 0ms

/samples/cpp/stitching_detailed.cpp

https://github.com/smart-make/opencv
C++ | 775 lines | 640 code | 72 blank | 63 comment | 240 complexity | 4722c4e46bd5bcd6c073fdc27dea5026 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    if (!estimator(features, pairwise_matches, cameras))
473    {
474        cout << "Homography estimation failed.\n";
475        return -1;
476    }
477
478    for (size_t i = 0; i < cameras.size(); ++i)
479    {
480        Mat R;
481        cameras[i].R.convertTo(R, CV_32F);
482        cameras[i].R = R;
483        LOGLN("Initial intrinsics #" << indices[i]+1 << ":\n" << cameras[i].K());
484    }
485
486    Ptr<detail::BundleAdjusterBase> adjuster;
487    if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
488    else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
489    else
490    {
491        cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
492        return -1;
493    }
494    adjuster->setConfThresh(conf_thresh);
495    Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
496    if (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
497    if (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
498    if (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
499    if (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
500    if (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
501    adjuster->setRefinementMask(refine_mask);
502    if (!(*adjuster)(features, pairwise_matches, cameras))
503    {
504        cout << "Camera parameters adjusting failed.\n";
505        return -1;
506    }
507
508    // Find median focal length
509
510    vector<double> focals;
511    for (size_t i = 0; i < cameras.size(); ++i)
512    {
513        LOGLN("Camera #" << indices[i]+1 << ":\n" << cameras[i].K());
514        focals.push_back(cameras[i].focal);
515    }
516
517    sort(focals.begin(), focals.end());
518    float warped_image_scale;
519    if (focals.size() % 2 == 1)
520        warped_image_scale = static_cast<float>(focals[focals.size() / 2]);
521    else
522        warped_image_scale = static_cast<float>(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f;
523
524    if (do_wave_correct)
525    {
526        vector<Mat> rmats;
527        for (size_t i = 0; i < cameras.size(); ++i)
528            rmats.push_back(cameras[i].R);
529        waveCorrect(rmats, wave_correct);
530        for (size_t i = 0; i < cameras.size(); ++i)
531            cameras[i].R = rmats[i];
532    }
533
534    LOGLN("Warping images (auxiliary)... ");
535#if ENABLE_LOG
536    t = getTickCount();
537#endif
538
539    vector<Point> corners(num_images);
540    vector<Mat> masks_warped(num_images);
541    vector<Mat> images_warped(num_images);
542    vector<Size> sizes(num_images);
543    vector<Mat> masks(num_images);
544
545    // Preapre images masks
546    for (int i = 0; i < num_images; ++i)
547    {
548        masks[i].create(images[i].size(), CV_8U);
549        masks[i].setTo(Scalar::all(255));
550    }
551
552    // Warp images and their masks
553
554    Ptr<WarperCreator> warper_creator;
555#ifdef HAVE_OPENCV_GPUWARPING
556    if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
557    {
558        if (warp_type == "plane") warper_creator = new cv::PlaneWarperGpu();
559        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarperGpu();
560        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarperGpu();
561    }
562    else
563#endif
564    {
565        if (warp_type == "plane") warper_creator = new cv::PlaneWarper();
566        else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper();
567        else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper();
568        else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
569        else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
570        else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
571        else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
572        else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
573        else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
574        else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
575        else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
576        else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
577        else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
578        else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
579        else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
580    }
581
582    if (warper_creator.empty())
583    {
584        cout << "Can't create the following warper '" << warp_type << "'\n";
585        return 1;
586    }
587
588    Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(warped_image_scale * seam_work_aspect));
589
590    for (int i = 0; i < num_images; ++i)
591    {
592        Mat_<float> K;
593        cameras[i].K().convertTo(K, CV_32F);
594        float swa = (float)seam_work_aspect;
595        K(0,0) *= swa; K(0,2) *= swa;
596        K(1,1) *= swa; K(1,2) *= swa;
597
598        corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
599        sizes[i] = images_warped[i].size();
600
601        warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
602    }
603
604    vector<Mat> images_warped_f(num_images);
605    for (int i = 0; i < num_images; ++i)
606        images_warped[i].convertTo(images_warped_f[i], CV_32F);
607
608    LOGLN("Warping images, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
609
610    Ptr<ExposureCompensator> compensator = ExposureCompensator::createDefault(expos_comp_type);
611    compensator->feed(corners, images_warped, masks_warped);
612
613    Ptr<SeamFinder> seam_finder;
614    if (seam_find_type == "no")
615        seam_finder = new detail::NoSeamFinder();
616    else if (seam_find_type == "voronoi")
617        seam_finder = new detail::VoronoiSeamFinder();
618    else if (seam_find_type == "gc_color")
619    {
620#ifdef HAVE_OPENCV_GPU
621        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
622            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR);
623        else
624#endif
625            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR);
626    }
627    else if (seam_find_type == "gc_colorgrad")
628    {
629#ifdef HAVE_OPENCV_GPU
630        if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
631            seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR_GRAD);
632        else
633#endif
634            seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR_GRAD);
635    }
636    else if (seam_find_type == "dp_color")
637        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR);
638    else if (seam_find_type == "dp_colorgrad")
639        seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR_GRAD);
640    if (seam_finder.empty())
641    {
642        cout << "Can't create the following seam finder '" << seam_find_type << "'\n";
643        return 1;
644    }
645
646    seam_finder->find(images_warped_f, corners, masks_warped);
647
648    // Release unused memory
649    images.clear();
650    images_warped.clear();
651    images_warped_f.clear();
652    masks.clear();
653
654    LOGLN("Compositing...");
655#if ENABLE_LOG
656    t = getTickCount();
657#endif
658
659    Mat img_warped, img_warped_s;
660    Mat dilated_mask, seam_mask, mask, mask_warped;
661    Ptr<Blender> blender;
662    //double compose_seam_aspect = 1;
663    double compose_work_aspect = 1;
664
665    for (int img_idx = 0; img_idx < num_images; ++img_idx)
666    {
667        LOGLN("Compositing image #" << indices[img_idx]+1);
668
669        // Read image and resize it if necessary
670        full_img = imread(img_names[img_idx]);
671        if (!is_compose_scale_set)
672        {
673            if (compose_megapix > 0)
674                compose_scale = min(1.0, sqrt(compose_megapix * 1e6 / full_img.size().area()));
675            is_compose_scale_set = true;
676
677            // Compute relative scales
678            //compose_seam_aspect = compose_scale / seam_scale;
679            compose_work_aspect = compose_scale / work_scale;
680
681            // Update warped image scale
682            warped_image_scale *= static_cast<float>(compose_work_aspect);
683            warper = warper_creator->create(warped_image_scale);
684
685            // Update corners and sizes
686            for (int i = 0; i < num_images; ++i)
687            {
688                // Update intrinsics
689                cameras[i].focal *= compose_work_aspect;
690                cameras[i].ppx *= compose_work_aspect;
691                cameras[i].ppy *= compose_work_aspect;
692
693                // Update corner and size
694                Size sz = full_img_sizes[i];
695                if (std::abs(compose_scale - 1) > 1e-1)
696                {
697                    sz.width = cvRound(full_img_sizes[i].width * compose_scale);
698                    sz.height = cvRound(full_img_sizes[i].height * compose_scale);
699                }
700
701                Mat K;
702                cameras[i].K().convertTo(K, CV_32F);
703                Rect roi = warper->warpRoi(sz, K, cameras[i].R);
704                corners[i] = roi.tl();
705                sizes[i] = roi.size();
706            }
707        }
708        if (abs(compose_scale - 1) > 1e-1)
709            resize(full_img, img, Size(), compose_scale, compose_scale);
710        else
711            img = full_img;
712        full_img.release();
713        Size img_size = img.size();
714
715        Mat K;
716        cameras[img_idx].K().convertTo(K, CV_32F);
717
718        // Warp the current image
719        warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped);
720
721        // Warp the current image mask
722        mask.create(img_size, CV_8U);
723        mask.setTo(Scalar::all(255));
724        warper->warp(mask, K, cameras[img_idx].R, INTER_NEAREST, BORDER_CONSTANT, mask_warped);
725
726        // Compensate exposure
727        compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped);
728
729        img_warped.convertTo(img_warped_s, CV_16S);
730        img_warped.release();
731        img.release();
732        mask.release();
733
734        dilate(masks_warped[img_idx], dilated_mask, Mat());
735        resize(dilated_mask, seam_mask, mask_warped.size());
736        mask_warped = seam_mask & mask_warped;
737
738        if (blender.empty())
739        {
740            blender = Blender::createDefault(blend_type, try_gpu);
741            Size dst_sz = resultRoi(corners, sizes).size();
742            float blend_width = sqrt(static_cast<float>(dst_sz.area())) * blend_strength / 100.f;
743            if (blend_width < 1.f)
744                blender = Blender::createDefault(Blender::NO, try_gpu);
745            else if (blend_type == Blender::MULTI_BAND)
746            {
747                MultiBandBlender* mb = dynamic_cast<MultiBandBlender*>(static_cast<Blender*>(blender));
748                mb->setNumBands(static_cast<int>(ceil(log(blend_width)/log(2.)) - 1.));
749                LOGLN("Multi-band blender, number of bands: " << mb->numBands());
750            }
751            else if (blend_type == Blender::FEATHER)
752            {
753                FeatherBlender* fb = dynamic_cast<FeatherBlender*>(static_cast<Blender*>(blender));
754                fb->setSharpness(1.f/blend_width);
755                LOGLN("Feather blender, sharpness: " << fb->sharpness());
756            }
757            blender->prepare(corners, sizes);
758        }
759
760        // Blend the current image
761        blender->feed(img_warped_s, mask_warped, corners[img_idx]);
762    }
763
764    Mat result, result_mask;
765    blender->blend(result, result_mask);
766
767    LOGLN("Compositing, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
768
769    imwrite(result_name, result);
770
771    LOGLN("Finished, total time: " << ((getTickCount() - app_start_time) / getTickFrequency()) << " sec");
772    return 0;
773}
774
775