DenseOpticalFlow(),createOptFlow_DualTVL1稠密光流

本文介绍了如何利用DenseOpticalFlow中的createOptFlow_DualTVL1函数来实现稠密光流计算,提供了一个详细的示例代码,帮助理解其工作原理。
摘要由CSDN通过智能技术生成


(1)DenseOpticalFlow示例代码

#include <iostream>
#include <fstream>

#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;
using namespace std;

inline bool isFlowCorrect(Point2f u)
{
    return !cvIsNaN(u.x) && !cvIsNaN(u.y) && fabs(u.x) < 1e9 && fabs(u.y) < 1e9;
}

static Vec3b computeColor(float fx, float fy)
{
    static bool first = true;

    // relative lengths of color transitions:
    // these are chosen based on perceptual similarity
    // (e.g. one can distinguish more shades between red and yellow
    //  than between yellow and green)
    const int RY = 15;
    const int YG = 6;
    const int GC = 4;
    const int CB = 11;
    const int BM = 13;
    const int MR = 6;
    const int NCOLS = RY + YG + GC + CB + BM + MR;
    static Vec3i colorWheel[NCOLS];

    
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C++和OpenCV实现对视频中运动物体运动轨迹的提取的示例代码: ```c++ #include <opencv2/opencv.hpp> #include <vector> using namespace std; using namespace cv; int main() { // 读取视频文件 VideoCapture cap("test.mp4"); // 定义背景差分器和光流计算器 Ptr<BackgroundSubtractor> bs = createBackgroundSubtractorMOG2(); Ptr<DenseOpticalFlow> flow = createOptFlow_DualTVL1(); // 定义用于绘制轨迹的颜色 Scalar color(0, 0, 255); // 定义轨迹点列表 vector<Point2f> points; // 循环读取视频帧 Mat frame, gray, fgmask, flowmap; while (cap.read(frame)) { // 转换为灰度图像 cvtColor(frame, gray, COLOR_BGR2GRAY); // 背景差分 bs->apply(gray, fgmask); // 计算光流 Mat prev = gray.clone(); flow->calc(prev, gray, flowmap); // 提取运动物体 Mat magnitude, angle; cartToPolar(flowmap(Rect(0, 0, frame.cols, frame.rows)).ptr<float>(0), flowmap(Rect(0, 0, frame.cols, frame.rows)).ptr<float>(1), magnitude, angle); threshold(magnitude, fgmask, 10, 255, THRESH_BINARY); // 查找运动物体的轮廓 vector<vector<Point>> contours; findContours(fgmask, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); // 绘制运动物体的轨迹 for (const auto& contour : contours) { Rect bbox = boundingRect(contour); Point2f center = Point2f(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2); // 记录轨迹点 points.push_back(center); // 绘制轨迹 for (size_t i = 1; i < points.size(); i++) { line(frame, points[i - 1], points[i], color, 2); } } // 显示原始帧和运动物体的轨迹 imshow("frame", frame); // 退出循环 if (waitKey(30) == 'q') break; } // 释放资源 cap.release(); destroyAllWindows(); return 0; } ``` 以上代码中,我们使用了cv::createBackgroundSubtractorMOG2()函数创建了背景差分器,使用了cv::createOptFlow_DualTVL1()函数创建了光流计算器。在每一帧中,我们先对图像进行背景差分和光流计算,然后提取运动物体的轮廓,并将每个运动物体的中心点保存到轨迹点列表中。最后,我们使用cv::line()函数绘制运动物体的轨迹,并使用cv::imshow()函数显示原始帧和运动物体的轨迹。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值