c++ LK光流的使用代码
时间: 2023-10-24 22:37:12 浏览: 151
以下是使用C++实现LK光流的示例代码:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取两张图像
Mat prev_frame = imread("prev_frame.jpg", IMREAD_GRAYSCALE);
Mat next_frame = imread("next_frame.jpg", IMREAD_GRAYSCALE);
// 设置LK光流参数
TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 10, 0.03);
Size winSize = Size(15, 15);
int maxLevel = 2;
double minEigThreshold = 0.01;
// 找到关键点
std::vector<Point2f> prev_corners, next_corners;
goodFeaturesToTrack(prev_frame, prev_corners, 200, 0.01, 10);
calcOpticalFlowPyrLK(prev_frame, next_frame, prev_corners, next_corners, status, error, winSize, maxLevel, criteria, 0, minEigThreshold);
// 筛选出好的关键点
std::vector<Point2f> good_prev_corners, good_next_corners;
for (int i = 0; i < prev_corners.size(); i++)
{
if (status[i] == 1) // 说明找到了对应的点
{
good_prev_corners.push_back(prev_corners[i]);
good_next_corners.push_back(next_corners[i]);
}
}
// 画出关键点和运动轨迹
Mat frame = imread("prev_frame.jpg");
Mat mask = Mat::zeros(frame.size(), frame.type());
for (int i = 0; i < good_prev_corners.size(); i++)
{
Point2f prev_pt = good_prev_corners[i];
Point2f next_pt = good_next_corners[i];
line(mask, next_pt, prev_pt, Scalar(0, 255, 0), 2);
circle(frame, next_pt, 5, Scalar(0, 0, 255), -1);
}
// 显示图像
imshow("frame", frame);
imshow("mask", mask);
waitKey(0);
destroyAllWindows();
return 0;
}
```
需要注意的是,C++中的LK光流函数与Python中的函数名略有不同,例如`cv::goodFeaturesToTrack()`、`cv::calcOpticalFlowPyrLK()`等。另外,C++中需要手动筛选出好的关键点,方法是通过`status`数组筛选出对应的点,将其存放到另一个向量中即可。
阅读全文