Object Detection(CV3)

一:背景减法

 

         对于一个稳定的监控场景而言,在没有运动目标,光照没有变化的情况下,视频图像中各个像素点的灰度值是符合随机概率分布的。由于摄像机在采集图像的过程中,会不可避免地引入噪声,这些灰度值以某一个均值为基准线,在附近做一定范围内的随机振荡,这种场景就是所谓的“背景”。

        背景减法(Background subtraction)是当前运动目标检测技术中应用较为广泛的一类方法,它的基本思想和帧间差分法相类似,都是利用不同图像的差分运算提取目标区域。不过与帧间差分法不同的是,背景减法不是将当前帧图像与相邻帧图像相减,而是将当前帧图像与一个不断更新的背景模型相减,在差分图像中提取运动目标。

                                Center

   背景减法的运算过程如图2-6 所示。首先利用数学建模的方法建立一幅背景图像帧,记当前图像帧为fn,背景帧和当前帧对应像素点的灰度值分别记为B(x)和fn(x , ) ,按照式2.17 将两帧图像对应像素点的灰度值进行相减,并取其绝对值,得到差分图像D n

                                      Center

   设定阈值 ,按照式2.18 逐个对像素点进行二值化处理,得到二值化图像 Rn' 。其中,灰度值为255 的点即为前景(运动目标)点,灰度值为0 的点即为背景点;对图像 Rn'进行连通性分析,最终可得到含有完整运动目标的图像Rn 

                                     Center

   背景减法计算较为简单,由于背景图像中没有运动目标,当前图像中有运动目标,将两幅图像相减,显然可以提取出完整的运动目标,解决了帧间差分法提取的目标内部含有“空洞”的问题。

   利用背景减法实现目标检测主要包括四个环节:背景建模,背景更新,目标检测,后期处理。其中,背景建模和背景更新是背景减法中的核心问题。背景模型建立的好坏直接影响到目标检测的效果。所谓背景建模,就是通过数学方法,构建出一种可以表征“背景”的模型。获取背景的最理想方法是在没有运动目标的情况下获取一帧“纯净”的图像作为背景,但是,在实际情况中,由于光照变化、雨雪天气、目标运动等诸多因素的影响,这种情况是很难实现。

代码实现:

 

 
  1. // Vedio_detect_human.cpp : 定义控制台应用程序的入口点。

  2. //

  3.  
  4. #include "stdafx.h"

  5. // 运动物体检测——背景减法

  6. #include "opencv2/opencv.hpp"

  7. using namespace cv;

  8. #include <iostream>

  9. using namespace std;

  10. // 运动物体检测函数声明

  11. Mat MoveDetect(Mat background, Mat frame);

  12.  
  13. int main()

  14. {

  15.  
  16. VideoCapture video("D:\\opencv\\soft\\3.3.0\\win\\opencv\\sources\\samples\\data\\vtest.avi");//定义VideoCapture类video

  17. if (!video.isOpened()) //对video进行异常检测

  18. {

  19. cout << "video open error!" << endl;

  20. return 0;

  21. }

  22. // 获取帧数

  23. int frameCount = video.get(CV_CAP_PROP_FRAME_COUNT);

  24. // 获取FPS

  25. double FPS = video.get(CV_CAP_PROP_FPS);

  26. // 存储帧

  27. Mat frame;

  28. // 存储背景图像

  29. Mat background;

  30. // 存储结果图像

  31. Mat result;

  32. for (int i = 0; i < frameCount; i++)

  33. {

  34. // 读帧进frame

  35. video >> frame;

  36. imshow("frame", frame);

  37. // 对帧进行异常检测

  38. if (frame.empty())

  39. {

  40. cout << "frame is empty!" << endl;

  41. break;

  42. }

  43. // 获取帧位置(第几帧)

  44. int framePosition = video.get(CV_CAP_PROP_POS_FRAMES);

  45. cout << "framePosition: " << framePosition << endl;

  46. // 将第一帧作为背景图像

  47. if (framePosition == 1)

  48. background = frame.clone();

  49. // 调用MoveDetect()进行运动物体检测,返回值存入result

  50. result = MoveDetect(background, frame);

  51. imshow("result", result);

  52. // 按原FPS显示

  53. if (waitKey(1000.0 / FPS) == 27)

  54. {

  55. cout << "ESC退出!" << endl;

  56. break;

  57. }

  58. }

  59. return 0;

  60. }

  61. Mat MoveDetect(Mat background, Mat frame)

  62. {

  63. Mat result = frame.clone();

  64. // 1.将background和frame转为灰度图

  65. Mat gray1, gray2;

  66. cvtColor(background, gray1, CV_BGR2GRAY);

  67. cvtColor(frame, gray2, CV_BGR2GRAY);

  68. // 2.将background和frame做差

  69. Mat diff;

  70. absdiff(gray1, gray2, diff);

  71. imshow("diff", diff);

  72. // 3.对差值图diff_thresh进行阈值化处理

  73. Mat diff_thresh;

  74. threshold(diff, diff_thresh, 50, 255, CV_THRESH_BINARY);

  75. imshow("diff_thresh", diff_thresh);

  76. // 4.腐蚀

  77. Mat kernel_erode = getStructuringElement(MORPH_RECT, Size(3, 3));

  78. Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(15, 15));

  79. erode(diff_thresh, diff_thresh, kernel_erode);

  80. imshow("erode", diff_thresh);

  81. // 5.膨胀

  82. dilate(diff_thresh, diff_thresh, kernel_dilate);

  83. imshow("dilate", diff_thresh);

  84. // 6.查找轮廓并绘制轮廓

  85. vector<vector<Point>> contours;

  86. findContours(diff_thresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

  87. // 在result上绘制轮廓

  88. drawContours(result, contours, -1, Scalar(0, 0, 255), 2);

  89. // 7.查找正外接矩形

  90. vector<Rect> boundRect(contours.size());

  91. for (int i = 0; i < contours.size(); i++)

  92. {

  93. boundRect[i] = boundingRect(contours[i]);

  94. // 在result上绘制正外接矩形

  95. rectangle(result, boundRect[i], Scalar(0, 255, 0), 2);

  96. }

  97. // 返回result

  98. return result;

  99. }


Center

 

Center

 

 

二:帧差法

      帧间差分方法利用图像序列中相邻两帧或者三帧图像对应像素值相减,然后取差值图像进行阈值化处理提取出图像中的运动区域:

Center

