我使用它作为跟踪算法的基础。
//1. detect the features
cv::goodFeaturesToTrack(gray_prev, // the image
features, // the output detected features
max_count, // the maximum number of features
qlevel, // quality level
minDist); // min distance between two features
// 2. track features
cv::calcOpticalFlowPyrLK(
gray_prev, gray, // 2 consecutive images
points_prev, // input point positions in first im
points_cur, // output point positions in the 2nd
status, // tracking success
err); // tracking error
cv::calcOpticalFlowPyrLK
将来自前一图像的点的矢量作为输入,并在下一图像上返回适当的点。假设我在前一张图像上有随机像素(x,y),我如何使用OpenCV光流函数计算该像素在下一张图像中的位置?
在编写时,cv::goodFeaturesToTrack
将图像作为输入,并生成一个它认为"易于跟踪"的点向量。这些是基于它们从周围环境中脱颖而出的能力而选择的,并且是基于图像中的哈里斯角。跟踪器通常通过将第一个图像传递给goodFeaturesToTrack并获得一组要跟踪的特征来初始化。然后,这些特征可以与序列中的下一个图像一起作为前一个点传递给cv::calcOpticalFlowPyrLK
,并且它将产生下一个点作为输出,然后这些点成为下一次迭代中的输入点。
如果您想尝试跟踪不同的像素集(而不是cv::goodFeaturesToTrack
或类似函数生成的特征),那么只需将这些像素与下一张图像一起提供给cv::calcOpticalFlowPyrLK
即可。
非常简单,代码:
// Obtain first image and set up two feature vectors
cv::Mat image_prev, image_next;
std::vector<cv::Point> features_prev, features_next;
image_next = getImage();
// Obtain initial set of features
cv::goodFeaturesToTrack(image_next, // the image
features_next, // the output detected features
max_count, // the maximum number of features
qlevel, // quality level
minDist // min distance between two features
);
// Tracker is initialised and initial features are stored in features_next
// Now iterate through rest of images
for(;;)
{
image_prev = image_next.clone();
feature_prev = features_next;
image_next = getImage(); // Get next image
// Find position of feature in new image
cv::calcOpticalFlowPyrLK(
image_prev, image_next, // 2 consecutive images
points_prev, // input point positions in first im
points_next, // output point positions in the 2nd
status, // tracking success
err // tracking error
);
if ( stopTracking() ) break;
}
cv::calcOpticalFlowPyrLK(..)函数使用参数:
cv::calcOpticalFlowPyrLK(prev_gray,curr_gray,features_prev,features_next,status,err);
cv::Mat prev_gray, curr_gray;
std::vector<cv::Point2f> features_prev, features_next;
std::vector<uchar> status;
std::vector<float> err;
在下一帧中查找像素的最简单(部分)代码:
features_prev.push_back(cv::Point(4, 5));
cv::calcOpticalFlowPyrLK(prev_gray, curr_gray, features_prev, features_next, status, err);
若成功找到像素,status[0] == 1
和features_next[0]
将显示下一帧中像素的坐标。值信息可以在本例中找到:OpenCV/samples/cpp/lkdemo.cpp