使用OpenCV实现背景减除

一、概述

  实现步骤:

  1.将图像转为灰度图

  2.使用滤波器去除图像中的噪音

  3.创建一个光模式图像

  4.用光模式矩阵减去处理过后的图像矩阵

  5.输出图像

  ps:此案例并不适合所有的情况,特别是生成光模式背景。如果是较为复杂且是彩色图像则完全没法发使用这种方式生成。

二、示例代码

  //原图
    Mat src = imread(inputImagePath);
    imshow("input", src);
    waitKey(0);
    //灰度图
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    //中值滤波去除椒盐噪声,此处卷积核用3、5都不是很理想,所以选择了7。有兴趣可以试试其他的。
    Mat mBlur;
    medianBlur(gray, mBlur, 7);
    imshow("mBlur", mBlur);
    waitKey(0);
    //对原始图像执行大模糊以得到光模式(和输入图像背景差不多的的背景图)
    Mat pattern;
    blur(mBlur, pattern, Size(mBlur.cols / 3, mBlur.rows / 3));
    imshow("pattern", pattern);
    waitKey(0);
    //减除输入图像背景:有两种算法:1.减法=光模式图像-原始矩阵图像。2.除法=255*(1-(原生图像/光模式))
    Mat removeLightPattern;
    removeLightPattern = pattern - mBlur;
    //输出背景减除后的图像
    imshow("removeLightPattern", removeLightPattern);
    waitKey(0);

三、测试对比效果图

  对比图1:

  

  

原文地址:https://www.cnblogs.com/tony-yang-flutter/p/14845751.html