背景消除或背景减法是这样一种假设。我们有2个图片,一个是静止的,比如场景,没有需要检测的东西,另一个照片则包含了要检测的对象,但他是侵入了背景里的东西,或对象。我们就是要检测这个东西,比如商场进入的小偷,老鼠,或者马路上通过的车辆。

利用背景减法,我们容易找到我们感兴趣的东西。先看看下面2张图片:

右边图片是我们的背景,左边图片是我们的结果,我们找到感兴趣的部分,就是框起来的部分。框起来前就是我们对比的图片,或者叫变化的图片。有这个教授坐在椅子上的部分。

本程序除了opencv 要安装好外,还要装好imutils。imutils 的下载和安装在 Python 下应用opencv 的简单功能演示 一文中有介绍。

本文的原始代码来自 https://www.pyimagesearch.com/2016/11/21/raspbian-opencv-pre-configured-and-pre-installed/ 的一个教学讲稿。

代码开始部分

注释里介绍使用方法:

python image_sub.py --bg 背景文件名  --fg 前景文件名

然后输入必要的包,命令行参数处理,这里有缺省参数,你可修改default 后的文件路径和名

# USAGE 使用方法
# python image_sub.py --bg images/bg.jpg --fg images/adrian.jpg# import the necessary packages  输入必要的包
import numpy as np
import argparse
import imutils
import cv2# construct the argument parser and parse the arguments
# 命令行参数处理,2个图片都存在imges 目录里,这里提供缺省值
# 这根据你的情况,更改default 后的文件名,当然也可命令行输入
ap = argparse.ArgumentParser()
ap.add_argument("-b", "--bg", default='images/bg.jpg',help="path to background image")
ap.add_argument("-f", "--fg", default='images/adrian.jpg',help="path to foreground image")
args = vars(ap.parse_args())

导入图片并灰度化处理

# load the background and foreground images
# 导入背景,前景文件
bg = cv2.imread(args["bg"])
fg = cv2.imread(args["fg"])# convert the background and foreground images to grayscale
# 灰度化处理
bgGray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
fgGray = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)

背景减法

做减法时,转换为int32,这样可以有负值。然后取绝对值,再转成类型uint8, opencv可以识别。

# perform background subtraction by subtracting the foreground from
# the background and then taking the absolute value
# 背景减法
sub = bgGray.astype("int32") - fgGray.astype("int32")
sub = np.absolute(sub).astype("uint8")
cv2.imshow("sub",sub)

二值化处理

用Otsu 门槛法,转换上面的减法结果为前景和背景,0为背景,255为前景。图片效果为下面左边图。

然后我们erosion,再 dilate消除噪声,处理效果为下面右边图:

erosion dilate 的详细介绍可以看:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html

# perform a series of erosions and dilations to remove noise
# erode ,dilate 降噪处理
thresh = cv2.erode(thresh, None, iterations=1)
thresh = cv2.dilate(thresh, None, iterations=1)
cv2.imshow("thresh2",thresh)

发现各个边界 ,然后计算所有边界的范围

# find contours in the thresholded difference map and then initialize
# 发现边界
# our bounding box regions that contains the *entire* region of motion
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)#给边界初始值
(minX, minY) = (np.inf, np.inf)
(maxX, maxY) = (-np.inf, -np.inf)# loop over the contours
# 循环计算边界
for c in cnts:# compute the bounding box of the contour(x, y, w, h) = cv2.boundingRect(c)# reduce noise by enforcing requirements on the bounding box size# 如果边界值,w 或 w 小于20 就认为是噪音if w > 20 and h > 20:# update our bookkeeping variablesminX = min(minX, x)minY = min(minY, y)maxX = max(maxX, x + w - 1)maxY = max(maxY, y + h - 1)

绘制长方形,并输出图形

