OpenCV  4.10.0
开源计算机视觉库
加载中...
搜索中...
未找到匹配项
samples/cpp/stitching_detailed.cpp

图像拼接的详细示例

#include <iostream>
#include <fstream>
#include <string>
#include "opencv2/opencv_modules.hpp"
#ifdef HAVE_OPENCV_XFEATURES2D
#endif
#define ENABLE_LOG 1
#define LOG(msg) std::cout << msg
#define LOGLN(msg) std::cout << msg << std::endl
using namespace std;
using namespace cv;
using namespace cv::detail;
static void printUsage(char** argv)
{
cout <<
"旋转模型图像拼接器。\n\n"
<< argv[0] << " img1 img2 [...imgN] [flags]\n\n"
"标志:\n"
" --preview\n"
" 在预览模式下运行拼接。比普通模式速度更快,\n"
" 但输出图像的分辨率会较低。\n"
" --try_cuda (yes|no)\n"
" 尝试使用 CUDA。默认值为 'no'。所有默认值\n"
" 用于 CPU 模式。\n"
"\n运动估计标志:\n"
" --work_megapix <float>\n"
" 图像配准步骤的分辨率。默认值为 0.6 Mpx。\n"
" --features (surf|orb|sift|akaze)\n"
" 用于图像匹配的特征类型。\n"
" 默认情况下,如果可用,则为 surf,否则为 orb。\n"
" --matcher (homography|affine)\n"
" 用于成对图像匹配的匹配器。\n"
" --estimator (homography|affine)\n"
" 用于变换估计的估计器类型。\n"
" --match_conf <float>\n"
" 特征匹配步骤的置信度。默认情况下,surf 为 0.65,orb 为 0.3。\n"
" --conf_thresh <float>\n"
" 两张图像来自同一全景的置信度阈值。\n"
" 默认值为 1.0。\n"
" --ba (no|reproj|ray|affine)\n"
" 捆绑调整成本函数。默认值为 ray。\n"
" --ba_refine_mask (mask)\n"
" 设置捆绑调整的优化掩码。它类似于 'x_xxx',\n"
" 其中 'x' 表示优化相应的参数,' _ ' 表示不\n"
" 优化一个,并且具有以下格式:\n"
" <fx><skew><ppx><aspect><ppy>。默认掩码为 'xxxxx'。如果捆绑\n"
" 调整不支持选定参数的估计,则\n"
" 相应的标志将被忽略。\n"
" --wave_correct (no|horiz|vert)\n"
" 执行波浪效应校正。默认值为 'horiz'。\n"
" --save_graph <file_name>\n"
" 将以 DOT 语言表示的匹配图保存到 <file_name> 文件中。\n"
" 标签描述:Nm 是匹配次数,Ni 是内点次数,\n"
" C 是置信度。\n"
"\n合成标志:\n"
" --warp (affine|plane|cylindrical|spherical|fisheye|stereographic|compressedPlaneA2B1|compressedPlaneA1.5B1|compressedPlanePortraitA2B1|compressedPlanePortraitA1.5B1|paniniA2B1|paniniA1.5B1|paniniPortraitA2B1|paniniPortraitA1.5B1|mercator|transverseMercator)\n"
" 变形表面类型。默认值为 'spherical'。\n"
" --seam_megapix <float>\n"
" 接缝估计步骤的分辨率。默认值为 0.1 Mpx。\n"
" --seam (no|voronoi|gc_color|gc_colorgrad)\n"
" 接缝估计方法。默认值为 'gc_color'。\n"
" --compose_megapix <float>\n"
" 合成步骤的分辨率。对于原始分辨率使用 -1。\n"
" 默认值为 -1。\n"
" --expos_comp (no|gain|gain_blocks|channels|channels_blocks)\n"
" 曝光补偿方法。默认值为 'gain_blocks'。\n"
" --expos_comp_nr_feeds <int>\n"
" 曝光补偿馈送次数。默认值为 1。\n"
" --expos_comp_nr_filtering <int>\n"
" 曝光补偿增益的滤波迭代次数。\n"
" 仅在使用块曝光补偿方法时使用。\n"
" 默认值为 2。\n"
" --expos_comp_block_size <int>\n"
" 曝光补偿器使用的像素块大小。\n"
" 仅在使用块曝光补偿方法时使用。\n"
" 默认值为 32。\n"
" --blend (no|feather|multiband)\n"
" 混合方法。默认值为 'multiband'。\n"
" --blend_strength <float>\n"
" 混合强度,范围为 [0,100]。默认值为 5。\n"
" --output <result_img>\n"
" 默认值为 'result.jpg'。\n"
" --timelapse (as_is|crop) \n"
" 将扭曲后的图像分别输出为延时电影的帧,在输入文件名之前添加 'fixed_'。\n"
" --rangewidth <int>\n"
" 使用 range_width 来限制要匹配的图像数量。\n";
}
// 默认命令行参数
vector<String> img_names;
bool preview = false;
bool try_cuda = false;
double work_megapix = 0.6;
double seam_megapix = 0.1;
double compose_megapix = -1;
float conf_thresh = 1.f;
#ifdef HAVE_OPENCV_XFEATURES2D
string features_type = "surf";
float match_conf = 0.65f;
#else
string features_type = "orb";
float match_conf = 0.3f;
#endif
string matcher_type = "homography";
string estimator_type = "homography";
string ba_cost_func = "ray";
string ba_refine_mask = "xxxxx";
bool do_wave_correct = true;
WaveCorrectKind wave_correct = detail::WAVE_CORRECT_HORIZ;
bool save_graph = false;
std::string save_graph_to;
string warp_type = "spherical";
int expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
int expos_comp_nr_feeds = 1;
int expos_comp_nr_filtering = 2;
int expos_comp_block_size = 32;
string seam_find_type = "gc_color";
int blend_type = Blender::MULTI_BAND;
int timelapse_type = Timelapser::AS_IS;
float blend_strength = 5;
string result_name = "result.jpg";
bool timelapse = false;
int range_width = -1;
static int parseCmdArgs(int argc, char** argv)
{
if (argc == 1)
{
printUsage(argv);
return -1; -1;
}
for (int i = 1; i < argc; ++i)
{
if (string(argv[i]) == "--help" || string(argv[i]) == "/?")
{
printUsage(argv);
return -1; -1;
}
printUsage(argv);
{
else if (string(argv[i]) == "--preview")
}
preview = true;
{
else if (string(argv[i]) == "--try_cuda")
if (string(argv[i + 1]) == "no")
try_cuda = false;
else if (string(argv[i + 1]) == "yes")
try_cuda = true;
{
else
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
i++;
{
else if (string(argv[i]) == "--work_megapix")
cout << "错误的 --try_cuda 标志值\n";
}
work_megapix = atof(argv[i + 1]);
{
else if (string(argv[i]) == "--seam_megapix")
cout << "错误的 --try_cuda 标志值\n";
}
seam_megapix = atof(argv[i + 1]);
{
else if (string(argv[i]) == "--compose_megapix")
cout << "错误的 --try_cuda 标志值\n";
}
compose_megapix = atof(argv[i + 1]);
{
else if (string(argv[i]) == "--result")
cout << "错误的 --try_cuda 标志值\n";
}
result_name = argv[i + 1];
{
else if (string(argv[i]) == "--features")
features_type = argv[i + 1];
if (string(features_type) == "orb")
cout << "错误的 --try_cuda 标志值\n";
}
match_conf = 0.3f;
{
else if (string(argv[i]) == "--matcher")
if (string(argv[i + 1]) == "homography" || string(argv[i + 1]) == "affine")
try_cuda = true;
{
matcher_type = argv[i + 1];
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else
{
else if (string(argv[i]) == "--matcher")
cout << "错误的 --matcher 标志值\n";
try_cuda = true;
{
else if (string(argv[i]) == "--estimator")
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
estimator_type = argv[i + 1];
{
else
cout << "错误的 --try_cuda 标志值\n";
}
cout << "错误的 --estimator 标志值\n";
{
else if (string(argv[i]) == "--match_conf")
cout << "错误的 --try_cuda 标志值\n";
}
match_conf = static_cast<float>(atof(argv[i + 1]));
{
else if (string(argv[i]) == "--conf_thresh")
cout << "错误的 --try_cuda 标志值\n";
}
conf_thresh = static_cast<float>(atof(argv[i + 1]));
{
else if (string(argv[i]) == "--ba")
ba_cost_func = argv[i + 1];
{
else if (string(argv[i]) == "--ba_refine_mask")
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
ba_refine_mask = argv[i + 1];
{
else if (string(argv[i]) == "--try_cuda")
if (ba_refine_mask.size() != 5)
cout << "优化掩码长度不正确。\n";
{
else if (string(argv[i]) == "--wave_correct")
do_wave_correct = false;
}
else if (string(argv[i + 1]) == "horiz")
{
else if (string(argv[i]) == "--wave_correct")
do_wave_correct = true;
}
try_cuda = true;
{
cout << "错误的 --wave_correct 标志值\n";
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--save_graph")
{
save_graph = true;
save_graph_to = argv[i + 1];
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--warp")
{
warp_type = string(argv[i + 1]);
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--expos_comp")
{
else if (string(argv[i]) == "--try_cuda")
expos_comp_type = ExposureCompensator::NO;
else if (string(argv[i + 1]) == "gain")
expos_comp_type = ExposureCompensator::GAIN;
else if (string(argv[i + 1]) == "gain_blocks")
expos_comp_type = ExposureCompensator::GAIN_BLOCKS;
else if (string(argv[i + 1]) == "channels")
expos_comp_type = ExposureCompensator::CHANNELS;
else if (string(argv[i + 1]) == "channels_blocks")
expos_comp_type = ExposureCompensator::CHANNELS_BLOCKS;
try_cuda = true;
{
cout << "错误的曝光补偿方法\n";
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--expos_comp_nr_feeds")
{
expos_comp_nr_feeds = atoi(argv[i + 1]);
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--expos_comp_nr_filtering")
{
expos_comp_nr_filtering = atoi(argv[i + 1]);
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--expos_comp_block_size")
{
expos_comp_block_size = atoi(argv[i + 1]);
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--seam")
{
if (string(argv[i + 1]) == "no" ||
string(argv[i + 1]) == "voronoi" ||
string(argv[i + 1]) == "gc_color" ||
string(argv[i + 1]) == "gc_colorgrad" ||
string(argv[i + 1]) == "dp_color" ||
string(argv[i + 1]) == "dp_colorgrad")
seam_find_type = argv[i + 1];
try_cuda = true;
{
cout << "错误的接缝查找方法\n";
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--blend")
{
else if (string(argv[i]) == "--try_cuda")
blend_type = Blender::NO;
else if (string(argv[i + 1]) == "feather")
blend_type = Blender::FEATHER;
else if (string(argv[i + 1]) == "multiband")
blend_type = Blender::MULTI_BAND;
try_cuda = true;
{
cout << "错误的混合方法\n";
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--timelapse")
{
timelapse = true;
if (string(argv[i + 1]) == "as_is")
timelapse_type = Timelapser::AS_IS;
else if (string(argv[i + 1]) == "crop")
timelapse_type = Timelapser::CROP;
try_cuda = true;
{
cout << "错误的延时摄影方法\n";
return -1; -1;
}
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--rangewidth")
{
range_width = atoi(argv[i + 1]);
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--blend_strength")
{
blend_strength = static_cast<float>(atof(argv[i + 1]));
cout << "错误的 --try_cuda 标志值\n";
}
else if (string(argv[i]) == "--output")
{
else if (string(argv[i]) == "--result")
cout << "错误的 --try_cuda 标志值\n";
}
try_cuda = true;
img_names.push_back(argv[i]);
}
if (preview)
{
compose_megapix = 0.6;
}
return -1; 0;
}
int main(int argc, char* argv[])
{
#if ENABLE_LOG
int64 app_start_time = getTickCount();
#endif
#if 0
#endif
int retval = parseCmdArgs(argc, argv);
if (retval)
return retval;
// 检查是否拥有足够多的图像
int num_images = static_cast<int>(img_names.size());
if (num_images < 2)
{
LOGLN("需要更多图像");
return -1; -1;
}
double work_scale = 1, seam_scale = 1, compose_scale = 1;
bool is_work_scale_set = false, is_seam_scale_set = false, is_compose_scale_set = false;
LOGLN("正在查找特征...");
#if ENABLE_LOG
#endif
if (features_type == "orb")
{
finder = ORB::create();
}
else if (features_type == "akaze")
{
finder = AKAZE::create();
}
#ifdef HAVE_OPENCV_XFEATURES2D
else if (features_type == "surf")
{
finder = xfeatures2d::SURF::create();
}
#endif
else if (features_type == "sift")
{
finder = SIFT::create();
}
try_cuda = true;
{
cout << "未知的 2D 特征类型: '" << features_type << "'.\n";
return -1; -1;
}
Mat full_img, img;
vector<ImageFeatures> features(num_images);
vector<Mat> images(num_images);
vector<Size> full_img_sizes(num_images);
double seam_work_aspect = 1;
for (int i = 0; i < num_images; ++i)
{
full_img = imread(samples::findFile(img_names[i]));
full_img_sizes[i] = full_img.size();
if (full_img.empty())
{
LOGLN("无法打开图像 " << img_names[i]);
return -1; -1;
}
if (work_megapix < 0)
{
img = full_img;
work_scale = 1;
is_work_scale_set = true;
}
try_cuda = true;
{
if (!is_work_scale_set)
{
work_scale = min(1.0, sqrt(work_megapix * 1e6 / full_img.size().area()));
is_work_scale_set = true;
}
resize(full_img, img, Size(), work_scale, work_scale, INTER_LINEAR_EXACT);
}
if (!is_seam_scale_set)
{
seam_scale = min(1.0, sqrt(seam_megapix * 1e6 / full_img.size().area()));
seam_work_aspect = seam_scale / work_scale;
is_seam_scale_set = true;
}
computeImageFeatures(finder, img, features[i]);
features[i].img_idx = i;
LOGLN("图像 #" << i+1 << " 中的特征: " << features[i].keypoints.size());
resize(full_img, img, Size(), seam_scale, seam_scale, INTER_LINEAR_EXACT);
images[i] = img.clone();
}
full_img.release();
img.release();
LOGLN("查找特征的时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
LOG("成对匹配");
#if ENABLE_LOG
#endif
vector<MatchesInfo> pairwise_matches;
if (matcher_type == "affine")
matcher = makePtr<AffineBestOf2NearestMatcher>(false, try_cuda, match_conf);
else if (range_width==-1)
matcher = makePtr<BestOf2NearestMatcher>(try_cuda, match_conf);
try_cuda = true;
matcher = makePtr<BestOf2NearestRangeMatcher>(range_width, try_cuda, match_conf);
(*matcher)(features, pairwise_matches);
matcher->collectGarbage();
LOGLN("成对匹配的时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
// 检查是否需要保存匹配图
if (save_graph)
{
LOGLN("正在保存匹配图...");
ofstream f(save_graph_to.c_str());
f << matchesGraphAsString(img_names, pairwise_matches, conf_thresh);
}
// 只保留我们确定来自同一全景图的图像
vector<int> indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh);
vector<Mat> img_subset;
vector<String> img_names_subset;
vector<Size> full_img_sizes_subset;
for (size_t i = 0; i < indices.size(); ++i)
{
img_names_subset.push_back(img_names[indices[i]]);
img_subset.push_back(images[indices[i]]);
full_img_sizes_subset.push_back(full_img_sizes[indices[i]]);
}
images = img_subset;
img_names = img_names_subset;
full_img_sizes = full_img_sizes_subset;
// 检查是否还有足够多的图像
num_images = static_cast<int>(img_names.size());
if (num_images < 2)
{
LOGLN("需要更多图像");
return -1; -1;
}
Ptr<Estimator> estimator;
if (estimator_type == "affine")
estimator = makePtr<AffineBasedEstimator>();
try_cuda = true;
estimator = makePtr<HomographyBasedEstimator>();
vector<CameraParams> cameras;
if (!(*estimator)(features, pairwise_matches, cameras))
{
cout << "单应性估计失败。\n";
return -1; -1;
}
for (size_t i = 0; i < cameras.size(); ++i)
{
Mat R;
cameras[i].R.convertTo(R, CV_32F);
cameras[i].R = R;
LOGLN("初始相机内参 #" << indices[i]+1 << ":\nK:\n" << cameras[i].K() << "\nR:\n" << cameras[i].R);
}
如果 (ba_cost_func == "reproj") adjuster = makePtr<detail::BundleAdjusterReproj>();
否则如果 (ba_cost_func == "ray") adjuster = makePtr<detail::BundleAdjusterRay>();
否则如果 (ba_cost_func == "affine") adjuster = makePtr<detail::BundleAdjusterAffinePartial>();
否则如果 (ba_cost_func == "no") adjuster = makePtr<NoBundleAdjuster>();
try_cuda = true;
{
cout << "未知的捆绑调整成本函数: '" << ba_cost_func << "'.\n";
return -1; -1;
}
adjuster->setConfThresh(conf_thresh);
Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
如果 (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
如果 (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
如果 (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
如果 (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
如果 (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
adjuster->setRefinementMask(refine_mask);
如果 (!(*adjuster)(features, pairwise_matches, cameras))
{
cout << "相机参数调整失败。\n";
return -1; -1;
}
// 查找中值焦距
vector<double> focals;
for (size_t i = 0; i < cameras.size(); ++i)
{
LOGLN("相机 #" << indices[i]+1 << ":\nK:\n" << cameras[i].K() << "\nR:\n" << cameras[i].R);
focals.push_back(cameras[i].focal);
}
sort(focals.begin(), focals.end());
float warped_image_scale;
如果 (focals.size() % 2 == 1)
warped_image_scale = static_cast<float>(focals[focals.size() / 2]);
try_cuda = true;
warped_image_scale = static_cast<float>(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f;
如果 (do_wave_correct)
{
vector<Mat> rmats;
for (size_t i = 0; i < cameras.size(); ++i)
rmats.push_back(cameras[i].R.clone());
waveCorrect(rmats, wave_correct);
for (size_t i = 0; i < cameras.size(); ++i)
cameras[i].R = rmats[i];
}
LOGLN("扭曲图像(辅助)... ");
#if ENABLE_LOG
#endif
vector<Point> corners(num_images);
vector<UMat> masks_warped(num_images);
vector<UMat> images_warped(num_images);
vector<Size> sizes(num_images);
vector<UMat> masks(num_images);
// 准备图像蒙版
for (int i = 0; i < num_images; ++i)
{
masks[i].create(images[i].size(), CV_8U);
masks[i].setTo(Scalar::all(255));
}
// 扭曲图像及其蒙版
Ptr<WarperCreator> warper_creator;
#ifdef HAVE_OPENCV_CUDAWARPING
如果 (try_cuda && cuda::getCudaEnabledDeviceCount() > 0)
{
如果 (warp_type == "plane")
warper_creator = makePtr<cv::PlaneWarperGpu>();
否则如果 (warp_type == "cylindrical")
warper_creator = makePtr<cv::CylindricalWarperGpu>();
否则如果 (warp_type == "spherical")
warper_creator = makePtr<cv::SphericalWarperGpu>();
}
try_cuda = true;
#endif
{
如果 (warp_type == "plane")
warper_creator = makePtr<cv::PlaneWarper>();
否则如果 (warp_type == "affine")
warper_creator = makePtr<cv::AffineWarper>();
否则如果 (warp_type == "cylindrical")
warper_creator = makePtr<cv::CylindricalWarper>();
否则如果 (warp_type == "spherical")
warper_creator = makePtr<cv::SphericalWarper>();
否则如果 (warp_type == "fisheye")
warper_creator = makePtr<cv::FisheyeWarper>();
否则如果 (warp_type == "stereographic")
warper_creator = makePtr<cv::StereographicWarper>();
否则如果 (warp_type == "compressedPlaneA2B1")
warper_creator = makePtr<cv::CompressedRectilinearWarper>(2.0f, 1.0f);
否则如果 (warp_type == "compressedPlaneA1.5B1")
warper_creator = makePtr<cv::CompressedRectilinearWarper>(1.5f, 1.0f);
否则如果 (warp_type == "compressedPlanePortraitA2B1")
warper_creator = makePtr<cv::CompressedRectilinearPortraitWarper>(2.0f, 1.0f);
否则如果 (warp_type == "compressedPlanePortraitA1.5B1")
warper_creator = makePtr<cv::CompressedRectilinearPortraitWarper>(1.5f, 1.0f);
否则如果 (warp_type == "paniniA2B1")
warper_creator = makePtr<cv::PaniniWarper>(2.0f, 1.0f);
否则如果 (warp_type == "paniniA1.5B1")
warper_creator = makePtr<cv::PaniniWarper>(1.5f, 1.0f);
否则如果 (warp_type == "paniniPortraitA2B1")
warper_creator = makePtr<cv::PaniniPortraitWarper>(2.0f, 1.0f);
否则如果 (warp_type == "paniniPortraitA1.5B1")
warper_creator = makePtr<cv::PaniniPortraitWarper>(1.5f, 1.0f);
否则如果 (warp_type == "mercator")
warper_creator = makePtr<cv::MercatorWarper>();
否则如果 (warp_type == "transverseMercator")
warper_creator = makePtr<cv::TransverseMercatorWarper>();
}
如果 (!warper_creator)
{
cout << "无法创建以下扭曲器 '" << warp_type << "'\n";
return -1; 1;
}
Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(warped_image_scale * seam_work_aspect));
for (int i = 0; i < num_images; ++i)
{
cameras[i].K().convertTo(K, CV_32F);
float swa = (float)seam_work_aspect;
K(0,0) *= swa; K(0,2) *= swa;
K(1,1) *= swa; K(1,2) *= swa;
corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
sizes[i] = images_warped[i].size();
warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
}
vector<UMat> images_warped_f(num_images);
for (int i = 0; i < num_images; ++i)
images_warped[i].convertTo(images_warped_f[i], CV_32F);
LOGLN("扭曲图像,时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
LOGLN("补偿曝光... ");
#if ENABLE_LOG
#endif
Ptr<ExposureCompensator> compensator = ExposureCompensator::createDefault(expos_comp_type);
如果 (dynamic_cast<GainCompensator*>(compensator.get()))
{
GainCompensator* gcompensator = dynamic_cast<GainCompensator*>(compensator.get());
gcompensator->setNrFeeds(expos_comp_nr_feeds);
}
如果 (dynamic_cast<ChannelsCompensator*>(compensator.get()))
{
ChannelsCompensator* ccompensator = dynamic_cast<ChannelsCompensator*>(compensator.get());
ccompensator->setNrFeeds(expos_comp_nr_feeds);
}
如果 (dynamic_cast<BlocksCompensator*>(compensator.get()))
{
BlocksCompensator* bcompensator = dynamic_cast<BlocksCompensator*>(compensator.get());
bcompensator->setNrFeeds(expos_comp_nr_feeds);
bcompensator->setNrGainsFilteringIterations(expos_comp_nr_filtering);
bcompensator->setBlockSize(expos_comp_block_size, expos_comp_block_size);
}
compensator->feed(corners, images_warped, masks_warped);
LOGLN("补偿曝光,时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
LOGLN("寻找接缝... ");
#if ENABLE_LOG
#endif
Ptr<SeamFinder> seam_finder;
如果 (seam_find_type == "no")
seam_finder = makePtr<detail::NoSeamFinder>();
否则如果 (seam_find_type == "voronoi")
seam_finder = makePtr<detail::VoronoiSeamFinder>();
否则如果 (seam_find_type == "gc_color")
{
#ifdef HAVE_OPENCV_CUDALEGACY
如果 (try_cuda && cuda::getCudaEnabledDeviceCount() > 0)
seam_finder = makePtr<detail::GraphCutSeamFinderGpu>(GraphCutSeamFinderBase::COST_COLOR);
try_cuda = true;
#endif
seam_finder = makePtr<detail::GraphCutSeamFinder>(GraphCutSeamFinderBase::COST_COLOR);
}
否则如果 (seam_find_type == "gc_colorgrad")
{
#ifdef HAVE_OPENCV_CUDALEGACY
如果 (try_cuda && cuda::getCudaEnabledDeviceCount() > 0)
seam_finder = makePtr<detail::GraphCutSeamFinderGpu>(GraphCutSeamFinderBase::COST_COLOR_GRAD);
try_cuda = true;
#endif
seam_finder = makePtr<detail::GraphCutSeamFinder>(GraphCutSeamFinderBase::COST_COLOR_GRAD);
}
否则如果 (seam_find_type == "dp_color")
seam_finder = makePtr<detail::DpSeamFinder>(DpSeamFinder::COLOR);
否则如果 (seam_find_type == "dp_colorgrad")
seam_finder = makePtr<detail::DpSeamFinder>(DpSeamFinder::COLOR_GRAD);
如果 (!seam_finder)
{
cout << "无法创建以下接缝查找器 '" << seam_find_type << "'\n";
return -1; 1;
}
seam_finder->find(images_warped_f, corners, masks_warped);
LOGLN("寻找接缝,时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
// 释放未使用的内存
images.clear();
images_warped.clear();
images_warped_f.clear();
masks.clear();
LOGLN("合成... ");
#if ENABLE_LOG
#endif
Mat img_warped, img_warped_s;
Mat dilated_mask, seam_mask, mask, mask_warped;
Ptr<Blender> blender;
Ptr<Timelapser> timelapser;
//double compose_seam_aspect = 1;
double compose_work_aspect = 1;
for (int img_idx = 0; img_idx < num_images; ++img_idx)
{
LOGLN("正在合成图像 #" << indices[img_idx]+1);
// 读取图像,如果需要则调整大小
full_img = imread(samples::findFile(img_names[img_idx]));
if (!is_compose_scale_set)
{
if (compose_megapix > 0)
compose_scale = min(1.0, sqrt(compose_megapix * 1e6 / full_img.size().area()));
is_compose_scale_set = true;
// 计算相对比例
//compose_seam_aspect = compose_scale / seam_scale;
compose_work_aspect = compose_scale / work_scale;
// 更新扭曲图像比例
warped_image_scale *= static_cast<float>(compose_work_aspect);
warper = warper_creator->create(warped_image_scale);
// 更新角点和尺寸
for (int i = 0; i < num_images; ++i)
{
// 更新内参
cameras[i].focal *= compose_work_aspect;
cameras[i].ppx *= compose_work_aspect;
cameras[i].ppy *= compose_work_aspect;
// 更新角点和尺寸
Size sz = full_img_sizes[i];
if (std::abs(compose_scale - 1) > 1e-1)
{
sz.width = cvRound(full_img_sizes[i].width * compose_scale);
sz.height = cvRound(full_img_sizes[i].height * compose_scale);
}
Mat K;
cameras[i].K().convertTo(K, CV_32F);
Rect roi = warper->warpRoi(sz, K, cameras[i].R);
corners[i] = roi.tl();
sizes[i] = roi.size();
}
}
if (abs(compose_scale - 1) > 1e-1)
resize(full_img, img, Size(), compose_scale, compose_scale, INTER_LINEAR_EXACT);
try_cuda = true;
img = full_img;
full_img.release();
Size img_size = img.size();
Mat K;
cameras[img_idx].K().convertTo(K, CV_32F);
// 扭曲当前图像
warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped);
// 扭曲当前图像掩码
mask.create(img_size, CV_8U);
mask.setTo(Scalar::all(255));
warper->warp(mask, K, cameras[img_idx].R, INTER_NEAREST, BORDER_CONSTANT, mask_warped);
// 补偿曝光
compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped);
img_warped.convertTo(img_warped_s, CV_16S);
img_warped.release();
img.release();
mask.release();
dilate(masks_warped[img_idx], dilated_mask, Mat());
resize(dilated_mask, seam_mask, mask_warped.size(), 0, 0, INTER_LINEAR_EXACT);
mask_warped = seam_mask & mask_warped;
if (!blender && !timelapse)
{
blender = Blender::createDefault(blend_type, try_cuda);
Size dst_sz = resultRoi(corners, sizes).size();
float blend_width = sqrt(static_cast<float>(dst_sz.area())) * blend_strength / 100.f;
if (blend_width < 1.f)
blender = Blender::createDefault(Blender::NO, try_cuda);
else if (blend_type == Blender::MULTI_BAND)
{
MultiBandBlender* mb = dynamic_cast<MultiBandBlender*>(blender.get());
mb->setNumBands(static_cast<int>(ceil(log(blend_width)/log(2.)) - 1.));
LOGLN("多波段混合器,波段数量: " << mb->numBands());
}
else if (blend_type == Blender::FEATHER)
{
FeatherBlender* fb = dynamic_cast<FeatherBlender*>(blender.get());
fb->setSharpness(1.f/blend_width);
LOGLN("羽毛混合器,锐度: " << fb->sharpness());
}
blender->prepare(corners, sizes);
}
else if (!timelapser && timelapse)
{
timelapser = Timelapser::createDefault(timelapse_type);
timelapser->initialize(corners, sizes);
}
// 混合当前图像
if (timelapse)
{
timelapser->process(img_warped_s, Mat::ones(img_warped_s.size(), CV_8UC1), corners[img_idx]);
String fixedFileName;
size_t pos_s = String(img_names[img_idx]).find_last_of("/\\");
if (pos_s == String::npos)
{
fixedFileName = "fixed_" + img_names[img_idx];
}
try_cuda = true;
{
fixedFileName = "fixed_" + String(img_names[img_idx]).substr(pos_s + 1, String(img_names[img_idx]).length() - pos_s);
}
imwrite(fixedFileName, timelapser->getDst());
}
try_cuda = true;
{
blender->feed(img_warped_s, mask_warped, corners[img_idx]);
}
}
if (!timelapse)
{
Mat result, result_mask;
blender->blend(result, result_mask);
LOGLN("合成中,时间: " << ((getTickCount() - t) / getTickFrequency()) << " 秒");
imwrite(result_name, result);
}
LOGLN("完成,总时间: " << ((getTickCount() - app_start_time) / getTickFrequency()) << " 秒");
return -1; 0;
}
从 Mat 派生的模板矩阵类。
定义 mat.hpp:2230
n 维密集数组类
定义 mat.hpp:812
CV_NODISCARD_STD Mat clone() const
创建数组及其底层数据的完整副本。
MatSize size
定义 mat.hpp:2160
bool empty() const
如果数组没有元素,则返回 true。
void convertTo(OutputArray m, int rtype, double alpha=1, double beta=0) const
将数组转换为另一种数据类型,并可选缩放。
void release()
减少引用计数,并在需要时释放矩阵。
用于二维矩形的模板类。
定义 types.hpp:444
Point_< _Tp > tl() const
左上角
Size_< _Tp > size() const
矩形的尺寸(宽度,高度)
用于指定图像或矩形尺寸的模板类。
定义 types.hpp:335
_Tp height
高度
定义 types.hpp:363
_Tp area() const
面积(宽度 * 高度)
_Tp width
宽度
定义 types.hpp:362
通过调整图像块来尝试消除曝光相关伪影的曝光补偿器。
定义 exposure_compensate.hpp:170
void setBlockSize(int width, int height)
定义 exposure_compensate.hpp:182
void setNrFeeds(int nr_feeds)
定义 exposure_compensate.hpp:178
void setNrGainsFilteringIterations(int nr_iterations)
定义 exposure_compensate.hpp:185
尝试通过调整图像强度来消除曝光相关伪影的曝光补偿器 ...
定义 exposure_compensate.hpp:146
void setNrFeeds(int nr_feeds)
定义 exposure_compensate.hpp:155
在边界混合图像的简单混合器。
定义 blenders.hpp:101
float sharpness() const
定义 blenders.hpp:105
void setSharpness(float val)
定义 blenders.hpp:106
尝试通过调整图像强度来消除曝光相关伪影的曝光补偿器,...
定义 exposure_compensate.hpp:112
void setNrFeeds(int nr_feeds)
定义 exposure_compensate.hpp:126
使用多波段混合算法的混合器(参见)。
定义 blenders.hpp:128
int numBands() const
定义 blenders.hpp:132
void setNumBands(int val)
定义 blenders.hpp:133
void sqrt(InputArray src, OutputArray dst)
计算数组元素的平方根。
void sort(InputArray src, OutputArray dst, int flags)
对矩阵的每一行或每一列进行排序。
void log(InputArray src, OutputArray dst)
计算每个数组元素的自然对数。
void min(InputArray src1, InputArray src2, OutputArray dst)
计算两个数组或一个数组和一个标量的逐元素最小值。
std::string String
定义 cvstd.hpp:151
std::shared_ptr< _Tp > Ptr
定义 cvstd_wrapper.hpp:23
#define CV_8U
定义 interface.h:73
#define CV_32F
定义 interface.h:78
int64_t int64
定义 interface.h:61
#define CV_8UC1
定义 interface.h:88
#define CV_16S
定义 interface.h:76
softfloat abs(softfloat a)
绝对值。
定义 softfloat.hpp:444
int cvRound(double value)
将浮点数四舍五入到最接近的整数。
定义 fast_math.hpp:200
double getTickFrequency()
返回每秒的滴答次数。
bool setBreakOnError(bool flag)
设置/重置错误中断模式。
int64 getTickCount()
返回滴答次数。
GMat mask(const GMat &src, const GMat &mask)
将掩码应用于矩阵。
GMat convertTo(const GMat &src, int rdepth, double alpha=1, double beta=0)
将矩阵转换为另一种数据深度,并可选地进行缩放。
CV_EXPORTS_W bool imwrite(const String &filename, InputArray img, const std::vector< int > &params=std::vector< int >())
将图像保存到指定文件。
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR)
从文件加载图像。
void dilate(InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar &borderValue=morphologyDefaultBorderValue())
使用特定的结构元素膨胀图像。
void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR)
调整图像大小。
void computeImageFeatures(const Ptr< Feature2D > &featuresFinder, InputArrayOfArrays images, std::vector< ImageFeatures > &features, InputArrayOfArrays masks=noArray())
std::vector< int > leaveBiggestComponent(std::vector< ImageFeatures > &features, std::vector< MatchesInfo > &pairwise_matches, float conf_threshold)
String matchesGraphAsString(std::vector< String > &paths, std::vector< MatchesInfo > &pairwise_matches, float conf_threshold)
WaveCorrectKind
定义 motion_estimators.hpp:329
void waveCorrect(std::vector< Mat > &rmats, WaveCorrectKind kind)
尝试使全景图更加水平(或垂直)。
Rect resultRoi(const std::vector< Point > &corners, const std::vector< UMat > &images)
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
定义 tracking.detail.hpp:21
GOpaque< Size > size(const GMat &src)
从 Mat 获取尺寸。
与磁盘上的文件关联的文件存储的“黑盒”表示。
定义 core.hpp:102
STL 命名空间。