1_5 optical_flow

news/2024/11/23 2:17:07/

        采用特征点法做VO存在耗时较大的问题,一般耗时情况:如下

        (1) 在图像中提取特征点并计算特征描述, 非常耗时  ~10+ms  ORB,shift耗时更多;
        (2) 在不同图像中寻找特征匹配,                非常耗时   O(n^2) 暴力匹配
        (3) 利用匹配点信息计算相机位姿,             比较快速<1ms

        因此,为了速度还有不使用特征匹配计算VO的方法,主要有两大类,分别是:

        (1) 通过其他方式寻找配对点;   光流法
                稀疏光流法:以Lucas-Kanade(LK)光流为代表
                稠密光流法:以Horn-Schunk(HS)光流为代表
        本质上是估计像素在不同时刻图像中的运动。
        光流法推导过程依赖灰度不变假设:I(x_{1},y_{1},t_{1})=I(x_{2},y_{2},t_{2})=I(x_{3},y_{3},t_{3})
        t时刻位于x,y处像素点的灰度值为I(x,y,t)
        t+dt时刻位于x+dx,y+dy处的像素点灰度值为I(x+dx,y+dy,t+dt)
        对t+dt时刻进行泰勒一级展开如下:
        I(x+dx,y+dy,t+dt)\approx I(x,y,t)+\frac{\partial I}{\partial x}dx+\frac{\partial I}{\partial y}dy+\frac{\partial I}{\partial t}dt,由于灰度值两个时刻相等,所以可得:
\frac{\partial I}{\partial x}\frac{dx}{dt}+\frac{\partial I}{\partial y}\frac{dy}{dt}=-\frac{\partial I}{\partial t},所以这里是希望求解dx/dt和dy/dt。

        注意:灰度不变是一种理想假设,对于高光、阴影等情况很可能不成立。

        由于上述的光流公式是一个二元一次方程,欠定的,所以需要引入额外的约束。假定一个窗口(w*w)内光度不变,则可以构建矩阵:

\begin{bmatrix} I_{x} & I_{y} \end{bmatrix}_{k}\begin{bmatrix} u\\v \end{bmatrix}=-I_{tk}, k=1,2,...w^{2}

        通过超定最小二乘求解运动u,v

        A=\begin{bmatrix} \begin{bmatrix} I_{x} &I_{y} \end{bmatrix}_{1}\\... \\ \begin{bmatrix} I_{x} &I_{y} \end{bmatrix}_{k} \end{bmatrix},b=\begin{bmatrix} I_{t1}\\ ... \\ I_{tk} \end{bmatrix}

        \begin{bmatrix} u\\ v \end{bmatrix}^*=-(A^{T}A)^{-1}A^{T}b

      具体代码如下:

//
// Created by Xiang on 2017/12/19.
//#include <opencv2/opencv.hpp>
#include <string>
#include <chrono>
#include <Eigen/Core>
#include <Eigen/Dense>using namespace std;
using namespace cv;string file_1 = "./LK1.png";  // first image
string file_2 = "./LK2.png";  // second image/// Optical flow tracker and interface
class OpticalFlowTracker {
public:OpticalFlowTracker(const Mat &img1_,const Mat &img2_,const vector<KeyPoint> &kp1_,vector<KeyPoint> &kp2_,vector<bool> &success_,bool inverse_ = true, bool has_initial_ = false) :img1(img1_), img2(img2_), kp1(kp1_), kp2(kp2_), success(success_), inverse(inverse_),has_initial(has_initial_) {}void calculateOpticalFlow(const Range &range);private:const Mat &img1;const Mat &img2;const vector<KeyPoint> &kp1;vector<KeyPoint> &kp2;vector<bool> &success;bool inverse = true;bool has_initial = false;
};/*** single level optical flow* @param [in] img1 the first image* @param [in] img2 the second image* @param [in] kp1 keypoints in img1* @param [in|out] kp2 keypoints in img2, if empty, use initial guess in kp1* @param [out] success true if a keypoint is tracked successfully* @param [in] inverse use inverse formulation?*/
void OpticalFlowSingleLevel(const Mat &img1,const Mat &img2,const vector<KeyPoint> &kp1,vector<KeyPoint> &kp2,vector<bool> &success,bool inverse = false,bool has_initial_guess = false
);/*** multi level optical flow, scale of pyramid is set to 2 by default* the image pyramid will be create inside the function* @param [in] img1 the first pyramid* @param [in] img2 the second pyramid* @param [in] kp1 keypoints in img1* @param [out] kp2 keypoints in img2* @param [out] success true if a keypoint is tracked successfully* @param [in] inverse set true to enable inverse formulation*/
void OpticalFlowMultiLevel(const Mat &img1,const Mat &img2,const vector<KeyPoint> &kp1,vector<KeyPoint> &kp2,vector<bool> &success,bool inverse = false
);/*** get a gray scale value from reference image (bi-linear interpolated)* @param img* @param x* @param y* @return the interpolated value of this pixel*/inline float GetPixelValue(const cv::Mat &img, float x, float y) {// boundary checkif (x < 0) x = 0;if (y < 0) y = 0;if (x >= img.cols - 1) x = img.cols - 2;if (y >= img.rows - 1) y = img.rows - 2;float xx = x - floor(x);float yy = y - floor(y);int x_a1 = std::min(img.cols - 1, int(x) + 1);int y_a1 = std::min(img.rows - 1, int(y) + 1);return (1 - xx) * (1 - yy) * img.at<uchar>(y, x)+ xx * (1 - yy) * img.at<uchar>(y, x_a1)+ (1 - xx) * yy * img.at<uchar>(y_a1, x)+ xx * yy * img.at<uchar>(y_a1, x_a1);
}int main(int argc, char **argv) {// images, note they are CV_8UC1, not CV_8UC3Mat img1 = imread(file_1, 0);Mat img2 = imread(file_2, 0);// key points, using GFTT here.vector<KeyPoint> kp1;Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20); // maximum 500 keypointsdetector->detect(img1, kp1);// now lets track these key points in the second image// first use single level LK in the validation picturevector<KeyPoint> kp2_single;vector<bool> success_single;OpticalFlowSingleLevel(img1, img2, kp1, kp2_single, success_single);// then test multi-level LKvector<KeyPoint> kp2_multi;vector<bool> success_multi;chrono::steady_clock::time_point t1 = chrono::steady_clock::now();OpticalFlowMultiLevel(img1, img2, kp1, kp2_multi, success_multi, true);chrono::steady_clock::time_point t2 = chrono::steady_clock::now();auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);cout << "optical flow by gauss-newton: " << time_used.count() << endl;// use opencv's flow for validationvector<Point2f> pt1, pt2;for (auto &kp: kp1) pt1.push_back(kp.pt);vector<uchar> status;vector<float> error;t1 = chrono::steady_clock::now();cv::calcOpticalFlowPyrLK(img1, img2, pt1, pt2, status, error);t2 = chrono::steady_clock::now();time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);cout << "optical flow by opencv: " << time_used.count() << endl;// plot the differences of those functionsMat img2_single;cv::cvtColor(img2, img2_single, CV_GRAY2BGR);for (int i = 0; i < kp2_single.size(); i++) {if (success_single[i]) {cv::circle(img2_single, kp2_single[i].pt, 2, cv::Scalar(0, 250, 0), 2);cv::line(img2_single, kp1[i].pt, kp2_single[i].pt, cv::Scalar(0, 250, 0));}}Mat img2_multi;cv::cvtColor(img2, img2_multi, CV_GRAY2BGR);for (int i = 0; i < kp2_multi.size(); i++) {if (success_multi[i]) {cv::circle(img2_multi, kp2_multi[i].pt, 2, cv::Scalar(0, 250, 0), 2);cv::line(img2_multi, kp1[i].pt, kp2_multi[i].pt, cv::Scalar(0, 250, 0));}}Mat img2_CV;cv::cvtColor(img2, img2_CV, CV_GRAY2BGR);for (int i = 0; i < pt2.size(); i++) {if (status[i]) {cv::circle(img2_CV, pt2[i], 2, cv::Scalar(0, 250, 0), 2);cv::line(img2_CV, pt1[i], pt2[i], cv::Scalar(0, 250, 0));}}cv::imshow("tracked single level", img2_single);cv::imshow("tracked multi level", img2_multi);cv::imshow("tracked by opencv", img2_CV);cv::waitKey(0);return 0;
}void OpticalFlowSingleLevel(const Mat &img1,const Mat &img2,const vector<KeyPoint> &kp1,vector<KeyPoint> &kp2,vector<bool> &success,bool inverse, bool has_initial) {kp2.resize(kp1.size());success.resize(kp1.size());OpticalFlowTracker tracker(img1, img2, kp1, kp2, success, inverse, has_initial);parallel_for_(Range(0, kp1.size()),std::bind(&OpticalFlowTracker::calculateOpticalFlow, &tracker, placeholders::_1));
}void OpticalFlowTracker::calculateOpticalFlow(const Range &range) {// parametersint half_patch_size = 4;int iterations = 10;for (size_t i = range.start; i < range.end; i++) {auto kp = kp1[i];double dx = 0, dy = 0; // dx,dy need to be estimatedif (has_initial) {dx = kp2[i].pt.x - kp.pt.x;dy = kp2[i].pt.y - kp.pt.y;}double cost = 0, lastCost = 0;bool succ = true; // indicate if this point succeeded// Gauss-Newton iterationsEigen::Matrix2d H = Eigen::Matrix2d::Zero();    // hessianEigen::Vector2d b = Eigen::Vector2d::Zero();    // biasEigen::Vector2d J;  // jacobianfor (int iter = 0; iter < iterations; iter++) {if (inverse == false) {H = Eigen::Matrix2d::Zero();b = Eigen::Vector2d::Zero();} else {// only reset bb = Eigen::Vector2d::Zero();}cost = 0;// compute cost and jacobianfor (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, kp.pt.x + x, kp.pt.y + y) -GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);;  // Jacobianif (inverse == false) {J = -1.0 * Eigen::Vector2d(0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1)));} else if (iter == 0) {// in inverse mode, J keeps same for all iterations// NOTE this J does not change when dx, dy is updated, so we can store it and only compute errorJ = -1.0 * Eigen::Vector2d(0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1)));}// compute H, b and set cost;b += -error * J;cost += error * error;if (inverse == false || iter == 0) {// also update HH += J * J.transpose();}}// compute updateEigen::Vector2d update = H.ldlt().solve(b);if (std::isnan(update[0])) {// sometimes occurred when we have a black or white patch and H is irreversiblecout << "update is nan" << endl;succ = false;break;}if (iter > 0 && cost > lastCost) {break;}// update dx, dydx += update[0];dy += update[1];lastCost = cost;succ = true;if (update.norm() < 1e-2) {// convergebreak;}}success[i] = succ;// set kp2kp2[i].pt = kp.pt + Point2f(dx, dy);}
}void OpticalFlowMultiLevel(const Mat &img1,const Mat &img2,const vector<KeyPoint> &kp1,vector<KeyPoint> &kp2,vector<bool> &success,bool inverse) {// parametersint pyramids = 4;double pyramid_scale = 0.5;double scales[] = {1.0, 0.5, 0.25, 0.125};// create pyramidschrono::steady_clock::time_point t1 = chrono::steady_clock::now();vector<Mat> pyr1, pyr2; // image pyramidsfor (int i = 0; i < pyramids; i++) {if (i == 0) {pyr1.push_back(img1);pyr2.push_back(img2);} else {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);}}chrono::steady_clock::time_point t2 = chrono::steady_clock::now();auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);cout << "build pyramid time: " << time_used.count() << endl;// coarse-to-fine LK tracking in pyramidsvector<KeyPoint> kp1_pyr, kp2_pyr;for (auto &kp:kp1) {auto kp_top = kp;kp_top.pt *= scales[pyramids - 1];kp1_pyr.push_back(kp_top);kp2_pyr.push_back(kp_top);}for (int level = pyramids - 1; level >= 0; level--) {// from coarse to finesuccess.clear();t1 = chrono::steady_clock::now();OpticalFlowSingleLevel(pyr1[level], pyr2[level], kp1_pyr, kp2_pyr, success, inverse, true);t2 = chrono::steady_clock::now();auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);cout << "track pyr " << level << " cost time: " << time_used.count() << endl;if (level > 0) {for (auto &kp: kp1_pyr)kp.pt /= pyramid_scale;for (auto &kp: kp2_pyr)kp.pt /= pyramid_scale;}}for (auto &kp: kp2_pyr)kp2.push_back(kp);
}


        (2) 无配对点方法;     直接法