代码:

 

 
  1. // Vedio_detect_human.cpp : 定义控制台应用程序的入口点。

  2. //

  3.  
  4. #include "stdafx.h"

  5. // 运动物体检测——帧差法

  6. #include "opencv2/opencv.hpp"

  7. using namespace cv;

  8. #include <iostream>

  9. using namespace std;

  10. // 运动物体检测函数声明

  11. Mat MoveDetect(Mat temp, Mat frame);

  12.  
  13. int main()

  14. {

  15. // 定义VideoCapture类video

  16. VideoCapture video("D:\\opencv\\soft\\3.3.0\\win\\opencv\\sources\\samples\\data\\vtest.avi");

  17. if (!video.isOpened()) //对video进行异常检测

  18. {

  19. cout << "video open error!" << endl;

  20. return 0;

  21. }

  22. // 获取帧数

  23. int frameCount = video.get(CV_CAP_PROP_FRAME_COUNT);

  24. // 获取FPS

  25. double FPS = video.get(CV_CAP_PROP_FPS);

  26. // 存储帧

  27. Mat frame;

  28. // 存储前一帧图像

  29. Mat temp;

  30. // 存储结果图像

  31. Mat result;

  32. for (int i = 0; i < frameCount; i++)

  33. {

  34. // 读帧进frame

  35. video >> frame;

  36. imshow("frame", frame);

  37. // 对帧进行异常检测

  38. if (frame.empty())

  39. {

  40. cout << "frame is empty!" << endl;

  41. break;

  42. }

  43. // 获取帧位置(第几帧)

  44. int framePosition = video.get(CV_CAP_PROP_POS_FRAMES);

  45. cout << "framePosition: " << framePosition << endl;

  46. // 如果为第一帧(temp还为空)

  47. if (i == 0)

  48. {

  49. // 调用MoveDetect()进行运动物体检测,返回值存入result

  50. result = MoveDetect(frame, frame);

  51. }

  52. //若不是第一帧(temp有值了)

  53. else

  54. {

  55. // 调用MoveDetect()进行运动物体检测,返回值存入result

  56. result = MoveDetect(temp, frame);

  57. }

  58. imshow("result", result);

  59. // 按原FPS显示

  60. if (waitKey(1000.0 / FPS) == 27)

  61. {

  62. cout << "ESC退出!" << endl;

  63. break;

  64. }

  65. temp = frame.clone();

  66. }

  67. return 0;

  68.  
  69.  
  70. }

  71. Mat MoveDetect(Mat temp, Mat frame)

  72. {

  73. Mat result = frame.clone();

  74. // 1.将background和frame转为灰度图

  75. Mat gray1, gray2;

  76. cvtColor(temp, gray1, CV_BGR2GRAY);

  77. cvtColor(frame, gray2, CV_BGR2GRAY);

  78. // 2.将background和frame做差

  79. Mat diff;

  80. absdiff(gray1, gray2, diff);

  81. imshow("diff", diff);

  82. // 3.对差值图diff_thresh进行阈值化处理

  83. Mat diff_thresh;

  84. threshold(diff, diff_thresh, 50, 255, CV_THRESH_BINARY);

  85. imshow("diff_thresh", diff_thresh);

  86. // 4.腐蚀

  87. Mat kernel_erode = getStructuringElement(MORPH_RECT, Size(3, 3));

  88. Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(18, 18));

  89. erode(diff_thresh, diff_thresh, kernel_erode);

  90. imshow("erode", diff_thresh);

  91. // 5.膨胀

  92. dilate(diff_thresh, diff_thresh, kernel_dilate);

  93. imshow("dilate", diff_thresh);

  94. // 6.查找轮廓并绘制轮廓

  95. vector<vector<Point>> contours;

  96. findContours(diff_thresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

  97. // 在result上绘制轮廓

  98. drawContours(result, contours, -1, Scalar(0, 0, 255), 2);

  99. // 7.查找正外接矩形

  100. vector<Rect> boundRect(contours.size());

  101. for (int i = 0; i < contours.size(); i++)

  102. {

  103. boundRect[i] = boundingRect(contours[i]);

  104. // 在result上绘制正外接矩形

  105. rectangle(result, boundRect[i], Scalar(0, 255, 0), 2);

  106. }

  107. // 返回result

  108. return result;

  109. }

CenterCenter

 

优点:

 

  • 帧间差分方法简单、运算量小且易于实现。
  • 帧间差分方法进行运动目标检测可以较强地适应动态环境的变化,有效地去除系统误差和噪声的影响,对场景中光照的变化不敏感而且不易受阴影的影响。

 

缺点:

 

  • 不能完全提取所有相关的特征像素点,也不能得到运动目标的完整轮廓,只能得到运动区域的大致轮廓;
  • 检测到的区域大小受物体的运动速度制约:对快速运动的物体,需要选择较小的时间间隔,如果选择不合适,当物体在前后两帧中没有重叠时,会被检测为两个分开的物体;对于慢速运动的物体,应该选择较大的时间差,如果时间选择不适当,当物体在前后两帧中几乎完全重叠时,则检测不到物体。
  • 容易在运动实体内部差生空洞现象。

 

三:光流法

 

简介:在计算机视觉中,Lucas–Kanade光流算法是一种两帧差分的光流估计算法。它由Bruce D. Lucas 和 Takeo

Kanade提出。
光流的概念:(Optical flow or optic flow)
它是一种运动模式,这种运动模式指的是一个物体、表面、边缘在一个视角下由一个观察者(比如眼睛、摄像头等)

和背景之间形成的明显移动。光流技术,如运动检测和图像分割,时间碰撞,运动补偿编码,三维立体视差,都是

利用了这种边缘或表面运动的技术。
二维图像的移动相对于观察者而言是三维物体移动的在图像平面的投影。
有序的图像可以估计出二维图像的瞬时图像速率或离散图像转移。

光流算法:
它评估了两幅图像的之间的变形,它的基本假设是体素和图像像素守恒。它假设一个物体的颜色在前后两帧没有巨大

而明显的变化。基于这个思路,我们可以得到图像约束方程。不同的光流算法解决了假定了不同附加条件的光流问题。

