写代码opencv之运动检测 调用摄像头 用c++ 构建cmake 函数
时间: 2024-05-01 11:18:11 浏览: 11
您好,关于运动检测的问题,以下是一个简单的示例,您可以参考一下:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
VideoCapture cap(0); // 打开默认摄像头
if (!cap.isOpened()) { // 检查摄像头是否成功打开
cerr << "Failed to open camera!" << endl;
return -1;
}
Mat previous, current, difference;
int threshold_value = 30; // 阈值
int max_BINARY_value = 255;
namedWindow("Camera Input", WINDOW_AUTOSIZE);
namedWindow("Motion Detection Result", WINDOW_AUTOSIZE);
while (true) {
cap >> current; // 读取当前帧
if (current.empty())
break;
cvtColor(current, current, COLOR_BGR2GRAY);
if (previous.empty()) { // 如果是第一帧,就将当前帧作为前一帧
previous = current;
continue;
}
absdiff(current, previous, difference); // 计算当前帧与前一帧的差
threshold(difference, difference, threshold_value, max_BINARY_value, THRESH_BINARY); // 二值化差图像
imshow("Camera Input", current);
imshow("Motion Detection Result", difference);
if (waitKey(10) == 'q') // 按下q键退出
break;
previous = current;
}
return 0;
}
```
此外,关于如何使用cmake构建这个C++程序,您可以在项目根目录下创建一个CMakeLists.txt文件,并添加以下内容:
```cmake
cmake_minimum_required(VERSION 3.0)
project(motion_detection)
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable(motion_detection main.cpp)
target_link_libraries( motion_detection ${OpenCV_LIBS} )
```
然后在项目根目录下创建一个build目录,进入该目录,运行以下命令:
```shell
cmake ..
make
```
这样就可以编译生成可执行文件了。