注:此教程是对贾志刚老师的opencv课程学习的一个记录,在此表示对贾老师的感谢.
稠密光流跟踪是将当前帧的所有像素点与前一帧比较,有变化的标记出来。对比的点比较多,不是对比变化的那几个特征点。所以速度较慢。没有稀疏光流的速度快。但有的时候效果比稀疏光流要好。
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
void drawOpticalFlowHF(const Mat &flowdata, Mat& image, int step);
int main(int argc, char** argv)
{
VideoCapture capture;
capture.open("/home/fuhong/code/cpp/opencv_learning/src/object_tracing/video/video_006.mp4");
if (!capture.isOpened()) {
printf("could not load image...\n");
return -1;
}
Mat frame, gray;
Mat prev_frame, prev_gray;
Mat flowResult, flowdata;
capture.read(frame);
cvtColor(frame, prev_gray, COLOR_BGR2GRAY);
namedWindow("flow", CV_WINDOW_AUTOSIZE);
namedWindow("input", CV_WINDOW_AUTOSIZE);
while(capture.read(frame))
{
cvtColor(frame, gray, COLOR_BGR2GRAY);
if (!prev_gray.empty()) {
calcOpticalFlowFarneback(prev_gray, gray, flowdata, 0.5, 3, 15, 3, 5, 1.2, 0);
cvtColor(prev_gray, flowResult, COLOR_GRAY2BGR);
drawOpticalFlowHF(flowdata, flowResult, 10);
imshow("flow", flowResult);
imshow("input", frame);
}
char c = waitKey(1);
if (c == 27) {
break;
}
}
return 0;
}
void drawOpticalFlowHF(const Mat &flowdata, Mat& image, int step) {
for (int row = 0; row < image.rows; row++) {
for (int col = 0; col < image.cols; col++) {
const Point2f fxy = flowdata.at<Point2f>(row, col);
if (fxy.x > 1 || fxy.y > 1) {
line(image, Point(col, row), Point(cvRound(col + fxy.x), cvRound(row + fxy.y)), Scalar(0, 255, 0), 2, 8, 0);
circle(image, Point(col, row), 2, Scalar(0, 0, 255), -1);
}
}
}
}
效果如下: