Closed sudonto closed 5 years ago
Code snippet using OpenCV >= 3 version:
cv::Mat image, prev_image, prev_grey, grey, frame, flow, flows[2]; cv::cuda::GpuMat frame_0, frame_1, gflow; cv::cuda::setDevice(chrDevID); cv::Ptr<cv::cuda::OpticalFlowDual_TVL1> alg_tvl1 = cv::cuda::OpticalFlowDual_TVL1::create(); cv::Ptr<cv::cuda::FarnebackOpticalFlow> alg_farn = cv::cuda::FarnebackOpticalFlow::create(); cv::Ptr<cv::cuda::BroxOpticalFlow> alg_brox = cv::cuda::BroxOpticalFlow::create(); while (true) { capture >> frame; if (frame.empty()) break; if (intFrameNum == 0) { image.create(frame.size(), CV_8UC3); grey.create(frame.size(), CV_8UC1); prev_image.create(frame.size(), CV_8UC3); prev_grey.create(frame.size(), CV_8UC1); frame.copyTo(prev_image); cv::cvtColor(prev_image, prev_grey, cv::COLOR_BGR2GRAY); intFrameNum++; int intStep_t = intStep; while (intStep_t > 1) { capture >> frame; intStep_t--; } continue; } frame.copyTo(image); cv::cvtColor(image, grey, cv::COLOR_BGR2GRAY); frame_0.upload(prev_grey); frame_1.upload(grey); // GPU optical flow switch (intType) { case 0: alg_farn->calc(frame_0, frame_1, gflow); break; case 1: alg_tvl1->calc(frame_0, frame_1, gflow); break; case 2: cv::cuda::GpuMat d_frame0f, d_frame1f; frame_0.convertTo(d_frame0f, CV_32F, 1.0 / 255.0); frame_1.convertTo(d_frame1f, CV_32F, 1.0 / 255.0); alg_brox->calc(d_frame0f, d_frame1f, gflow); break; } gflow.download(flow); cv::split(flow, flows); // Output optical flow cv::Mat imgX(flows[0].size(), CV_8UC1); cv::Mat imgY(flows[1].size(), CV_8UC1); convertFlowToImage(flows[0], flows[1], imgX, imgY, -intBound, intBound); char chrSuffix[20]; sprintf_s(chrSuffix, "_%06d.jpg", int(intFrameNum)); cv::Mat imgX_, imgY_, image_; intHeight = (intHeight > 0) ? intHeight : imgX.rows; intWidth = (intWidth > 0) ? intWidth : imgX.cols; resize(imgX, imgX_, cv::Size(intWidth, intHeight)); resize(imgY, imgY_, cv::Size(intWidth, intHeight)); resize(image, image_, cv::Size(intWidth, intHeight)); //cv::namedWindow("image", cv::WINDOW_AUTOSIZE); //cv::imshow("image", imgY_); //cv::waitKey(20); cv::imwrite(strSavePath + strXFlowFile + chrSuffix, imgX_); cv::imwrite(strSavePath + strYFlowFile + chrSuffix, imgY_); cv::imwrite(strSavePath + strImgFile + chrSuffix, image_);
Code snippet using OpenCV >= 3 version: