当前位置:   article > 正文

如何使用OpenCV实现多张图像拼接_opencv多幅图像拼接算法

opencv多幅图像拼接算法

先来看看OpenCV官方的例子得到效果是非常的好,输入的images如下:

效果:

#Stitcher类与detail命名空间

OpenCV提供了高级别的函数封装在Stitcher类中,使用很方便,不用考虑太多的细节。

低级别函数封装在detail命名空间中,展示了OpenCV算法实现的很多步骤和细节,使熟悉如下拼接流水线的用户,方便自己定制。

这涉及到以下算法流程:

命令行调用程序,输入源图像以及程序的参数

特征点检测,判断是使用surf还是orb,默认是surf。

对图像的特征点进行匹配,使用最近邻和次近邻方法,

将两个最优的匹配的置信度保存下来。

对图像进行排序以及将置信度高的图像保存到同一个集合中,

删除置信度比较低的图像间的匹配,得到能正确匹配的图像序列。

这样将置信度高于门限的所有匹配合并到一个集合中。

对所有图像进行相机参数粗略估计,然后求出旋转矩阵

使用光束平均法进一步精准的估计出旋转矩阵。

波形校正,水平或者垂直

拼接

融合,多频段融合,光照补偿。

另外在拼接的时候可以设置不同warper,这样会对拼接之后的图像生成不同效果,常见的效果包括

  1. 鱼眼相机
  2. 环视(平面曲翘)
  3. 默认

如下图所示:

代码演示:

  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. using namespace cv;
  4. using namespace std;
  5. int main(int argc, char** argv) {
  6. vector<string> files;
  7. glob("D:/images/zsxq/1", files);
  8. vector<Mat> images;
  9. for (int i = 0; i < files.size(); i++) {
  10. printf("image file : %s \n", files[i].c_str());
  11. images.push_back(imread(files[i]));
  12. }
  13. // 设置拼接模式与参数
  14. Mat result1, result2, result3;
  15. Stitcher::Mode mode = Stitcher::PANORAMA;
  16. Ptr<Stitcher> stitcher = Stitcher::create(mode);
  17. // 拼接方式-多通道融合
  18. auto blender = detail::Blender::createDefault(detail::Blender::MULTI_BAND);
  19. stitcher->setBlender(blender);
  20. // 拼接
  21. Stitcher::Status status = stitcher->stitch(images, result1);
  22. // 平面曲翘拼接
  23. auto plane_warper = makePtr<cv::PlaneWarper>();
  24. stitcher->setWarper(plane_warper);
  25. status = stitcher->stitch(images, result2);
  26. // 鱼眼拼接
  27. auto fisheye_warper = makePtr<cv::FisheyeWarper>();
  28. stitcher->setWarper(fisheye_warper);
  29. status = stitcher->stitch(images, result3);
  30. // 检查返回
  31. if (status != Stitcher::OK)
  32. {
  33. cout << "Can't stitch images, error code = " << int(status) << endl;
  34. return EXIT_FAILURE;
  35. }
  36. imwrite("D:/result1.png", result1);
  37. imwrite("D:/result2.png", result2);
  38. imwrite("D:/result3.png", result3);
  39. waitKey(0);
  40. return 0;
  41. }

在来看一组输入4张图像,每张分辨率为327*245,总的拼接时间为9.25s。

演示代码:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include "opencv2/opencv_modules.hpp"
  5. #include "opencv2/highgui/highgui.hpp"
  6. #include "opencv2/stitching/detail/autocalib.hpp"
  7. #include "opencv2/stitching/detail/blenders.hpp"
  8. #include "opencv2/stitching/detail/camera.hpp"
  9. #include "opencv2/stitching/detail/exposure_compensate.hpp"
  10. #include "opencv2/stitching/detail/matchers.hpp"
  11. #include "opencv2/stitching/detail/motion_estimators.hpp"
  12. #include "opencv2/stitching/detail/seam_finders.hpp"
  13. #include "opencv2/stitching/detail/util.hpp"
  14. #include "opencv2/stitching/detail/warpers.hpp"
  15. #include "opencv2/stitching/warpers.hpp"
  16. using namespace std;
  17. using namespace cv;
  18. using namespace cv::detail;
  19. //
  20. #define ENABLE_LOG 1
  21. // Default command line args
  22. vector<string> img_names;
  23. bool preview = false;
  24. bool try_gpu = true;
  25. double work_megapix = 0.6;
  26. double seam_megapix = 0.1;
  27. double compose_megapix = -1;
  28. float conf_thresh = 1.f;
  29. string features_type = "surf";
  30. string ba_cost_func = "ray";
  31. string ba_refine_mask = "xxxxx";
  32. bool do_wave_correct = true;
  33. WaveCorrectKind wave_correct = detail::WAVE_CORRECT_HORIZ;
  34. bool save_graph = false;
  35. std::string save_graph_to;
  36. string warp_type = "spherical";
  37. int expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
  38. float match_conf = 0.3f;
  39. string seam_find_type = "gc_color";
  40. int blend_type = Blender::MULTI_BAND;
  41. float blend_strength = 5;
  42. string result_name = "result.jpg";
  43. int main(int argc, char* argv[])
  44. {
  45. //读入图像
  46. double ttt = getTickCount();
  47. img_names.push_back("E:/workspace/iamge/dataset/yard1.jpg");
  48. img_names.push_back("E:/workspace/iamge/dataset/yard2.jpg");
  49. img_names.push_back("E:/workspace/iamge/dataset/yard3.jpg");
  50. img_names.push_back("E:/workspace/iamge/dataset/yard4.jpg");
  51. #if ENABLE_LOG
  52. int64 app_start_time = getTickCount();
  53. #endif
  54. cv::setBreak(true);
  55. /*int retval = parseCmdArgs(argc, argv);
  56. if (retval)
  57. return retval;*/
  58. // Check if have enough images
  59. int num_images = static_cast<int>(img_names.size());
  60. if (num_images < 2)
  61. {
  62. LOGLN("Need more images");
  63. return -1;
  64. }
  65. double work_scale = 1, seam_scale = 1, compose_scale = 1;
  66. bool is_work_scale_set = false, is_seam_scale_set = false, is_compose_scale_set = false;
  67. LOGLN("Finding features...");
  68. #if ENABLE_LOG
  69. int64 t = getTickCount();
  70. #endif
  71. Ptr<FeaturesFinder> finder;
  72. if (features_type == "surf")
  73. {
  74. #if defined(HAVE_OPENCV_NONFREE) && defined(HAVE_OPENCV_GPU)
  75. if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
  76. finder = new SurfFeaturesFinderGpu();
  77. else
  78. #endif
  79. finder = new SurfFeaturesFinder();
  80. }
  81. else if (features_type == "orb")
  82. {
  83. finder = new OrbFeaturesFinder();
  84. }
  85. else
  86. {
  87. cout << "Unknown 2D features type: '" << features_type << "'.\n";
  88. return -1;
  89. }
  90. Mat full_img, img;
  91. vector<ImageFeatures> features(num_images);
  92. vector<Mat> images(num_images);
  93. vector<Size> full_img_sizes(num_images);
  94. double seam_work_aspect = 1;
  95. for (int i = 0; i < num_images; ++i)
  96. {
  97. full_img = imread(img_names[i]);
  98. full_img_sizes[i] = full_img.size();
  99. if (full_img.empty())
  100. {
  101. LOGLN("Can't open image " << img_names[i]);
  102. return -1;
  103. }
  104. if (work_megapix < 0)
  105. {
  106. img = full_img;
  107. work_scale = 1;
  108. is_work_scale_set = true;
  109. }
  110. else
  111. {
  112. if (!is_work_scale_set)
  113. {
  114. work_scale = min(1.0, sqrt(work_megapix * 1e6 / full_img.size().area()));
  115. is_work_scale_set = true;
  116. }
  117. resize(full_img, img, Size(), work_scale, work_scale);
  118. }
  119. if (!is_seam_scale_set)
  120. {
  121. seam_scale = min(1.0, sqrt(seam_megapix * 1e6 / full_img.size().area()));
  122. seam_work_aspect = seam_scale / work_scale;
  123. is_seam_scale_set = true;
  124. }
  125. (*finder)(img, features[i]);
  126. features[i].img_idx = i;
  127. LOGLN("Features in image #" << i+1 << ": " << features[i].keypoints.size());
  128. resize(full_img, img, Size(), seam_scale, seam_scale);
  129. images[i] = img.clone();
  130. }
  131. finder->collectGarbage();
  132. full_img.release();
  133. img.release();
  134. LOGLN("Finding features, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
  135. LOG("Pairwise matching");
  136. #if ENABLE_LOG
  137. t = getTickCount();
  138. #endif
  139. vector<MatchesInfo> pairwise_matches;
  140. BestOf2NearestMatcher matcher(try_gpu, match_conf);
  141. matcher(features, pairwise_matches);
  142. matcher.collectGarbage();
  143. LOGLN("Pairwise matching, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
  144. // Check if we should save matches graph
  145. if (save_graph)
  146. {
  147. LOGLN("Saving matches graph...");
  148. ofstream f(save_graph_to.c_str());
  149. f << matchesGraphAsString(img_names, pairwise_matches, conf_thresh);
  150. }
  151. // Leave only images we are sure are from the same panorama
  152. vector<int> indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh);
  153. vector<Mat> img_subset;
  154. vector<string> img_names_subset;
  155. vector<Size> full_img_sizes_subset;
  156. for (size_t i = 0; i < indices.size(); ++i)
  157. {
  158. img_names_subset.push_back(img_names[indices[i]]);
  159. img_subset.push_back(images[indices[i]]);
  160. full_img_sizes_subset.push_back(full_img_sizes[indices[i]]);
  161. }
  162. images = img_subset;
  163. img_names = img_names_subset;
  164. full_img_sizes = full_img_sizes_subset;
  165. // Check if we still have enough images
  166. num_images = static_cast<int>(img_names.size());
  167. if (num_images < 2)
  168. {
  169. LOGLN("Need more images");
  170. return -1;
  171. }
  172. HomographyBasedEstimator estimator;
  173. vector<CameraParams> cameras;
  174. estimator(features, pairwise_matches, cameras);
  175. for (size_t i = 0; i < cameras.size(); ++i)
  176. {
  177. Mat R;
  178. cameras[i].R.convertTo(R, CV_32F);
  179. cameras[i].R = R;
  180. LOGLN("Initial intrinsics #" << indices[i]+1 << ":\n" << cameras[i].K());
  181. }
  182. Ptr<detail::BundleAdjusterBase> adjuster;
  183. if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
  184. else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
  185. else
  186. {
  187. cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
  188. return -1;
  189. }
  190. adjuster->setConfThresh(conf_thresh);
  191. Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
  192. if (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
  193. if (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
  194. if (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
  195. if (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
  196. if (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
  197. adjuster->setRefinementMask(refine_mask);
  198. (*adjuster)(features, pairwise_matches, cameras);
  199. // Find median focal length
  200. vector<double> focals;
  201. for (size_t i = 0; i < cameras.size(); ++i)
  202. {
  203. LOGLN("Camera #" << indices[i]+1 << ":\n" << cameras[i].K());
  204. focals.push_back(cameras[i].focal);
  205. }
  206. sort(focals.begin(), focals.end());
  207. float warped_image_scale;
  208. if (focals.size() % 2 == 1)
  209. warped_image_scale = static_cast<float>(focals[focals.size() / 2]);
  210. else
  211. warped_image_scale = static_cast<float>(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f;
  212. if (do_wave_correct)
  213. {
  214. vector<Mat> rmats;
  215. for (size_t i = 0; i < cameras.size(); ++i)
  216. rmats.push_back(cameras[i].R.clone());
  217. waveCorrect(rmats, wave_correct);
  218. for (size_t i = 0; i < cameras.size(); ++i)
  219. cameras[i].R = rmats[i];
  220. }
  221. LOGLN("Warping images (auxiliary)... ");
  222. #if ENABLE_LOG
  223. t = getTickCount();
  224. #endif
  225. vector<Point> corners(num_images);
  226. vector<Mat> masks_warped(num_images);
  227. vector<Mat> images_warped(num_images);
  228. vector<Size> sizes(num_images);
  229. vector<Mat> masks(num_images);
  230. // Preapre images masks
  231. for (int i = 0; i < num_images; ++i)
  232. {
  233. masks[i].create(images[i].size(), CV_8U);
  234. masks[i].setTo(Scalar::all(255));
  235. }
  236. // Warp images and their masks
  237. Ptr<WarperCreator> warper_creator;
  238. #if defined(HAVE_OPENCV_GPU)
  239. if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
  240. {
  241. if (warp_type == "plane") warper_creator = new cv::PlaneWarperGpu();
  242. else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarperGpu();
  243. else if (warp_type == "spherical") warper_creator = new cv::SphericalWarperGpu();
  244. }
  245. else
  246. #endif
  247. {
  248. if (warp_type == "plane") warper_creator = new cv::PlaneWarper();
  249. else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper();
  250. else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper();
  251. else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
  252. else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
  253. else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
  254. else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
  255. else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
  256. else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
  257. else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
  258. else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
  259. else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
  260. else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
  261. else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
  262. else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
  263. }
  264. if (warper_creator.empty())
  265. {
  266. cout << "Can't create the following warper '" << warp_type << "'\n";
  267. return 1;
  268. }
  269. Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(warped_image_scale * seam_work_aspect));
  270. for (int i = 0; i < num_images; ++i)
  271. {
  272. Mat_<float> K;
  273. cameras[i].K().convertTo(K, CV_32F);
  274. float swa = (float)seam_work_aspect;
  275. K(0,0) *= swa; K(0,2) *= swa;
  276. K(1,1) *= swa; K(1,2) *= swa;
  277. corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
  278. sizes[i] = images_warped[i].size();
  279. warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
  280. }
  281. vector<Mat> images_warped_f(num_images);
  282. for (int i = 0; i < num_images; ++i)
  283. images_warped[i].convertTo(images_warped_f[i], CV_32F);
  284. LOGLN("Warping images, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
  285. Ptr<ExposureCompensator> compensator = ExposureCompensator::createDefault(expos_comp_type);
  286. compensator->feed(corners, images_warped, masks_warped);
  287. Ptr<SeamFinder> seam_finder;
  288. if (seam_find_type == "no")
  289. seam_finder = new detail::NoSeamFinder();
  290. else if (seam_find_type == "voronoi")
  291. seam_finder = new detail::VoronoiSeamFinder();
  292. else if (seam_find_type == "gc_color")
  293. {
  294. #if defined(HAVE_OPENCV_GPU)
  295. if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
  296. seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR);
  297. else
  298. #endif
  299. seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR);
  300. }
  301. else if (seam_find_type == "gc_colorgrad")
  302. {
  303. #if defined(HAVE_OPENCV_GPU)
  304. if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
  305. seam_finder = new detail::GraphCutSeamFinderGpu(GraphCutSeamFinderBase::COST_COLOR_GRAD);
  306. else
  307. #endif
  308. seam_finder = new detail::GraphCutSeamFinder(GraphCutSeamFinderBase::COST_COLOR_GRAD);
  309. }
  310. else if (seam_find_type == "dp_color")
  311. seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR);
  312. else if (seam_find_type == "dp_colorgrad")
  313. seam_finder = new detail::DpSeamFinder(DpSeamFinder::COLOR_GRAD);
  314. if (seam_finder.empty())
  315. {
  316. cout << "Can't create the following seam finder '" << seam_find_type << "'\n";
  317. return 1;
  318. }
  319. seam_finder->find(images_warped_f, corners, masks_warped);
  320. // Release unused memory
  321. images.clear();
  322. images_warped.clear();
  323. images_warped_f.clear();
  324. masks.clear();
  325. LOGLN("Compositing...");
  326. #if ENABLE_LOG
  327. t = getTickCount();
  328. #endif
  329. Mat img_warped, img_warped_s;
  330. Mat dilated_mask, seam_mask, mask, mask_warped;
  331. Ptr<Blender> blender;
  332. //double compose_seam_aspect = 1;
  333. double compose_work_aspect = 1;
  334. for (int img_idx = 0; img_idx < num_images; ++img_idx)
  335. {
  336. LOGLN("Compositing image #" << indices[img_idx]+1);
  337. // Read image and resize it if necessary
  338. full_img = imread(img_names[img_idx]);
  339. if (!is_compose_scale_set)
  340. {
  341. if (compose_megapix > 0)
  342. compose_scale = min(1.0, sqrt(compose_megapix * 1e6 / full_img.size().area()));
  343. is_compose_scale_set = true;
  344. // Compute relative scales
  345. //compose_seam_aspect = compose_scale / seam_scale;
  346. compose_work_aspect = compose_scale / work_scale;
  347. // Update warped image scale
  348. warped_image_scale *= static_cast<float>(compose_work_aspect);
  349. warper = warper_creator->create(warped_image_scale);
  350. // Update corners and sizes
  351. for (int i = 0; i < num_images; ++i)
  352. {
  353. // Update intrinsics
  354. cameras[i].focal *= compose_work_aspect;
  355. cameras[i].ppx *= compose_work_aspect;
  356. cameras[i].ppy *= compose_work_aspect;
  357. // Update corner and size
  358. Size sz = full_img_sizes[i];
  359. if (std::abs(compose_scale - 1) > 1e-1)
  360. {
  361. sz.width = cvRound(full_img_sizes[i].width * compose_scale);
  362. sz.height = cvRound(full_img_sizes[i].height * compose_scale);
  363. }
  364. Mat K;
  365. cameras[i].K().convertTo(K, CV_32F);
  366. Rect roi = warper->warpRoi(sz, K, cameras[i].R);
  367. corners[i] = roi.tl();
  368. sizes[i] = roi.size();
  369. }
  370. }
  371. if (abs(compose_scale - 1) > 1e-1)
  372. resize(full_img, img, Size(), compose_scale, compose_scale);
  373. else
  374. img = full_img;
  375. full_img.release();
  376. Size img_size = img.size();
  377. Mat K;
  378. cameras[img_idx].K().convertTo(K, CV_32F);
  379. // Warp the current image
  380. warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped);
  381. // Warp the current image mask
  382. mask.create(img_size, CV_8U);
  383. mask.setTo(Scalar::all(255));
  384. warper->warp(mask, K, cameras[img_idx].R, INTER_NEAREST, BORDER_CONSTANT, mask_warped);
  385. // Compensate exposure
  386. compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped);
  387. img_warped.convertTo(img_warped_s, CV_16S);
  388. img_warped.release();
  389. img.release();
  390. mask.release();
  391. dilate(masks_warped[img_idx], dilated_mask, Mat());
  392. resize(dilated_mask, seam_mask, mask_warped.size());
  393. mask_warped = seam_mask & mask_warped;
  394. if (blender.empty())
  395. {
  396. blender = Blender::createDefault(blend_type, try_gpu);
  397. Size dst_sz = resultRoi(corners, sizes).size();
  398. float blend_width = sqrt(static_cast<float>(dst_sz.area())) * blend_strength / 100.f;
  399. if (blend_width < 1.f)
  400. blender = Blender::createDefault(Blender::NO, try_gpu);
  401. else if (blend_type == Blender::MULTI_BAND)
  402. {
  403. MultiBandBlender* mb = dynamic_cast<MultiBandBlender*>(static_cast<Blender*>(blender));
  404. mb->setNumBands(static_cast<int>(ceil(log(blend_width)/log(2.)) - 1.));
  405. LOGLN("Multi-band blender, number of bands: " << mb->numBands());
  406. }
  407. else if (blend_type == Blender::FEATHER)
  408. {
  409. FeatherBlender* fb = dynamic_cast<FeatherBlender*>(static_cast<Blender*>(blender));
  410. fb->setSharpness(1.f/blend_width);
  411. LOGLN("Feather blender, sharpness: " << fb->sharpness());
  412. }
  413. blender->prepare(corners, sizes);
  414. }
  415. // Blend the current image
  416. blender->feed(img_warped_s, mask_warped, corners[img_idx]);
  417. }
  418. Mat result, result_mask;
  419. blender->blend(result, result_mask);
  420. LOGLN("Compositing, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
  421. imwrite(result_name, result);
  422. result.convertTo(result,CV_8UC1);
  423. imshow("stitch",result);
  424. ttt = ((double)getTickCount() - ttt) / getTickFrequency();
  425. cout << "总的拼接时间:" << ttt << endl;
  426. waitKey(0);
  427. LOGLN("Finished, total time: " << ((getTickCount() - app_start_time) / getTickFrequency()) << " sec");
  428. return 0;
  429. }

效果:

论文源码关注微信公众号:“图像算法”或者微信搜索账号imalg_cn关注公众号

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/81397
推荐阅读
相关标签
  

闽ICP备14008679号