PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/samples/cpp/stitching_detailed.cpp

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