Lucas–Kanade算法:
这个算法是最常见,最流行的。它计算两帧在时间t 到t + δt之间每个每个像素点位置的移动。 由于它是基于图像信号

的泰勒级数,这种方法称为差分,这就是对于空间和时间坐标使用偏导数。

图像约束方程可以写为I (x ,y ,z ,t ) = I (x + δx ,y + δy ,z + δz ,t + δt )
I(x, y,z, t) 为在(x,y,z)位置的体素。
我们假设移动足够的小,那么对图像约束方程使用泰勒公式,我们可以得到:
201212042209368274.png

H.O.T. 指更高阶,在移动足够小的情况下可以忽略。从这个方程中我们可以得到:
201212042209366290.png
或者
201212042209374272.png
我们得到:

201212042209394356.png
V x ,V y ,V z 分别是I(x,y,z,t)的光流向量中x,y,z的组成。 201212042209462791.png201212042209468298.png201212042209461645.png和 201212042209468265.png则是图像在(x ,y ,z ,t )这一点向相应方向的差分 。
所以

I x V x + I y V y + I z V z = − I t。

写做:

201212042209471612.png

这个方程有三个未知量,尚不能被解决,这也就是所谓光流算法的光圈问题。那么要找到光流向量则需要另一套解决的方案。而Lucas-Kanade算法

是一个非迭代的算法:

假设流(Vx,Vy,Vz)在一个大小为m*m*m(m>1)的小窗中是一个常数,那么从像素1...n , n = m 3 中可以得到下列一组方程:

201212042209476039.png

20121204220947989.png

201212042209485101.png

201212042209485624.png

三个未知数但是有多于三个的方程,这个方程组自然是个超定方程,也就是说方程组内有冗余,方程组可以表示为:

201212042209482003.png

记作:201212042209498000.png

为了解决这个超定问题,我们采用最小二乘法:

201212042209496888.pngor

201212042209501772.png

得到:

201212042209519721.png

其中的求和是从1到n。

这也就是说寻找光流可以通过在四维上图像导数的分别累加得出。我们还需要一个权重函数W(i, j,k) , 201212042209512753.png来突出窗口中心点的

坐标。高斯函数做这项工作是非常合适的,

这个算法的不足在于它不能产生一个密度很高的流向量,例如在运动的边缘和黑大的同质区域中的微小移动方面流信息会很快的褪去。它的优点在于

有噪声存在的鲁棒性还是可以的。

简单来说,上图表现的就是光流,光流描述的是图像上每个像素点的灰度的位置(速度)变化情况,光流的研究是利用图像序列中的像素强度数据的时域变化和相关性来确定各自像素位置的“运动”。研究光流场的目的就是为了从图片序列中近似得到不能直接得到的运动场。
光流法的前提假设:
(1)相邻帧之间的亮度恒定;
(2)相邻视频帧的取帧时间连续,或者,相邻帧之间物体的运动比较“微小”;
(3)保持空间一致性;即,同一子图像的像素点具有相同的运动;

