基于c++ opencv4.6做三帧间差法检测物体
时间: 2023-07-25 11:04:18 浏览: 160
test_opencv_帧差法识别视频中的静止物体_
5星 · 资源好评率100%
三帧间差法是一种简单有效的运动目标检测方法,可以通过比较相邻的三帧图像像素值的差异来检测运动物体。下面是基于C++和OpenCV4.6实现三帧间差法的步骤:
1. 读取视频并初始化三个Mat对象:currentFrame, previousFrame和nextFrame。
```c++
VideoCapture capture("video.mp4");
Mat currentFrame, previousFrame, nextFrame;
capture >> previousFrame;
capture >> currentFrame;
capture >> nextFrame;
```
2. 将帧转换为灰度图像,以便进行差分计算。
```c++
cvtColor(previousFrame, previousFrame, COLOR_BGR2GRAY);
cvtColor(currentFrame, currentFrame, COLOR_BGR2GRAY);
cvtColor(nextFrame, nextFrame, COLOR_BGR2GRAY);
```
3. 计算相邻帧之间的差异,并将其存储在Mat对象中。
```c++
Mat diff1, diff2;
absdiff(previousFrame, currentFrame, diff1);
absdiff(currentFrame, nextFrame, diff2);
```
4. 对两个差分图像进行二值化处理,以便提取物体的运动。
```c++
threshold(diff1, diff1, 30, 255, THRESH_BINARY);
threshold(diff2, diff2, 30, 255, THRESH_BINARY);
```
5. 将两个二值化的图像进行逻辑与运算,以便提取出物体的移动区域。
```c++
Mat motionMask;
bitwise_and(diff1, diff2, motionMask);
```
6. 对运动区域进行形态学处理,以便去除噪声并填充空洞。
```c++
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(motionMask, motionMask, MORPH_OPEN, kernel);
morphologyEx(motionMask, motionMask, MORPH_CLOSE, kernel);
```
7. 显示运动区域,并等待按下任意键退出程序。
```c++
imshow("Motion Mask", motionMask);
waitKey(0);
```
完整的代码如下所示:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
VideoCapture capture("video.mp4");
Mat currentFrame, previousFrame, nextFrame;
capture >> previousFrame;
capture >> currentFrame;
capture >> nextFrame;
cvtColor(previousFrame, previousFrame, COLOR_BGR2GRAY);
cvtColor(currentFrame, currentFrame, COLOR_BGR2GRAY);
cvtColor(nextFrame, nextFrame, COLOR_BGR2GRAY);
while (true)
{
Mat diff1, diff2;
absdiff(previousFrame, currentFrame, diff1);
absdiff(currentFrame, nextFrame, diff2);
threshold(diff1, diff1, 30, 255, THRESH_BINARY);
threshold(diff2, diff2, 30, 255, THRESH_BINARY);
Mat motionMask;
bitwise_and(diff1, diff2, motionMask);
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(motionMask, motionMask, MORPH_OPEN, kernel);
morphologyEx(motionMask, motionMask, MORPH_CLOSE, kernel);
imshow("Motion Mask", motionMask);
char key = waitKey(1);
if (key == 27) break;
previousFrame = currentFrame;
currentFrame = nextFrame;
capture >> nextFrame;
if (nextFrame.empty()) break;
cvtColor(nextFrame, nextFrame, COLOR_BGR2GRAY);
}
return 0;
}
```
阅读全文