# draw a rectangle surrounding the region of motion
# 绘制长方形
cv2.rectangle(fg, (minX, minY), (maxX, maxY), (0, 255, 0), 2)# show the output image
# 输出图形
cv2.imshow("Output", fg)
cv2.imshow("bg", bg)
cv2.waitKey(0)

综合在一起的代码:

# USAGE 使用方法
# python image_sub.py --bg images/bg.jpg --fg images/adrian.jpg# import the necessary packages  输入必要的包
import numpy as np
import argparse
import imutils
import cv2# construct the argument parser and parse the arguments
# 命令行参数处理,2个图片都存在imges 目录里,这里提供缺省值
# 这根据你的情况,更改default 后的文件名,当然也可命令行输入
ap = argparse.ArgumentParser()
ap.add_argument("-b", "--bg", default='images/bg.jpg',help="path to background image")
ap.add_argument("-f", "--fg", default='images/adrian.jpg',help="path to foreground image")
args = vars(ap.parse_args())# load the background and foreground images
# 导入背景,前景文件
bg = cv2.imread(args["bg"])
fg = cv2.imread(args["fg"])# convert the background and foreground images to grayscale
# 灰度化处理
bgGray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
fgGray = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)# perform background subtraction by subtracting the foreground from
# the background and then taking the absolute value
# 背景减法
sub = bgGray.astype("int32") - fgGray.astype("int32")
sub = np.absolute(sub).astype("uint8")
cv2.imshow("sub",sub)# threshold the image to find regions of the subtracted image with
# larger pixel differences
thresh = cv2.threshold(sub, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv2.imshow("thresh",thresh)# perform a series of erosions and dilations to remove noise
# erode ,dilate 降噪处理
thresh = cv2.erode(thresh, None, iterations=1)
thresh = cv2.dilate(thresh, None, iterations=1)
cv2.imshow("thresh2",thresh)# find contours in the thresholded difference map and then initialize
# 发现边界
# our bounding box regions that contains the *entire* region of motion
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)#给边界初始值
(minX, minY) = (np.inf, np.inf)
(maxX, maxY) = (-np.inf, -np.inf)# loop over the contours
# 循环计算边界
for c in cnts:# compute the bounding box of the contour(x, y, w, h) = cv2.boundingRect(c)# reduce noise by enforcing requirements on the bounding box size# 如果边界值,w 或 w 小于20 就认为是噪音if w > 20 and h > 20:# update our bookkeeping variablesminX = min(minX, x)minY = min(minY, y)maxX = max(maxX, x + w - 1)maxY = max(maxY, y + h - 1)# draw a rectangle surrounding the region of motion
# 绘制长方形
cv2.rectangle(fg, (minX, minY), (maxX, maxY), (0, 255, 0), 2)# show the output image
# 输出图形
cv2.imshow("Output", fg)
cv2.imshow("bg", bg)
cv2.waitKey(0)