http://www.ppmy.cn/news/124644.html

相关文章

Goerli认证水龙头接水

&#xff08;1&#xff09;获取你的地址 因为运行bee需要花费币&#xff0c;所以我们先要就某一个地方获取到币&#xff08;就是口头说的接水&#xff09;&#xff0c;或者别人转给币到你钱包下。 拷贝到 0xe1137c0f833844f65114fc46cedfc6062044627c &#xff08;2&#xf…

各种水龙头拆卸图解_各种水龙头拆卸图解 蜜罐蚁小编带您了解水龙头拆卸方法...

水龙头的种类还是比较多的&#xff0c;常见的有普通面盆水龙头、卫生间水龙头、厨房水龙头、按压式水龙头、感应式水龙头、洗衣机水龙头、起泡器水龙头等等。 今天蜜罐蚁小编整理一些常见水龙头拆卸图解供大家参考&#xff0c;如果您不会拆卸水龙头&#xff0c;不妨看看本文吧&…

各种水龙头拆卸图解_各种水龙头拆卸图解法

水是生命之源&#xff0c;但是水资源是有限的&#xff0c;人们在平时用水的时候要学会注意保护水资源&#xff0c;节约用水是非常重要的事情&#xff0c;而家庭中可以使用一些水龙头进行控制用水量。水龙头的材质非常多&#xff0c;而每一种不同材质的水龙头应用的领域不同&…

