1.换opencv4

2.修改程序

改程序针对slambook2/ch8/direct_method.cpp

#include <opencv2/opencv.hpp>
#include <sophus/se3.hpp>
#include <boost/format.hpp>
#include <pangolin/pangolin.h> using namespace std; typedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d; // Camera intrinsics
double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;
// baseline
double baseline = 0.573;
// paths
string left_file = "../left.png";
string disparity_file = "../disparity.png";
boost::format fmt_others("../%06d.png"); // other files // useful typedefs
typedef Eigen::Matrix<double, 6, 6> Matrix6d;
typedef Eigen::Matrix<double, 2, 6> Matrix26d;
typedef Eigen::Matrix<double, 6, 1> Vector6d; /**
* pose estimation using direct method
* @param img1
* @param img2
* @param px_ref
* @param depth_ref
* @param T21
*/
void DirectPoseEstimationMultiLayer(
const cv::Mat &img1,
const cv::Mat &img2,
const VecVector2d &px_ref,
const vector<double> depth_ref,
Sophus::SE3d &T21
); /**
* pose estimation using direct method
* @param img1
* @param img2
* @param px_ref
* @param depth_ref
* @param T21
*/
void DirectPoseEstimationSingleLayer(
const cv::Mat &img1,
const cv::Mat &img2,
const VecVector2d &px_ref,
const vector<double> depth_ref,
Sophus::SE3d &T21
); // bilinear interpolation
inline float GetPixelValue(const cv::Mat &img, float x, float y) {
// boundary check
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x >= img.cols) x = img.cols - 1;
if (y >= img.rows) y = img.rows - 1;
uchar *data = &img.data[int(y) * img.step + int(x)];
float xx = x - floor(x);
float yy = y - floor(y);
return float(
(1 - xx) * (1 - yy) * data[0] +
xx * (1 - yy) * data[1] +
(1 - xx) * yy * data[img.step] +
xx * yy * data[img.step + 1]
);
} /// class for accumulator jacobians in parallel
class JacobianAccumulator: public cv::ParallelLoopBody {
private:
const cv::Mat &img1;
const cv::Mat &img2;
const VecVector2d &px_ref;
const vector<double> depth_ref;
Sophus::SE3d &T21;
mutable VecVector2d projection; // projected points mutable std::mutex hessian_mutex;
mutable Matrix6d H = Matrix6d::Zero();
mutable Vector6d b = Vector6d::Zero();
mutable double cost = 0; public:
JacobianAccumulator(
const cv::Mat &img1_,
const cv::Mat &img2_,
const VecVector2d &px_ref_,
const vector<double> depth_ref_,
Sophus::SE3d &T21_) :
img1(img1_), img2(img2_), px_ref(px_ref_), depth_ref(depth_ref_), T21(T21_) {
projection = VecVector2d(px_ref.size(), Eigen::Vector2d(0, 0));
} /// accumulate jacobians in a range
// void accumulate_jacobian(const cv::Range &range); /// get hessian matrix
Matrix6d hessian() const { return H; } /// get bias
Vector6d bias() const { return b; } /// get total cost
double cost_func() const { return cost; } /// get projected points
VecVector2d projected_points() const { return projection; } /// reset h, b, cost to zero
void reset() {
H = Matrix6d::Zero();
b = Vector6d::Zero();
cost = 0;
} virtual void operator()(const cv::Range& range) const { // parameters
const int half_patch_size = 1;
int cnt_good = 0;
Matrix6d hessian = Matrix6d::Zero();
Vector6d bias = Vector6d::Zero();
double cost_tmp = 0; for (size_t i = range.start; i < range.end; i++) { // compute the projection in the second image
Eigen::Vector3d point_ref =
depth_ref[i] * Eigen::Vector3d((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);
Eigen::Vector3d point_cur = T21 * point_ref;
if (point_cur[2] < 0) // depth invalid
continue; float u = fx * point_cur[0] / point_cur[2] + cx, v = fy * point_cur[1] / point_cur[2] + cy;
if (u < half_patch_size || u > img2.cols - half_patch_size || v < half_patch_size ||
v > img2.rows - half_patch_size)
continue; projection[i] = Eigen::Vector2d(u, v);
double X = point_cur[0], Y = point_cur[1], Z = point_cur[2],
Z2 = Z * Z, Z_inv = 1.0 / Z, Z2_inv = Z_inv * Z_inv;
cnt_good++; // and compute error and jacobian
for (int x = -half_patch_size; x <= half_patch_size; x++)
for (int y = -half_patch_size; y <= half_patch_size; y++) { double error = GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y) -
GetPixelValue(img2, u + x, v + y);
Matrix26d J_pixel_xi;
Eigen::Vector2d J_img_pixel; J_pixel_xi(0, 0) = fx * Z_inv;
J_pixel_xi(0, 1) = 0;
J_pixel_xi(0, 2) = -fx * X * Z2_inv;
J_pixel_xi(0, 3) = -fx * X * Y * Z2_inv;
J_pixel_xi(0, 4) = fx + fx * X * X * Z2_inv;
J_pixel_xi(0, 5) = -fx * Y * Z_inv; J_pixel_xi(1, 0) = 0;
J_pixel_xi(1, 1) = fy * Z_inv;
J_pixel_xi(1, 2) = -fy * Y * Z2_inv;
J_pixel_xi(1, 3) = -fy - fy * Y * Y * Z2_inv;
J_pixel_xi(1, 4) = fy * X * Y * Z2_inv;
J_pixel_xi(1, 5) = fy * X * Z_inv; J_img_pixel = Eigen::Vector2d(
0.5 * (GetPixelValue(img2, u + 1 + x, v + y) - GetPixelValue(img2, u - 1 + x, v + y)),
0.5 * (GetPixelValue(img2, u + x, v + 1 + y) - GetPixelValue(img2, u + x, v - 1 + y))
); // total jacobian
Vector6d J = -1.0 * (J_img_pixel.transpose() * J_pixel_xi).transpose(); hessian += J * J.transpose();
bias += -error * J;
cost_tmp += error * error;
}
} if (cnt_good) {
// set hessian, bias and cost
unique_lock<mutex> lck(hessian_mutex);
H += hessian;
b += bias;
cost += cost_tmp / cnt_good;
}
} }; int main(int argc, char **argv) { cv::Mat left_img = cv::imread(left_file, 0);
cv::Mat disparity_img = cv::imread(disparity_file, 0);
if (left_img.empty() || disparity_img.empty())
{
std::cout << "!!! Failed imread(): image not found" << std::endl;
return 1;
}
// let's randomly pick pixels in the first image and generate some 3d points in the first image's frame
cv::RNG rng;
int nPoints = 2000;
int boarder = 20;
VecVector2d pixels_ref;
vector<double> depth_ref;
cout << "left_img.cols" << left_img.cols << endl;
cout << "left_img: " << left_img << endl;
// generate pixels in ref and load depth data
for (int i = 0; i < nPoints; i++) {
int x = rng.uniform(boarder, left_img.cols - boarder); // don't pick pixels close to boarder
int y = rng.uniform(boarder, left_img.rows - boarder); // don't pick pixels close to boarder
int disparity = disparity_img.at<uchar>(y, x);
double depth = fx * baseline / disparity; // you know this is disparity to depth
depth_ref.push_back(depth);
pixels_ref.push_back(Eigen::Vector2d(x, y));
} // estimates 01~05.png's pose using this information
Sophus::SE3d T_cur_ref; for (int i = 1; i < 6; i++) { // 1~10
cv::Mat img = cv::imread((fmt_others % i).str(), 0);
// try single layer by uncomment this line
// DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);
DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);
}
return 0;
} void DirectPoseEstimationSingleLayer(
const cv::Mat &img1,
const cv::Mat &img2,
const VecVector2d &px_ref,
const vector<double> depth_ref,
Sophus::SE3d &T21) { const int iterations = 10;
double cost = 0, lastCost = 0;
auto t1 = chrono::steady_clock::now();
JacobianAccumulator jaco_accu(img1, img2, px_ref, depth_ref, T21); for (int iter = 0; iter < iterations; iter++) {
jaco_accu.reset();
cv::parallel_for_(cv::Range(0, px_ref.size()), jaco_accu);
Matrix6d H = jaco_accu.hessian();
Vector6d b = jaco_accu.bias(); // solve update and put it into estimation
Vector6d update = H.ldlt().solve(b);;
T21 = Sophus::SE3d::exp(update) * T21;
cost = jaco_accu.cost_func(); if (std::isnan(update[0])) {
// sometimes occurred when we have a black or white patch and H is irreversible
cout << "update is nan" << endl;
break;
}
if (iter > 0 && cost > lastCost) {
cout << "cost increased: " << cost << ", " << lastCost << endl;
break;
}
if (update.norm() < 1e-3) {
// converge
break;
} lastCost = cost;
cout << "iteration: " << iter << ", cost: " << cost << endl;
} cout << "T21 = \n" << T21.matrix() << endl;
auto t2 = chrono::steady_clock::now();
auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "direct method for single layer: " << time_used.count() << endl; // plot the projected pixels here
cv::Mat img2_show;
cv::cvtColor(img2, img2_show, CV_GRAY2BGR);
VecVector2d projection = jaco_accu.projected_points();
for (size_t i = 0; i < px_ref.size(); ++i) {
auto p_ref = px_ref[i];
auto p_cur = projection[i];
if (p_cur[0] > 0 && p_cur[1] > 0) {
cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);
cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]),
cv::Scalar(0, 250, 0));
}
}
cv::imshow("current", img2_show);
cv::waitKey();
} void DirectPoseEstimationMultiLayer(
const cv::Mat &img1,
const cv::Mat &img2,
const VecVector2d &px_ref,
const vector<double> depth_ref,
Sophus::SE3d &T21) { // parameters
int pyramids = 4;
double pyramid_scale = 0.5;
double scales[] = {1.0, 0.5, 0.25, 0.125}; // create pyramids
vector<cv::Mat> pyr1, pyr2; // image pyramids
for (int i = 0; i < pyramids; i++) {
if (i == 0) {
pyr1.push_back(img1);
pyr2.push_back(img2);
} else {
cv::Mat img1_pyr, img2_pyr;
cv::resize(pyr1[i - 1], img1_pyr,
cv::Size(pyr1[i - 1].cols * pyramid_scale, pyr1[i - 1].rows * pyramid_scale));
cv::resize(pyr2[i - 1], img2_pyr,
cv::Size(pyr2[i - 1].cols * pyramid_scale, pyr2[i - 1].rows * pyramid_scale));
pyr1.push_back(img1_pyr);
pyr2.push_back(img2_pyr);
}
} double fxG = fx, fyG = fy, cxG = cx, cyG = cy; // backup the old values
for (int level = pyramids - 1; level >= 0; level--) {
VecVector2d px_ref_pyr; // set the keypoints in this pyramid level
for (auto &px: px_ref) {
px_ref_pyr.push_back(scales[level] * px);
} // scale fx, fy, cx, cy in different pyramid levels
fx = fxG * scales[level];
fy = fyG * scales[level];
cx = cxG * scales[level];
cy = cyG * scales[level];
DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);
} }

