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

cpp 复制代码
// 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'来退出程序。

The end

相关推荐
网安INF2 分钟前
【论文阅读】-《HopSkipJumpAttack: A Query-Efficient Decision-Based Attack》
论文阅读·人工智能·深度学习·网络安全·对抗攻击
qq_526099136 分钟前
图像采集卡与工业相机:机器视觉“双剑合璧”的效能解析
图像处理·数码相机·计算机视觉
你知道网上冲浪吗18 分钟前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
l1t1 小时前
利用DeepSeek辅助WPS电子表格ET格式分析
人工智能·python·wps·插件·duckdb
plusplus1682 小时前
边缘智能实战手册:攻克IoT应用三大挑战的AI战术
人工智能·物联网
地平线开发者2 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy2 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
果粒橙_LGC2 小时前
论文阅读系列(一)Qwen-Image Technical Report
论文阅读·人工智能·学习
雷达学弱狗2 小时前
backward怎么计算的是torch.tensor(2.0, requires_grad=True)变量的梯度
人工智能·pytorch·深度学习
Seeklike2 小时前
diffuxers学习--AutoPipeline
人工智能·python·stable diffusion·diffusers