Python下应用opencv 背景消除或图片减法相关推荐

  1. 基于Python下的OpenCv人脸检测

    基于Python下的OpenCv人脸识别模拟 1.Pycharm下OpenCv的安装 2.人脸识别的原理 目标实现 基本原理 3.代码实现: 实现步骤 参考示意图: 1.Pycharm下OpenCv的 ...

  2. python下常用OpenCV代码

    1.python下OpenCV版本 python import cv2 cv2.__version__ 待续

  3. python opencv gpu加速_让Python下的OpenCV也能GPU加速!part.1

    20200411更新: 经过评论区 @鹤汀凫渚 的指导,我成功的用最简单的方法在python中调用到了GPU加速后的函数,这里把这位朋友的评论贴出来供各位参考: 以下原文: 本文的核心目的就是加速,在 ...

  4. 基于(Python下的OpenCV)图像处理的喷墨墨滴形状规范检测

    通过图像处理,分析数码印花的喷头所喷出来的墨滴形状,与标准墨滴形状对比分析,来判断墨水及其喷头设备的状态,由两部分构成 PS:获取墨滴形状照片和标准墨滴形状照片都是手绘的,将就的看吧,主要功能已经实现 ...

  5. Python下应用opencv 人脸检测

    使用OpenCV's Haar cascades作为人脸检测,因为他做好了库,我们只管使用. 代码简单,除去注释,总共有效代码只有10多行. 所谓库就是一个检测人脸的xml 文件,可以网上查找,下面是 ...

  6. Opencv --- 背景消除建模(BSM)

    1. 基本原理 BSM适用于背景不变的情况下. 2. 相关API 3. 代码演示 #include<iostream> #include<opencv2/opencv.hpp> ...

  7. #最全面# Python 下将 opencv MAT ( numpy ndarray ) 彩色 或 灰度 图像转化为 QImage 对象

    1. 直接将ndarray彩色图像转化为 QImage 对象: #解决中文路径下cv2无法读取的问题 #path为文件路径 colorimg = cv2.imdecode(np.fromfile(pa ...

  8. opencv在python环境下的安装_关于python环境下的opencv安装

    吐槽: 这一天我终于记起了这个博客.今天搞python环境下的opencv,又弄了一天,很烦躁.之前配置VS的opencv也是花了好久的时间,然后突然发现之前记录在电脑上的文档都找不到了,于是决定还是 ...

  9. python图像拼接_python opencv 图像拼接的实现方法

    初级的图像拼接为将两幅图像简单的粘贴在一起,仅仅是图像几何空间的转移与合成,与图像内容无关.高级图像拼接也叫作基于特征匹配的图像拼接,拼接时消去两幅图像相同的部分,实现拼接合成全景图. 具有相同尺寸的 ...

最新文章

  1. RabbitMQ学习笔记一:本地Windows环境安装RabbitMQ Server
  2. 四位达林顿_ULN2069B - 80 V - 1.5 A四路达林顿开关 - STMicroelectronics
  3. Apache Derby数据库用户和权限
  4. public 函数_UE4精品教程 | 渲染编程(C++篇)【第三卷:从仿函数到std::function再到虚幻4Delegate】...
  5. 微服务feignclient_搞微服务用阿里开源的 Nacos 真香啊
  6. python中的for语句可以在任意序列_python在循环内任意增加迭代器
  7. Maven是个什么鬼?,没办法起床排bug...
  8. 怎么用计算机按键弹歌谱,键盘钢琴及谱子(弹钢琴练打字一举两得)
  9. python使用matplotlib可视化线图(line plot)、使用semilogy函数将Y轴数据处理为对数坐标(logarithmic scale in Matplotlib)
  10. PDF转换器可以做到PDF转Office,TXT,HTM,PDF文件;PDF合并拆分,压缩,加密解密!
  11. Flask项目: 蓝本
  12. VB读取武林外传内存地址
  13. 我的学习笔记001--private protected public internal mxx
  14. Codeforces Round #548 (Div. 2), problem: (C) Edgy Trees 【并查集+快速幂】
  15. Chapter2、HDR流水线
  16. 施努卡:国内机器视觉公司(哪些公司做机器视觉检测特别厉害的)
  17. 单文件组件下的vue,可以擦出怎样的火花
  18. 读何敬才同志的哀祭诗
  19. Diary(八)——日志信息删除与修改(下)
  20. 查看网页上保存的密码-Google Chrome

热门文章

  1. r生成新的dataframe_R语言中数据框的定义与使用
  2. 软件测试实习生培训大纲
  3. FileSaver+xlsx 表格下载为excel
  4. hbw-utils - 基本数据类型进制转换的实现
  5. Android异常大全
  6. Netty源码剖析之内存池和对象池设计流程
  7. 中科院计算所培训中心开启课程研发新征程
  8. 牛客练习赛91A~D
  9. leetcode刷题记录2:进度64, 2021.10.23
  10. NBT|45种单细胞轨迹推断方法比较,110个实际数据集和229个合成数据集