各种水龙头拆卸图解_水龙头怎么拆卸图解法?水龙头的安装费是多少?

水龙头对于我们生活有多重要&#xff0c;相信大家都应该知道吧&#xff0c;如果水龙头出现了问题的话&#xff0c;那么要怎么处理呢&#xff1f;如果水龙头出现问题的话&#xff0c;那么就必须要学会拆卸&#xff0c;这是很关键的第一步&#xff0c;那么&#xff0c;接下来我们…

2022-2028全球及中国冷凝式即热型热水器行业研究报告

据168报网的分析师调研显示&#xff0c;2021年全球冷凝式即热型热水器市场规模大约为 亿元&#xff08;人民币&#xff09;&#xff0c;预计2028年将达到 亿元&#xff0c;2022-2028期间年复合增长率&#xff08;CAGR&#xff09;为 %。未来几年&#xff0c;本行业具有很大不确…

工具箱:BUMO 水龙头用户手册

BUMO 水龙头用户手册 Faucet 又称“水龙头”&#xff0c;是为用户获取测试BU的网页版应用。用户只要输入自己的测试账 户地址即可获取100个测试BU。可多次为同一账户获取BU&#xff0c;但不可过于频繁。Faucet测试版网址为 https://faucet.bumotest.io/。 你可以按照下面步骤…

识别与挑选水龙头

目前&#xff0c;市场上的水龙头品种繁多&#xff0c;会令人在选购时会觉得无所适从。其实&#xff0c;厨卫水龙头尽管花色、式样、造型、品种五花八门&#xff0c;但也很容易从功能和结构两个方面来划分。 1.是从使用功能上来分&#xff0c;大体有浴缸龙头、面盆龙头、厨房龙头…

一文带你了解什么是测试网水龙头

关于测试网水龙头 以太坊测试网水龙头&#xff08;Ethereum testnet faucet&#xff09;是一个用于向开发者和测试人员分发测试网络以太币&#xff08;Ether&#xff09;的服务。测试网络是一个模拟真实以太坊网络的环境&#xff0c;用于开发和测试智能合约和去中心化应用程序…