PageRenderTime 84ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/samples/cpp/stitching_detailed.cpp

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