代码1:

 

 
  1. // Vedio_detect_human.cpp : 定义控制台应用程序的入口点。

  2. //

  3.  
  4. #include "stdafx.h"

  5. // 运动物体检测——光流法--LK金字塔

  6. #include<iostream>

  7. #include<opencv2\highgui\highgui.hpp>

  8. #include<opencv2\nonfree\nonfree.hpp>

  9. #include<opencv2\video\tracking.hpp>

  10.  
  11. using namespace std;

  12. using namespace cv;

  13.  
  14. Mat image1, image2;

  15. vector<Point2f> point1, point2, pointCopy;

  16. vector<uchar> status;

  17. vector<float> err;

  18.  
  19. int main()

  20. {

  21. VideoCapture video("D:\\opencv\\soft\\3.3.0\\win\\opencv\\sources\\samples\\data\\vtest.avi");

  22. // 获取视频帧率

  23. double fps = video.get(CV_CAP_PROP_FPS);

  24. // 两幅画面中间间隔

  25. double pauseTime = 1000 / fps;

  26. video >> image1;

  27. Mat image1Gray, image2Gray;

  28. cvtColor(image1, image1Gray, CV_RGB2GRAY);

  29. goodFeaturesToTrack(image1Gray, point1, 100, 0.01, 10, Mat());

  30. pointCopy = point1;

  31. // 绘制特征点位

  32. for (int i = 0; i<point1.size(); i++)

  33. {

  34. circle(image1, point1[i], 1, Scalar(0, 0, 255), 2);

  35. }

  36. namedWindow("LK--角点特征光流", 0);

  37. imshow("LK--角点特征光流", image1);

  38. while (true)

  39. {

  40. video >> image2;

  41. // 图像为空或Esc键按下退出播放

  42. if (!image2.data || waitKey(pauseTime) == 27)

  43. {

  44. break;

  45. }

  46. cvtColor(image2, image2Gray, CV_RGB2GRAY);

  47. // LK金字塔实现

  48. calcOpticalFlowPyrLK(image1Gray, image2Gray, point1, point2, status, err, Size(20, 20), 3);

  49. for (int i = 0; i<point2.size(); i++)

  50. {

  51. circle(image2, point2[i], 1, Scalar(0, 0, 255), 2);

  52. line(image2, pointCopy[i], point2[i], Scalar(255, 0, 0), 2);

  53. }

  54. imshow("LK金字塔实现--角点特征光流", image2);

  55. swap(point1, point2);

  56. image1Gray = image2Gray.clone();

  57. }

  58. return 0;

  59. }


Center

 

 

代码2:

 

 
  1. // Vedio_detect_human.cpp : 定义控制台应用程序的入口点。

  2. //

  3.  
  4. #include "stdafx.h"

  5. // 运动物体检测——光流法--LK金字塔

  6. #include <iostream>

  7. #include <opencv2/opencv.hpp>

  8. #include <opencv2/core/core.hpp>

  9. #include <opencv2/highgui/highgui.hpp>

  10. #include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur

  11. #include <opencv2/ml/ml.hpp>

  12. #include <opencv2/contrib/contrib.hpp>

  13.  
  14. using namespace cv;

  15. using namespace std;

  16.  
  17. void duan_OpticalFlow(Mat &frame, Mat & result);

  18. bool addNewPoints();

  19. bool acceptTrackedPoint(int i);

  20.  
  21. Mat image;

  22. vector<Point2f> point1, point2, pointCopy;

  23. Mat curgray; // 当前图片

  24. Mat pregray; // 预测图片

  25. vector<Point2f> point[2]; // point0为特征点的原来位置,point1为特征点的新位置

  26. vector<Point2f> initPoint; // 初始化跟踪点的位置

  27. vector<Point2f> features; // 检测的特征

  28. int maxCount = 1000; // 检测的最大特征数

  29. double qLevel = 0.01; // 特征检测的等级

  30. double minDist = 10.0; // 两特征点之间的最小距离

  31. vector<uchar> status; // 跟踪特征的状态,特征的流发现为1,否则为0

  32. vector<float> err;

  33.  
  34. int main()

  35. {

  36. Mat matSrc;

  37. Mat matRst;

  38.  
  39. VideoCapture cap("D:\\opencv\\soft\\3.3.0\\win\\opencv\\sources\\samples\\data\\vtest.avi");

  40. int totalFrameNumber = cap.get(CV_CAP_PROP_FRAME_COUNT);

  41.  
  42. cap >> image;

  43. Mat imageGray, image2Gray;

  44. cvtColor(image, imageGray, CV_RGB2GRAY);

  45. goodFeaturesToTrack(imageGray, point1, 100, 0.01, 10, Mat());

  46. pointCopy = point1;

  47. // 绘制特征点位

  48. for (int i = 0; i<point1.size(); i++)

  49. {

  50. circle(image, point1[i], 1, Scalar(0, 0, 255), 2);

  51. }

  52. namedWindow("LK--角点特征光流", 0);

  53. imshow("LK--角点特征光流", image);

  54.  
  55. // perform the tracking process

  56. cout << "开始检测视频,按下ESC键推出。" << endl;

  57. for (int nFrmNum = 0; nFrmNum < totalFrameNumber; nFrmNum++) {

  58. // 读取视频

  59. cap >> matSrc;

  60. if (!matSrc.empty())

  61. {

  62. duan_OpticalFlow(matSrc, matRst);

  63. cout << "该图片帧是 " << nFrmNum << endl;

  64. }

  65. else

  66. {

  67. cout << "获取视频帧数错误!" << endl;

  68. }

  69. if (waitKey(1) == 27) break;

  70. }

  71.  
  72. waitKey(0);

  73.  
  74. return 0;

  75. }

  76.  
  77. void duan_OpticalFlow(Mat &frame, Mat & result)

  78. {

  79. cvtColor(frame, curgray, CV_BGR2GRAY);

  80. frame.copyTo(result);

  81. // 添加特征点

  82. if (addNewPoints())

  83. {

  84. goodFeaturesToTrack(curgray, features, maxCount, qLevel, minDist);

  85. point[0].insert(point[0].end(), features.begin(), features.end());

  86. initPoint.insert(initPoint.end(), features.begin(), features.end());

  87. }

  88.  
  89. if (pregray.empty())

  90. {

  91. curgray.copyTo(pregray);

  92. }

  93.  
  94. calcOpticalFlowPyrLK(pregray, curgray, point[0], point[1], status, err);

  95. // 去除部分不好的光电

  96. int k = 0;

  97. for (size_t i = 0; i<point[1].size(); i++)

  98. {

  99. if (acceptTrackedPoint(i))

  100. {

  101. initPoint[k] = initPoint[i];

  102. point[1][k++] = point[1][i];

  103. }

  104. }

  105.  
  106. point[1].resize(k);

  107. initPoint.resize(k);

  108. // 现实特征点和运动轨迹

  109. for (size_t i = 0; i<point[1].size(); i++)

  110. {

  111. line(result, initPoint[i], point[1][i], Scalar(0, 0, 255));

  112. circle(result, point[1][i], 3, Scalar(0, 255, 0), -1);

  113. }

  114. // 更新该次结果作为下一次的参考

  115. swap(point[1], point[0]);

  116. swap(pregray, curgray);

  117.  
  118. imshow("LK--Demo", result);

  119. // waitKey(0);

  120. }

  121.  
  122. bool addNewPoints()

  123. {

  124. return point[0].size() <= 10;

  125. }

  126.  
  127. bool acceptTrackedPoint(int i)

  128. {

  129. return status[i] && ((abs(point[0][i].x - point[1][i].x) +

  130. abs(point[0][i].y - point[1][i].y)) > 2);

  131. }