关于opencv3.2的parallel_for_函数不支持bind function的处理(基于ch8代码)的更多相关文章

  1. 如何将Console application的Program函数变成支持async的?

    如何将Console application的Program函数变成支持async的?   class Program { static void Main(string[] args) { Task ...

  2. [C] zintrin.h : 智能引入intrinsic函数。支持VC、GCC,兼容Windows、Linux、Mac OS X

    博客来源:http://blog.csdn.net/zyl910/article/details/8100744 现在很多编译器支持intrinsic函数,这给编写SSE等SIMD代码带来了方便.但是 ...

  3. 【转】PHP里的basename函数不支持中文名的解决

    今天用到basename 函数获取文件名称时,发现如果是中文的文件名返回只有后缀的空文件名(如:.pdf)    string basename ( string path [, string suf ...

  4. vue 2.5.14以上版本render函数不支持返回字符串

    vue 2.5.14以上版本render函数不再支持直接返回字符串,必须返回数组或vnode节点,如果返回字符串的话,渲染为空.详情可见源码. function createFunctionalCom ...

  5. js时间格式化函数,支持Unix时间戳

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  6. WIN10远程桌面连接--“出现身份验证错误。要求的函数不支持”

    最近WIN10升级补丁后发现远程桌面无法连接了,报“出现身份验证错误.要求的函数不支持”的错误: 解决办法: 第一种,配置本地自己的电脑,开始菜单->搜索gpedit.msc并打开   打开配置 ...

  7. 使用正则实现php的trim函数,支持全角空格

    之前使用trim来移除一段文字开头的空格,移除不掉,发现是全角空格的锅. 便专门添加对全角空格的移除: trim($str," "); 但是效果并不好,因为trim函数对多字节字符 ...

  8. 解决IE10以下对象不支持“bind”属性或方法

    IE10一下的浏览器,如果在JS代码中用了bind函数,那么就会报“SCRIPT438: 对象不支持“bind”属性或方法” 因为浏览器没有提供这个参数的方法,所以我们就自己写一个bind,来让这个参 ...

  9. 应该用bind+function取代虚函数吗?

    用bind+function取代虚函数在好几年前就有人提出了,曾引起广泛的讨论,有支持的有反对的,可能赞成的人占大多数.这个话题挺有趣,本来是作为技术沙龙的开放性话题来讨论的,由于时间关系并没有讨论. ...

  10. typedef 函数指针 数组 std::function

    1.整型指针 typedef int* PINT;或typedef int *PINT; 2.结构体 typedef struct { double data;}DATA,  *PDATA;  //D ...

随机推荐

  1. C温故补缺(八):结构体与共用体

    结构体与共用体 结构体 是一个可以存储多个不同类型的变量的结构,类似于面对对象中的类(只有成员变量的类). struct tag { member-list member-list member-li ...

  2. 关于CSDN获取博客内容接口的x-ca-signature签名算法研究

    前言 源码下载 不知道怎么就不通过了,这篇文章放出去几个月了,然后突然告诉我不行了,所以我打算换个平台(至少不能在一棵树吊死),垃圾审核 我最初想直接获取html博客,然后保存在本地,最后发布到别的博 ...

  3. linux deb系 apache 配置解析php文件

    安装apache服务器和php服务 sudo apt-get install apache2 php 然后其实一般来说什么也不用安装了就可以成功解析php文件了 制作一个测试文件,test.php放到 ...

  4. 更换linux的开机启动图片, 启动主题

    简述 之前就想更改开机的启动图片,但是后来简单查了一下,说要重新编译内核,听到编译我就望而却步了,今天发现只是个命令而已,注意这里我用的是 linux mint .这里更改不是 grub 主题, 是 ...

  5. JUC源码学习笔记6——ReentrantReadWriteLock

    系列文章目录和关于我 阅读此文需要有AQS独占和AQS共享的源码功底,推荐阅读: 1.JUC源码学习笔记1--AQS独占模式和ReentrantLock 2.JUC源码学习笔记2--AQS共享和Sem ...

  6. 【Java SE】Day08 String类、static关键字、Arrays类、Math类

    一.String类 1.概述 所有双引号字符串,都是String类的对象 字符串常量,会存在字符串常量池中 2.创建 构造函数--空构造.字符数组.字节(byte ASCII码)数组 3.常用方法-- ...

  7. 【每日一题】【小根堆&边出队边入队后续节点&注意判空】23. 合并K个升序链表-211128/220213

    给你一个链表数组,每个链表都已经按升序排列. 请你将所有链表合并到一个升序链表中,返回合并后的链表. 答案1(参数是数组): /** * Definition for singly-linked li ...

  8. MasaFramework -- 领域驱动设计

    概念 什么是领域驱动设计 领域驱动的主要思想是, 利用确定的业务模型来指导业务与应用的设计和实现.主张开发人员与业务人员持续地沟通和模型的持续迭代,从而保证业务模型与代码的一致性,实现有效管理业务的复 ...

  9. Python异步爬虫(aiohttp版)

    异步协程不太了解的话可以去看我上篇博客:https://www.cnblogs.com/Red-Sun/p/16934843.html PS:本博客是个人笔记分享,不需要扫码加群或必须关注什么的(如果 ...

  10. ArcObjects SDK开发 014 MapSurround和普通Element

    1.如何获取MapSurround 和获取MapFrame类似,如果你已经获取指北针.比例尺等对象,可以通过IGraphicsContainer的FindFrame函数获取.如果没有,则通过IGrap ...