【opencv】示例-bgfg_segm 背景分割:利用背景减去算法(KNN、MOG2)分离图像中运动物体(前景)和静止背景图像...

d7bdbbe92eefc47bd2ebfd1ae0b0db49.png

78f54fd780c3026dbb1c7fe01ad76575.png

// OpenCV项目的一部分。
// 它遵从分布及 http://opencv.org/license.html 顶级目录下的LICENSE文件中的许可条款


// 包含OpenCV相关头文件
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/video.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include <iostream> // 包含输入输出流的头文件


// 使用标准命名空间和OpenCV命名空间
using namespace std;
using namespace cv;


// 主函数,程序入口
int main(int argc, const char** argv)
{
    // 定义命令行参数
    const String keys = "{c camera     | 0 | use video stream from camera (device index starting from 0) }"
                        "{fn file_name |   | use video file as input }"
                        "{m method | mog2 | method: background subtraction algorithm ('knn', 'mog2')}"
                        "{h help | | show help message}";
    // 命令行解析器
    CommandLineParser parser(argc, argv, keys);
    // 解析器相关描述
    parser.about("This sample demonstrates background segmentation.");
    // 若有"help"参数,则打印帮助信息并退出程序
    if (parser.has("help"))
    {
        parser.printMessage();
        return 0;
    }
    // 获取摄像机索引、文件名称和方法参数
    int camera = parser.get<int>("camera");
    String file = parser.get<String>("file_name");
    String method = parser.get<String>("method");
    // 若参数解析出现错误则打印错误并退出
    if (!parser.check())
    {
        parser.printErrors();
        return 1;
    }


    // 视频捕获对象
    VideoCapture cap;
    // 如果文件名为空则打开摄像头,否则打开视频文件
    if (file.empty())
        cap.open(camera);
    else
    {
        file = samples::findFileOrKeep(file);  // 忽略gstreamer管道
        cap.open(file.c_str());
    }
    // 若视频流打不开则打印错误并退出
    if (!cap.isOpened())
    {
        cout << "Can not open video stream: '" << (file.empty() ? "<camera>" : file) << "'" << endl;
        return 2;
    }


    // 背景减去模型的智能指针
    Ptr<BackgroundSubtractor> model;
    // 根据方法参数创建对应的背景模型
    if (method == "knn")
        model = createBackgroundSubtractorKNN();
    else if (method == "mog2")
        model = createBackgroundSubtractorMOG2();
    // 若模型为空则打印错误并退出
    if (!model)
    {
        cout << "Can not create background model using provided method: '" << method << "'" << endl;
        return 3;
    }


    // 输出控制信息
    cout << "Press <space> to toggle background model update" << endl;
    cout << "Press 's' to toggle foreground mask smoothing" << endl;
    cout << "Press ESC or 'q' to exit" << endl;
    // 用户控制变量
    bool doUpdateModel = true;
    bool doSmoothMask = false;


    // 存储帧数据的Mat对象
    Mat inputFrame, frame, foregroundMask, foreground, background;
    // 无限循环读取视频帧
    for (;;)
    {
        // 准备输入帧
        cap >> inputFrame;
        // 如果帧为空则退出循环
        if (inputFrame.empty())
        {
            cout << "Finished reading: empty frame" << endl;
            break;
        }
        // 设置帧大小
        const Size scaledSize(640, 640 * inputFrame.rows / inputFrame.cols);
        // 缩放帧到新的尺寸
        resize(inputFrame, frame, scaledSize, 0, 0, INTER_LINEAR);


        // 传递帧到背景模型
        model->apply(frame, foregroundMask, doUpdateModel ? -1 : 0);


        // 显示缩放后的帧
        imshow("image", frame);


        // 显示前景图像和掩码(可选平滑处理)
        if (doSmoothMask)
        {
            GaussianBlur(foregroundMask, foregroundMask, Size(11, 11), 3.5, 3.5);
            threshold(foregroundMask, foregroundMask, 10, 255, THRESH_BINARY);
        }
        // 初始化并更新前景
        if (foreground.empty())
            foreground.create(scaledSize, frame.type());
        foreground = Scalar::all(0);
        frame.copyTo(foreground, foregroundMask);
        // 显示前景掩码和图像
        imshow("foreground mask", foregroundMask);
        imshow("foreground image", foreground);


        // 显示背景图像
        model->getBackgroundImage(background);
        if (!background.empty())
            imshow("mean background image", background );


        // 与用户交互
        const char key = (char)waitKey(30);
        if (key == 27 || key == 'q') // ESC键
        {
            cout << "Exit requested" << endl;
            break;
        }
        else if (key == ' ')
        {
            // 切换是否更新背景模型的标志
            doUpdateModel = !doUpdateModel;
            cout << "Toggle background update: " << (doUpdateModel ? "ON" : "OFF") << endl;
        }
        else if (key == 's')
        {
            // 切换是否平滑前景掩码的标志
            doSmoothMask = !doSmoothMask;
            cout << "Toggle foreground mask smoothing: " << (doSmoothMask ? "ON" : "OFF") << endl;
        }
    }
    // 程序正常退出
    return 0;
}

该代码是使用OpenCV库编写的背景分割示例程序。在OpenCV的帮助下,它可以从视频流(无论是摄像头还是视频文件)中获取帧,并利用背景减去算法(如KNN或MOG2)来分离图像中的运动物体(前景)和静止的背景图像。程序提供了用空格键切换更新背景模型的选项,以及用's'键切换是否对前景掩码应用平滑处理的选项。此外,用户可以通过按下ESC键或'q'来退出程序。

97cebd1b51f132029ea48b4822b045c0.png

6f464a48c3bcc671eb9ba8056bf1522b.png

1bc449bec46e58cb42197590a4243953.png

496c1bdd8bf40288f5b6e937ef963f05.png

The end

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值