Center

 

opencv源码给出的demo:

 

 
  1. // Vedio_detect_human.cpp : 定义控制台应用程序的入口点。

  2. //

  3.  
  4. #include "stdafx.h"

  5. // 运动物体检测——光流法--LK金字塔

  6. #include <stdio.h>

  7. #include <iostream>

  8. #include <opencv2/opencv.hpp>

  9. #include <opencv2/core/core.hpp>

  10. #include <opencv2/highgui/highgui.hpp>

  11. #include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur

  12. #include <opencv2/ml/ml.hpp>

  13. #include <opencv2/contrib/contrib.hpp>

  14.  
  15. #include <opencv2/video/tracking.hpp>

  16.  
  17.  
  18. using namespace cv;

  19.  
  20. static void convertFlowToImage(const Mat &flow_x, const Mat &flow_y, Mat &img_x, Mat &img_y, double lowerBound, double higherBound) {

  21. #define CAST(v, L, H) ((v) > (H) ? 255 : (v) < (L) ? 0 : cvRound(255*((v) - (L))/((H)-(L))))

  22. for (int i = 0; i < flow_x.rows; ++i) {

  23. for (int j = 0; j < flow_y.cols; ++j) {

  24. float x = flow_x.at<float>(i, j);

  25. float y = flow_y.at<float>(i, j);

  26. img_x.at<uchar>(i, j) = CAST(x, lowerBound, higherBound);

  27. img_y.at<uchar>(i, j) = CAST(y, lowerBound, higherBound);

  28. }

  29. }

  30. #undef CAST

  31. }

  32.  
  33. static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step, double, const Scalar& color)

  34. {

  35. for (int y = 0; y < cflowmap.rows; y += step)

  36. for (int x = 0; x < cflowmap.cols; x += step)

  37. {

  38. const Point2f& fxy = flow.at<Point2f>(y, x);

  39. line(cflowmap, Point(x, y), Point(cvRound(x + fxy.x), cvRound(y + fxy.y)),

  40. color);

  41. circle(cflowmap, Point(x, y), 2, color, -1);

  42. }

  43. }

  44.  
  45. int main(int argc, char** argv)

  46. {

  47. // IO operation

  48.  
  49. const char* keys =

  50. {

  51. "{ f | vidFile | ex2.avi | filename of video }"

  52. "{ x | xFlowFile | flow_x | filename of flow x component }"

  53. "{ y | yFlowFile | flow_y | filename of flow x component }"

  54. "{ i | imgFile | flow_i | filename of flow image}"

  55. "{ b | bound | 15 | specify the maximum of optical flow}"

  56. };

  57.  
  58. //CommandLineParser cmd(argc, argv, keys);

  59. //string vidFile = cmd.get<string>("vidFile");

  60. //string xFlowFile = cmd.get<string>("xFlowFile");

  61. //string yFlowFile = cmd.get<string>("yFlowFile");

  62. //string imgFile = cmd.get<string>("imgFile");

  63. //int bound = cmd.get<int>("bound");

  64. string vidFile = "vidFile";

  65. string xFlowFile = "xFlowFile";

  66. string yFlowFile = "yFlowFile";

  67. string imgFile = "imgFile";

  68. int bound = 80;

  69.  
  70.  
  71. namedWindow("video", 1);

  72. namedWindow("imgX", 1);

  73. namedWindow("imgY", 1);

  74. namedWindow("Demo", 1);

  75. //VideoCapture capture(vidFile);

  76. VideoCapture capture("D:\\opencv\\soft\\3.3.0\\win\\opencv\\sources\\samples\\data\\vtest.avi");

  77.  
  78. if (!capture.isOpened()) {

  79. printf("Could not initialize capturing..\n");

  80. return -1;

  81. }

  82.  
  83. int frame_num = 0;

  84. Mat image, prev_image, prev_grey, grey, frame, flow, cflow;

  85.  
  86. while (true) {

  87. capture >> frame;

  88. if (frame.empty())

  89. break;

  90. imshow("video", frame);

  91.  
  92. if (frame_num == 0) {

  93. image.create(frame.size(), CV_8UC3);

  94. grey.create(frame.size(), CV_8UC1);

  95. prev_image.create(frame.size(), CV_8UC3);

  96. prev_grey.create(frame.size(), CV_8UC1);

  97.  
  98. frame.copyTo(prev_image);

  99. cvtColor(prev_image, prev_grey, CV_BGR2GRAY);

  100.  
  101. frame_num++;

  102. continue;

  103. }

  104.  
  105. frame.copyTo(image);

  106. cvtColor(image, grey, CV_BGR2GRAY);

  107.  
  108. // calcOpticalFlowFarneback(prev_grey,grey,flow,0.5, 3, 15, 3, 5, 1.2, 0 );

  109. calcOpticalFlowFarneback(prev_grey, grey, flow, 0.702, 5, 10, 2, 7, 1.5, cv::OPTFLOW_FARNEBACK_GAUSSIAN);

  110.  
  111. prev_image.copyTo(cflow);

  112. drawOptFlowMap(flow, cflow, 12, 1.5, Scalar(0, 255, 0));

  113. imshow("cflow", cflow);

  114.  
  115. Mat flows[2];

  116. split(flow, flows);

  117. Mat imgX(flows[0].size(), CV_8UC1);

  118. Mat imgY(flows[0].size(), CV_8UC1);

  119. convertFlowToImage(flows[0], flows[1], imgX, imgY, -bound, bound);

  120. //char tmp[20];

  121. //sprintf(tmp, "_%04d.jpg", int(frame_num));

  122. //imwrite(xFlowFile + tmp, imgX);

  123. //imwrite(yFlowFile + tmp, imgY);

  124. //imwrite(imgFile + tmp, image);

  125.  
  126. std::swap(prev_grey, grey);

  127. std::swap(prev_image, image);

  128. frame_num = frame_num + 1;

  129.  
  130. imshow("imgX", imgX);

  131. imshow("imgY", imgY);

  132. imshow("Demo", image);

  133. if (waitKey(1) == 27) break;

  134. }

  135. waitKey(0);

  136. return 0;

  137. }


Center

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值