Path: blob/master/samples/gpu/pyrlk_optical_flow.cpp
16337 views
#include <iostream>1#include <vector>23#include <opencv2/core.hpp>4#include <opencv2/core/utility.hpp>5#include <opencv2/imgproc.hpp>6#include <opencv2/highgui.hpp>7#include <opencv2/video.hpp>8#include <opencv2/cudaoptflow.hpp>9#include <opencv2/cudaimgproc.hpp>10#include <opencv2/cudaarithm.hpp>1112using namespace std;13using namespace cv;14using namespace cv::cuda;1516static void download(const GpuMat& d_mat, vector<Point2f>& vec)17{18vec.resize(d_mat.cols);19Mat mat(1, d_mat.cols, CV_32FC2, (void*)&vec[0]);20d_mat.download(mat);21}2223static void download(const GpuMat& d_mat, vector<uchar>& vec)24{25vec.resize(d_mat.cols);26Mat mat(1, d_mat.cols, CV_8UC1, (void*)&vec[0]);27d_mat.download(mat);28}2930static void drawArrows(Mat& frame, const vector<Point2f>& prevPts, const vector<Point2f>& nextPts, const vector<uchar>& status, Scalar line_color = Scalar(0, 0, 255))31{32for (size_t i = 0; i < prevPts.size(); ++i)33{34if (status[i])35{36int line_thickness = 1;3738Point p = prevPts[i];39Point q = nextPts[i];4041double angle = atan2((double) p.y - q.y, (double) p.x - q.x);4243double hypotenuse = sqrt( (double)(p.y - q.y)*(p.y - q.y) + (double)(p.x - q.x)*(p.x - q.x) );4445if (hypotenuse < 1.0)46continue;4748// Here we lengthen the arrow by a factor of three.49q.x = (int) (p.x - 3 * hypotenuse * cos(angle));50q.y = (int) (p.y - 3 * hypotenuse * sin(angle));5152// Now we draw the main line of the arrow.53line(frame, p, q, line_color, line_thickness);5455// Now draw the tips of the arrow. I do some scaling so that the56// tips look proportional to the main line of the arrow.5758p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4));59p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4));60line(frame, p, q, line_color, line_thickness);6162p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4));63p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4));64line(frame, p, q, line_color, line_thickness);65}66}67}6869inline bool isFlowCorrect(Point2f u)70{71return !cvIsNaN(u.x) && !cvIsNaN(u.y) && fabs(u.x) < 1e9 && fabs(u.y) < 1e9;72}7374static Vec3b computeColor(float fx, float fy)75{76static bool first = true;7778// relative lengths of color transitions:79// these are chosen based on perceptual similarity80// (e.g. one can distinguish more shades between red and yellow81// than between yellow and green)82const int RY = 15;83const int YG = 6;84const int GC = 4;85const int CB = 11;86const int BM = 13;87const int MR = 6;88const int NCOLS = RY + YG + GC + CB + BM + MR;89static Vec3i colorWheel[NCOLS];9091if (first)92{93int k = 0;9495for (int i = 0; i < RY; ++i, ++k)96colorWheel[k] = Vec3i(255, 255 * i / RY, 0);9798for (int i = 0; i < YG; ++i, ++k)99colorWheel[k] = Vec3i(255 - 255 * i / YG, 255, 0);100101for (int i = 0; i < GC; ++i, ++k)102colorWheel[k] = Vec3i(0, 255, 255 * i / GC);103104for (int i = 0; i < CB; ++i, ++k)105colorWheel[k] = Vec3i(0, 255 - 255 * i / CB, 255);106107for (int i = 0; i < BM; ++i, ++k)108colorWheel[k] = Vec3i(255 * i / BM, 0, 255);109110for (int i = 0; i < MR; ++i, ++k)111colorWheel[k] = Vec3i(255, 0, 255 - 255 * i / MR);112113first = false;114}115116const float rad = sqrt(fx * fx + fy * fy);117const float a = atan2(-fy, -fx) / (float)CV_PI;118119const float fk = (a + 1.0f) / 2.0f * (NCOLS - 1);120const int k0 = static_cast<int>(fk);121const int k1 = (k0 + 1) % NCOLS;122const float f = fk - k0;123124Vec3b pix;125126for (int b = 0; b < 3; b++)127{128const float col0 = colorWheel[k0][b] / 255.0f;129const float col1 = colorWheel[k1][b] / 255.0f;130131float col = (1 - f) * col0 + f * col1;132133if (rad <= 1)134col = 1 - rad * (1 - col); // increase saturation with radius135else136col *= .75; // out of range137138pix[2 - b] = static_cast<uchar>(255.0 * col);139}140141return pix;142}143144static void drawOpticalFlow(const Mat_<float>& flowx, const Mat_<float>& flowy, Mat& dst, float maxmotion = -1)145{146dst.create(flowx.size(), CV_8UC3);147dst.setTo(Scalar::all(0));148149// determine motion range:150float maxrad = maxmotion;151152if (maxmotion <= 0)153{154maxrad = 1;155for (int y = 0; y < flowx.rows; ++y)156{157for (int x = 0; x < flowx.cols; ++x)158{159Point2f u(flowx(y, x), flowy(y, x));160161if (!isFlowCorrect(u))162continue;163164maxrad = max(maxrad, sqrt(u.x * u.x + u.y * u.y));165}166}167}168169for (int y = 0; y < flowx.rows; ++y)170{171for (int x = 0; x < flowx.cols; ++x)172{173Point2f u(flowx(y, x), flowy(y, x));174175if (isFlowCorrect(u))176dst.at<Vec3b>(y, x) = computeColor(u.x / maxrad, u.y / maxrad);177}178}179}180181static void showFlow(const char* name, const GpuMat& d_flow)182{183GpuMat planes[2];184cuda::split(d_flow, planes);185186Mat flowx(planes[0]);187Mat flowy(planes[1]);188189Mat out;190drawOpticalFlow(flowx, flowy, out, 10);191192imshow(name, out);193}194195template <typename T> inline T clamp (T x, T a, T b)196{197return ((x) > (a) ? ((x) < (b) ? (x) : (b)) : (a));198}199200template <typename T> inline T mapValue(T x, T a, T b, T c, T d)201{202x = clamp(x, a, b);203return c + (d - c) * (x - a) / (b - a);204}205206int main(int argc, const char* argv[])207{208const char* keys =209"{ h help | | print help message }"210"{ l left | ../data/pic1.png | specify left image }"211"{ r right | ../data/pic2.png | specify right image }"212"{ flow | sparse | specify flow type [PyrLK] }"213"{ gray | | use grayscale sources [PyrLK Sparse] }"214"{ win_size | 21 | specify windows size [PyrLK] }"215"{ max_level | 3 | specify max level [PyrLK] }"216"{ iters | 30 | specify iterations count [PyrLK] }"217"{ points | 4000 | specify points count [GoodFeatureToTrack] }"218"{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }";219220CommandLineParser cmd(argc, argv, keys);221222if (cmd.has("help") || !cmd.check())223{224cmd.printMessage();225cmd.printErrors();226return 0;227}228229string fname0 = cmd.get<string>("left");230string fname1 = cmd.get<string>("right");231232if (fname0.empty() || fname1.empty())233{234cerr << "Missing input file names" << endl;235return -1;236}237238string flow_type = cmd.get<string>("flow");239bool is_sparse = true;240if (flow_type == "sparse")241{242is_sparse = true;243}244else if (flow_type == "dense")245{246is_sparse = false;247}248else249{250cerr << "please specify 'sparse' or 'dense' as flow type" << endl;251return -1;252}253254bool useGray = cmd.has("gray");255int winSize = cmd.get<int>("win_size");256int maxLevel = cmd.get<int>("max_level");257int iters = cmd.get<int>("iters");258int points = cmd.get<int>("points");259double minDist = cmd.get<double>("min_dist");260261Mat frame0 = imread(fname0);262Mat frame1 = imread(fname1);263264if (frame0.empty() || frame1.empty())265{266cout << "Can't load input images" << endl;267return -1;268}269270cout << "Image size : " << frame0.cols << " x " << frame0.rows << endl;271cout << "Points count : " << points << endl;272273cout << endl;274275Mat frame0Gray;276cv::cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY);277Mat frame1Gray;278cv::cvtColor(frame1, frame1Gray, COLOR_BGR2GRAY);279280// goodFeaturesToTrack281GpuMat d_frame0Gray(frame0Gray);282GpuMat d_prevPts;283284Ptr<cuda::CornersDetector> detector = cuda::createGoodFeaturesToTrackDetector(d_frame0Gray.type(), points, 0.01, minDist);285detector->detect(d_frame0Gray, d_prevPts);286287GpuMat d_frame0(frame0);288GpuMat d_frame1(frame1);289GpuMat d_frame1Gray(frame1Gray);290GpuMat d_nextPts;291GpuMat d_status;292GpuMat d_flow(frame0.size(), CV_32FC2);293294if (is_sparse)295{296// Sparse297Ptr<cuda::SparsePyrLKOpticalFlow> d_pyrLK_sparse = cuda::SparsePyrLKOpticalFlow::create(298Size(winSize, winSize), maxLevel, iters);299d_pyrLK_sparse->calc(useGray ? d_frame0Gray : d_frame0, useGray ? d_frame1Gray : d_frame1, d_prevPts, d_nextPts, d_status);300301// Draw arrows302vector<Point2f> prevPts(d_prevPts.cols);303download(d_prevPts, prevPts);304305vector<Point2f> nextPts(d_nextPts.cols);306download(d_nextPts, nextPts);307308vector<uchar> status(d_status.cols);309download(d_status, status);310311namedWindow("PyrLK [Sparse]", WINDOW_NORMAL);312drawArrows(frame0, prevPts, nextPts, status, Scalar(255, 0, 0));313imshow("PyrLK [Sparse]", frame0);314}315else316{317// Dense318Ptr<cuda::DensePyrLKOpticalFlow> d_pyrLK_dense = cuda::DensePyrLKOpticalFlow::create(319Size(winSize, winSize), maxLevel, iters);320d_pyrLK_dense->calc(d_frame0Gray, d_frame1Gray, d_flow);321322// Draw flows323namedWindow("PyrLK [Dense] Flow Field", WINDOW_NORMAL);324showFlow("PyrLK [Dense] Flow Field", d_flow);325}326327waitKey(0);328329return 0;330}331332