opencv中createBackgroundSubtractorMOG2 c++
时间: 2024-03-12 13:14:43 浏览: 22
`createBackgroundSubtractorMOG2` 是OpenCV库中的一个函数,用于创建一个基于高斯混合模型的背景减法器。它可以用于从视频中提取前景目标。
以下是一个使用 `createBackgroundSubtractorMOG2` 的C++示例代码:
```cpp
#include <opencv2/opencv.hpp>
int main() {
cv::VideoCapture capture("input_video.mp4");
if (!capture.isOpened()) {
std::cout << "Failed to open video file!" << std::endl;
return -1;
}
cv::Mat frame;
cv::Ptr<cv::BackgroundSubtractorMOG2> bgSubtractor = cv::createBackgroundSubtractorMOG2();
while (capture.read(frame)) {
cv::Mat foregroundMask;
bgSubtractor->apply(frame, foregroundMask);
cv::imshow("Foreground Mask", foregroundMask);
cv::imshow("Original Frame", frame);
if (cv::waitKey(30) == 'q') {
break;
}
}
capture.release();
cv::destroyAllWindows();
return 0;
}
```
在上述代码中,我们首先打开一个视频文件,然后使用 `createBackgroundSubtractorMOG2` 函数创建了一个背景减法器对象 `bgSubtractor`。然后,在每一帧上调用 `apply` 函数,将当前帧和背景模型作为参数传入,得到前景掩码 `foregroundMask`。最后,我们使用 `imshow` 函数显示原始帧和前景掩码,并通过按下 'q' 键来退出循环。
请确保在编译时链接OpenCV库,并将 "input_video.mp4" 替换为你要处理的视频文件路径。