老黄实验:基于图像差异的异物入侵检测系统 - 完整开发文档

微信公众号 老黄编程

CSDN 老黄编程

email: wilsonwong@126.com

Copyright © 2026 黄锦威. All rights reserved.


目录

  1. 系统概述
  2. 关键技术理论(展开细节看附录E.)
  3. 系统架构图
  4. 流程图
  5. 时序图
  6. 类图
  7. 模块功能详解
  8. 命令行调用范例
  9. 调参策略
  10. 应用场景参数配置速查表
  11. 中英文对照表

1. 系统概述

1.1 系统简介

本系统是一个基于图像差异的异物入侵检测系统,通过融合多种检测器(MOG2背景减除、帧差法、自适应背景建模),实现对监控视频中入侵目标的实时检测和报警。支持自定义多边形入侵区域,提供交互式区域绘制工具。

1.2 核心功能

功能模块 功能描述
入侵检测 融合三种检测器检测运动目标
区域管理 支持不规则多边形入侵区域定义
场景识别 智能识别光照、天气、图像质量等场景
参数自适应 根据场景自动调整检测参数
目标跟踪 跨帧关联同一目标,计算持续时间
报警系统 基于持续时间和面积的报警机制

2. 关键技术理论

2.1 图像差异检测理论基础

2.1.1 运动检测概述

运动检测是计算机视觉中的基础问题,其目标是从视频序列中提取出运动区域。本系统采用三种互补的运动检测方法:背景减除法、帧差法和自适应背景建模法。

2.1.2 混合高斯模型(MOG2)

理论原理
混合高斯模型(Gaussian Mixture Model, GMM)是一种基于统计的背景建模方法。其核心思想是利用多个高斯分布对图像中每个像素的历史值进行建模,通过判断当前像素值与模型的匹配程度来区分前景和背景。

数学模型
对于每个像素,其历史值被建模为K个高斯分布的混合:

P ( I t ) = ∑ i = 1 K ω i , t ⋅ η ( I t ; μ i , t , Σ i , t ) P(I_t) = \sum_{i=1}^{K} \omega_{i,t} \cdot \eta(I_t; \mu_{i,t}, \Sigma_{i,t}) P(It)=i=1Kωi,tη(It;μi,t,Σi,t)

其中:

  • I t I_t It 为t时刻的像素值
  • ω i , t \omega_{i,t} ωi,t 为第i个高斯分布的权重
  • μ i , t \mu_{i,t} μi,t 为第i个高斯分布的均值
  • Σ i , t \Sigma_{i,t} Σi,t 为第i个高斯分布的协方差矩阵
  • η \eta η 为高斯概率密度函数

参数更新
当新像素值到来时,按以下规则更新模型:

  1. 匹配检测: ∣ I t − μ i , t − 1 ∣ ≤ D ⋅ σ i , t − 1 |I_t - \mu_{i,t-1}| \leq D \cdot \sigma_{i,t-1} Itμi,t1Dσi,t1
  2. 权重更新: ω i , t = ( 1 − α ) ω i , t − 1 + α M i , t \omega_{i,t} = (1-\alpha)\omega_{i,t-1} + \alpha M_{i,t} ωi,t=(1α)ωi,t1+αMi,t
  3. 均值更新: μ i , t = ( 1 − ρ ) μ i , t − 1 + ρ I t \mu_{i,t} = (1-\rho)\mu_{i,t-1} + \rho I_t μi,t=(1ρ)μi,t1+ρIt
  4. 方差更新: σ i , t 2 = ( 1 − ρ ) σ i , t − 1 2 + ρ ( I t − μ i , t ) 2 \sigma_{i,t}^2 = (1-\rho)\sigma_{i,t-1}^2 + \rho (I_t - \mu_{i,t})^2 σi,t2=(1ρ)σi,t12+ρ(Itμi,t)2

其中:

  • α \alpha α 为学习率
  • ρ = α ⋅ η ( I t ; μ i , t − 1 , Σ i , t − 1 ) \rho = \alpha \cdot \eta(I_t; \mu_{i,t-1}, \Sigma_{i,t-1}) ρ=αη(It;μi,t1,Σi,t1)
  • M i , t M_{i,t} Mi,t 为匹配指示函数

阴影检测
MOG2算法通过分析像素值在RGB或HSV空间中的变化来检测阴影。阴影通常表现为亮度降低而色度基本不变,算法可将其标记为灰色区域而非前景。

2.1.3 帧差法

理论原理
帧差法是最简单的运动检测方法,通过计算相邻两帧之间的差异来提取运动区域。其理论基础是:运动目标在连续帧中位置发生变化,导致对应像素值产生显著差异。

数学模型

D t ( x , y ) = ∣ I t ( x , y ) − I t − 1 ( x , y ) ∣ D_t(x,y) = |I_t(x,y) - I_{t-1}(x,y)| Dt(x,y)=It(x,y)It1(x,y)

M t ( x , y ) = { 255 if  D t ( x , y ) > T 0 otherwise M_t(x,y) = \begin{cases} 255 & \text{if } D_t(x,y) > T \\ 0 & \text{otherwise} \end{cases} Mt(x,y)={2550if Dt(x,y)>Totherwise

其中:

  • I t ( x , y ) I_t(x,y) It(x,y) 为t时刻图像坐标 ( x , y ) (x,y) (x,y)的像素值
  • D t ( x , y ) D_t(x,y) Dt(x,y) 为帧间差异
  • T T T 为预设阈值
  • M t ( x , y ) M_t(x,y) Mt(x,y) 为运动掩码

优点与局限

  • 优点:计算简单、速度快、对光照变化不敏感
  • 局限:产生"双影"效果、无法检测静止目标、对慢速运动不敏感
2.1.4 自适应背景建模

理论原理
自适应背景建模采用指数加权移动平均(Exponentially Weighted Moving Average, EWMA)方法,这是一种递归滤波算法,能够根据历史信息动态更新背景模型。

数学模型

B t ( x , y ) = ( 1 − α ) ⋅ B t − 1 ( x , y ) + α ⋅ I t ( x , y ) B_t(x,y) = (1-\alpha) \cdot B_{t-1}(x,y) + \alpha \cdot I_t(x,y) Bt(x,y)=(1α)Bt1(x,y)+αIt(x,y)

其中:

  • B t ( x , y ) B_t(x,y) Bt(x,y) 为t时刻的背景模型值
  • α \alpha α 为学习率( 0 < α < 1 0 < \alpha < 1 0<α<1
  • I t ( x , y ) I_t(x,y) It(x,y) 为当前帧像素值

学习率 α \alpha α 控制背景更新的速度:

  • α \alpha α 较大:背景更新快,适应快速变化
  • α \alpha α 较小:背景更新慢,模型更稳定

前景检测

F t ( x , y ) = ∣ I t ( x , y ) − B t ( x , y ) ∣ F_t(x,y) = |I_t(x,y) - B_t(x,y)| Ft(x,y)=It(x,y)Bt(x,y)

M t ( x , y ) = { 255 if  F t ( x , y ) > T t 0 otherwise M_t(x,y) = \begin{cases} 255 & \text{if } F_t(x,y) > T_t \\ 0 & \text{otherwise} \end{cases} Mt(x,y)={2550if Ft(x,y)>Ttotherwise

自适应阈值
本系统采用基于图像统计的自适应阈值策略:

T t = max ⁡ ( T m i n , min ⁡ ( T m a x , μ d i f f ⋅ k ) ) T_t = \max(T_{min}, \min(T_{max}, \mu_{diff} \cdot k)) Tt=max(Tmin,min(Tmax,μdiffk))

其中:

  • μ d i f f \mu_{diff} μdiff 为差异图像的平均值
  • k k k 为比例系数
  • T m i n , T m a x T_{min}, T_{max} Tmin,Tmax 为阈值边界

2.2 形态学图像处理

2.2.1 腐蚀与膨胀

腐蚀(Erosion)
( A ⊖ B ) ( x , y ) = min ⁡ ( i , j ) ∈ B A ( x + i , y + j ) (A \ominus B)(x,y) = \min_{(i,j) \in B} A(x+i, y+j) (AB)(x,y)=(i,j)BminA(x+i,y+j)

腐蚀用于消除小的噪声点和分离粘连目标。

膨胀(Dilation)
( A ⊕ B ) ( x , y ) = max ⁡ ( i , j ) ∈ B A ( x + i , y + j ) (A \oplus B)(x,y) = \max_{(i,j) \in B} A(x+i, y+j) (AB)(x,y)=(i,j)BmaxA(x+i,y+j)

膨胀用于填充目标内部的孔洞和连接断裂区域。

2.2.2 开运算与闭运算

开运算(Opening)
A ∘ B = ( A ⊖ B ) ⊕ B A \circ B = (A \ominus B) \oplus B AB=(AB)B

开运算先腐蚀后膨胀,用于去除孤立的噪声点。

闭运算(Closing)
A ∙ B = ( A ⊕ B ) ⊖ B A \bullet B = (A \oplus B) \ominus B AB=(AB)B

闭运算先膨胀后腐蚀,用于填充目标内部的孔洞。

2.3 轮廓分析

2.3.1 轮廓提取

轮廓提取基于边界跟踪算法,常见的有Suzuki算法。该算法通过扫描二值图像,识别并跟踪连通区域的边界像素。

算法步骤

  1. 逐行扫描二值图像
  2. 检测到边界起始点后开始跟踪
  3. 沿边界方向移动,记录边界点坐标
  4. 返回起始点完成轮廓跟踪
  5. 继续扫描直到完成所有轮廓提取
2.3.2 轮廓特征
特征 计算公式 用途
面积 A r e a = ∮ C x d y Area = \oint_C x dy Area=Cxdy 目标大小判断
周长 P e r i m e t e r = ∮ C d s Perimeter = \oint_C ds Perimeter=Cds 复杂度分析
宽高比 R = w i d t h / h e i g h t R = width/height R=width/height 形状分类
紧凑度 C = 4 π ⋅ A r e a / P e r i m e t e r 2 C = 4\pi \cdot Area / Perimeter^2 C=4πArea/Perimeter2 圆形度判断

2.4 多边形区域处理

2.4.1 点与多边形关系

采用射线法(Ray Casting Algorithm)判断点是否在多边形内:

算法原理
从点出发向任意方向发射射线,统计射线与多边形边界的交点数量:

  • 奇数个交点:点在多边形内部
  • 偶数个交点:点在多边形外部
2.4.2 多边形填充

采用扫描线算法(Scanline Algorithm)生成多边形掩码:

  1. 确定多边形的最小/最大Y坐标
  2. 对每条扫描线,计算与多边形各边的交点
  3. 排序交点,配对填充

2.5 目标跟踪

2.5.1 最近邻关联

采用最近邻算法(Nearest Neighbor Association)进行跨帧目标关联:

t ^ = arg ⁡ min ⁡ t ∈ T ∥ p t − p o ∥ 2 \hat{t} = \arg\min_{t \in T} \|p_t - p_o\|_2 t^=argtTminptpo2

其中:

  • p o p_o po 为当前检测目标的位置
  • p t p_t pt 为已有跟踪器的位置
  • ∥ ⋅ ∥ 2 \|\cdot\|_2 2 为欧氏距离
2.5.2 跟踪器生命周期管理
  • 创建:当检测到新目标且无关联跟踪器时
  • 更新:成功关联后更新位置和持续时间
  • 过期:超过设定时间未更新则删除

2.6 场景特征提取

2.6.1 亮度特征

L m e a n = 1 M N ∑ x = 1 M ∑ y = 1 N I ( x , y ) L_{mean} = \frac{1}{MN}\sum_{x=1}^{M}\sum_{y=1}^{N} I(x,y) Lmean=MN1x=1My=1NI(x,y)

L s t d = 1 M N ∑ x = 1 M ∑ y = 1 N ( I ( x , y ) − L m e a n ) 2 L_{std} = \sqrt{\frac{1}{MN}\sum_{x=1}^{M}\sum_{y=1}^{N} (I(x,y)-L_{mean})^2} Lstd=MN1x=1My=1N(I(x,y)Lmean)2

2.6.2 纹理特征

拉普拉斯能量
E l a p = 1 M N ∑ x = 1 M ∑ y = 1 N ∣ ∇ 2 I ( x , y ) ∣ E_{lap} = \frac{1}{MN}\sum_{x=1}^{M}\sum_{y=1}^{N} |\nabla^2 I(x,y)| Elap=MN1x=1My=1N2I(x,y)

边缘密度
D e d g e = ∑ ( x , y ) ∈ E d g e 1 M × N D_{edge} = \frac{\sum_{(x,y) \in Edge} 1}{M \times N} Dedge=M×N(x,y)Edge1

2.6.3 暗通道先验(雾霾检测)

暗通道先验理论指出:在无雾图像中,至少有一个颜色通道的局部最小值趋近于0。

J d a r k ( x ) = min ⁡ y ∈ Ω ( x ) ( min ⁡ c ∈ { r , g , b } J c ( y ) ) → 0 J^{dark}(x) = \min_{y \in \Omega(x)} \left( \min_{c \in \{r,g,b\}} J^c(y) \right) \rightarrow 0 Jdark(x)=yΩ(x)min(c{r,g,b}minJc(y))0

雾霾密度估计:
A = max ⁡ x ( ∑ c I c ( x ) ) A = \max_{x} \left( \sum_{c} I^c(x) \right) A=xmax(cIc(x))

t ( x ) = 1 − ω ⋅ min ⁡ c ( min ⁡ y ∈ Ω ( x ) I c ( y ) A c ) t(x) = 1 - \omega \cdot \min_{c} \left( \min_{y \in \Omega(x)} \frac{I^c(y)}{A^c} \right) t(x)=1ωcmin(yΩ(x)minAcIc(y))

2.7 图像质量评估

2.7.1 噪声估计

使用高斯滤波估计噪声:
σ n o i s e = std ( I − G ∗ I ) \sigma_{noise} = \text{std}(I - G * I) σnoise=std(IGI)

其中 G G G 为高斯核。

2.7.2 模糊检测

基于高频分量能量的模糊检测:
E h i g h = 1 M N ∑ x , y ∣ H ∗ I ( x , y ) ∣ E_{high} = \frac{1}{MN}\sum_{x,y} |H * I(x,y)| Ehigh=MN1x,yHI(x,y)

其中 H H H 为高通滤波器(拉普拉斯算子)。


3. 系统架构图

3.1 Architecture Diagram

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                           Intrusion Detection System Architecture                       │
├─────────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                         │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐    │
│  │                                  Input Layer                                    │    │
│  │  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐       │    │
│  │  │ Video File  │    │  Camera     │    │ Config File │    │Region Config│       │    │
│  │  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘    └──────┬──────┘       │    │
│  └─────────┼──────────────────┼──────────────────┼──────────────────┼──────────────┘    │
│            │                  │                  │                  │                   │
│            └──────────────────┴──────────────────┴──────────────────┘                   │
│                                            │                                            │
│                                            ▼                                            │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐    │
│  │                              Processing Layer                                   │    │
│  │                                                                                 │    │
│  │  ┌─────────────────────────────────────────────────────────────────────────┐    │    │
│  │  │                        Scene Recognition Module                         │    │    │
│  │  │  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐                │    │    │
│  │  │  │ Feature       │  │ Scene         │  │ Parameter     │                │    │    │
│  │  │  │ Extractor     │→ │ Classifier    │→ │ Adjuster      │                │    │    │
│  │  │  └───────────────┘  └───────────────┘  └───────────────┘                │    │    │
│  │  └─────────────────────────────────────────────────────────────────────────┘    │    │
│  │                                    │                                            │    │
│  │                                    ▼                                            │    │
│  │  ┌─────────────────────────────────────────────────────────────────────────┐    │    │
│  │  │                          Region Manager Module                          │    │    │
│  │  │  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐                │    │    │
│  │  │  │ Region Load   │  │ Mask          │  │ Event Filter  │                │    │    │
│  │  │  │ / Save        │  │ Generator     │  │               │                │    │    │
│  │  │  └───────────────┘  └───────────────┘  └───────────────┘                │    │    │
│  │  └─────────────────────────────────────────────────────────────────────────┘    │    │
│  │                                    │                                            │    │
│  │                                    ▼                                            │    │
│  │  ┌─────────────────────────────────────────────────────────────────────────┐    │    │
│  │  │                          Detection Module                               │    │    │
│  │  │  ┌───────────────┐  ┌───────────────┐  ┌───────────────┐                │    │    │
│  │  │  │ MOG2          │  │ Frame         │  │ Adaptive      │                │    │    │
│  │  │  │ Detector      │  │ Difference    │  │ Background    │                │    │    │
│  │  │  │               │  │ Detector      │  │ Detector      │                │    │    │
│  │  │  └───────┬───────┘  └───────┬───────┘  └───────┬───────┘                │    │    │
│  │  │          │                  │                  │                        │    │    │
│  │  │          └──────────────────┼──────────────────┘                        │    │    │
│  │  │                             │                                           │    │    │
│  │  │                    ┌────────┴────────┐                                  │    │    │
│  │  │                    │ Mask Fusion     │                                  │    │    │
│  │  │                    │ (Weighted Sum)  │                                  │    │    │
│  │  │                    └────────┬────────┘                                  │    │    │
│  │  │                             │                                           │    │    │
│  │  │                    ┌────────┴────────┐                                  │    │    │
│  │  │                    │ Morphological   │                                  │    │    │
│  │  │                    │ Processing      │                                  │    │    │
│  │  │                    └────────┬────────┘                                  │    │    │
│  │  │                             │                                           │    │    │
│  │  │                    ┌────────┴────────┐                                  │    │    │
│  │  │                    │ Contour Analysis│                                  │    │    │
│  │  │                    └────────┬────────┘                                  │    │    │
│  │  │                             │                                           │    │    │
│  │  │                    ┌────────┴────────┐                                  │    │    │
│  │  │                    │ Event Merge     │                                  │    │    │
│  │  │                    │ & Tracking      │                                  │    │    │
│  │  │                    └────────┬────────┘                                  │    │    │
│  │  └─────────────────────────────┼───────────────────────────────────────────┘    │    │
│  └────────────────────────────────┼────────────────────────────────────────────────┘    │
│                                   │                                                     │
│                                   ▼                                                     │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐    │
│  │                               Output Layer                                      │    │
│  │  ┌──────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐      │    │
│  │  │ Visualization│    │   Alarm     │    │ Video Save  │    │   Log       │      │    │
│  │  └──────────────┘    └─────────────┘    └─────────────┘    └─────────────┘      │    │
│  └─────────────────────────────────────────────────────────────────────────────────┘    │
│                                                                                         │
└─────────────────────────────────────────────────────────────────────────────────────────┘

3.2 中英文对照 - Architecture

英文 中文
Input Layer 输入层
Processing Layer 处理层
Output Layer 输出层
Scene Recognition Module 场景识别模块
Region Manager Module 区域管理模块
Detection Module 检测模块
Feature Extractor 特征提取器
Scene Classifier 场景分类器
Parameter Adjuster 参数调整器
Mask Fusion 掩码融合
Morphological Processing 形态学处理
Contour Analysis 轮廓分析
Event Merge & Tracking 事件合并与跟踪
Visualization 可视化
Alarm 报警

4. 流程图

4.1 Main Flowchart

                    ┌─────────────────┐
                    │      START      │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │  Parse CLI Args │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │  Load Config    │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │  Load Regions   │
                    └────────┬────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │      Select Input Source     │
              └──────────────┬───────────────┘
                             │
        ┌────────────────────┼────────────────────┐
        │                    │                    │
        ▼                    ▼                    ▼
┌───────────────┐    ┌───────────────┐    ┌───────────────┐
│  Camera Mode  │    │  Video Mode   │    │ Region Mode   │
└───────┬───────┘    └───────┬───────┘    └───────┬───────┘
        │                    │                    │
        └────────────────────┼────────────────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │  Frame Loop     │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Preprocess      │
                    │ (Gray + Blur)   │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │Scene Analysis?  │
                    └────────┬────────┘
                             │
              ┌──────────────┼──────────────┐
              │ Yes          │ No           │
              ▼              │              │
     ┌───────────────┐       │              │
     │ Extract       │       │              │
     │ Features      │       │              │
     └───────┬───────┘       │              │
             │               │              │
             ▼               │              │
     ┌───────────────┐       │              │
     │ Classify      │       │              │
     │ Scene         │       │              │
     └───────┬───────┘       │              │
             │               │              │
             ▼               │              │
     ┌───────────────┐       │              │
     │ Adjust        │       │              │
     │ Parameters    │       │              │
     └───────┬───────┘       │              │
             │               │              │
             └───────────────┼──────────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ 3 Detectors     │
                    │ Parallel        │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Mask Fusion     │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Morphological   │
                    │ Processing      │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Contour         │
                    │ Analysis        │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Event Merge     │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Region Filter   │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Tracker Update  │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ Visualization   │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │   Alarm Check   │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │    END?         │
                    └────────┬────────┘
                             │
              ┌──────────────┼──────────────┐
              │ No           │ Yes          │
              ▼              │              ▼
              └──────────────┘     ┌───────────────┐
                                   │     STOP      │
                                   └───────────────┘

4.2 中英文对照 - Flowchart

英文 中文
START 开始
STOP 结束
Parse CLI Args 解析命令行参数
Load Config 加载配置
Load Regions 加载区域
Select Input Source 选择输入源
Camera Mode 摄像头模式
Video Mode 视频模式
Region Mode 区域模式
Frame Loop 帧循环
Preprocess (Gray + Blur) 预处理(灰度+模糊)
Scene Analysis 场景分析
Extract Features 提取特征
Classify Scene 分类场景
Adjust Parameters 调整参数
3 Detectors Parallel 三个检测器并行
Mask Fusion 掩码融合
Morphological Processing 形态学处理
Contour Analysis 轮廓分析
Event Merge 事件合并
Region Filter 区域过滤
Tracker Update 跟踪器更新
Visualization 可视化
Alarm Check 报警检查

4.3 Single Frame Detection Flowchart

                    ┌─────────────────────────────────────────────────────────────────┐
                    │                         Input Frame                             │
                    └─────────────────────────────────────┬───────────────────────────┘
                                                          │
                                                          ▼
                    ┌─────────────────────────────────────────────────────────────────┐
                    │                         Preprocess                              │
                    │  ┌─────────────────┐        ┌─────────────────┐                 │
                    │  │ BGR → Gray      │───────→│ Gaussian Blur   │                 │
                    │  └─────────────────┘        └─────────────────┘                 │
                    └─────────────────────────────────────┬───────────────────────────┘
                                                          │
                          ┌───────────────────────────────┼───────────────────────────────┐
                          │                               │                               │
                          ▼                               ▼                               ▼
          ┌───────────────────────────┐   ┌───────────────────────────┐   ┌───────────────────────────┐
          │      MOG2 Detector        │   │  Frame Difference Detector│   │  Adaptive Background      │
          │                           │   │                           │   │        Detector           │
          │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │
          │  │ Background Model    │  │   │  │ Previous Frame      │  │   │  │ Background Model    │  │
          │  │ Update              │  │   │  │ Store               │  │   │  │ Update (EWMA)       │  │
          │  └──────────┬──────────┘  │   │  └──────────┬──────────┘  │   │  └──────────┬──────────┘  │
          │             │             │   │             │             │   │             │             │
          │             ▼             │   │             ▼             │   │             ▼             │
          │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │
          │  │ Foreground Extract  │  │   │  │ Frame Difference    │  │   │  │ Background Diff     │  │
          │  └──────────┬──────────┘  │   │  │ Calculation         │  │   │  │ Calculation         │  │
          │             │             │   │  └──────────┬──────────┘  │   │  └──────────┬──────────┘  │
          │             ▼             │   │             ▼             │   │             ▼             │
          │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │   │  ┌─────────────────────┐  │
          │  │ Shadow Removal      │  │   │  │ Thresholding        │  │   │  │ Adaptive Threshold  │  │
          │  └──────────┬──────────┘  │   │  └──────────┬──────────┘  │   │  └──────────┬──────────┘  │
          └─────────────┼─────────────┘   └─────────────┼─────────────┘   └─────────────┼─────────────┘
                        │                               │                               │
                        └───────────────────────────────┼───────────────────────────────┘
                                                        │
                                                        ▼
                                      ┌─────────────────────────────────┐
                                      │          Mask Fusion            │
                                      │  fgmask = 0.5*fg1 + 0.3*fg2     │
                                      │          + 0.3*fg3              │
                                      └────────────────┬────────────────┘
                                                       │
                                                       ▼
                                      ┌─────────────────────────────────┐
                                      │      Morphological Closing      │
                                      │  Kernel: 5x5 Ellipse            │
                                      │  Iterations: 2                  │
                                      └────────────────┬────────────────┘
                                                       │
                                                       ▼
                                      ┌─────────────────────────────────┐
                                      │        Region Mask Apply        │
                                      │  fgmask = fgmask & active_mask  │
                                      └────────────────┬────────────────┘
                                                       │
                                                       ▼
                                      ┌─────────────────────────────────┐
                                      │         Contour Analysis        │
                                      │  ┌───────────────────────────┐  │
                                      │  │ findContours()            │  │
                                      │  └─────────────┬─────────────┘  │
                                      │                ▼                │
                                      │  ┌───────────────────────────┐  │
                                      │  │ For each contour:         │  │
                                      │  │  - Area filter            │  │
                                      │  │  - Aspect ratio filter    │  │
                                      │  │  - Circularity filter     │  │
                                      │  │  - Confidence calculation │  │
                                      │  └─────────────┬─────────────┘  │
                                      └────────────────┬────────────────┘
                                                       │
                                                       ▼
                                      ┌─────────────────────────────────┐
                                      │          Event Processing       │
                                      │  ┌───────────────────────────┐  │
                                      │  │ Merge by Position         │  │
                                      │  └─────────────┬─────────────┘  │
                                      │                ▼                │
                                      │  ┌───────────────────────────┐  │
                                      │  │ Region Filter             │  │
                                      │  └─────────────┬─────────────┘  │
                                      │                ▼                │
                                      │  ┌───────────────────────────┐  │
                                      │  │ Tracker Update            │  │
                                      │  │ - Association             │  │
                                      │  │ - Duration calculation    │  │
                                      │  └─────────────┬─────────────┘  │
                                      └────────────────┬────────────────┘
                                                       │
                                                       ▼
                                      ┌─────────────────────────────────┐
                                      │           Output Events         │
                                      └─────────────────────────────────┘

5. 时序图

5.1 System Initialization Sequence

┌────────┐  ┌──────────────┐  ┌─────────────┐  ┌────────────┐  ┌─────────────┐  ┌─────────────┐
│  Main  │  │  Detection   │  │   Region    │  │   Hybrid   │  │  MOG2/      │  │  Intrusion  │
│        │  │   System     │  │   Manager   │  │  Detector  │  │  Frame/Adapt│  │   Alarm     │
└───┬────┘  └──────┬───────┘  └───────┬─────┘  └───────┬────┘  └───────┬─────┘  └───────┬─────┘
    │              │                  │                │               │                │
    │ new(config)  │                  │                │               │                │
    │─────────────>│                  │                │               │                │
    │              │                  │                │               │                │
    │              │ new()            │                │               │                │
    │              │─────────────────>│                │               │                │
    │              │                  │                │               │                │
    │              │                  │ new(config, manager)           │                │
    │              │                  │───────────────>│               │                │
    │              │                  │                │               │                │
    │              │                  │                │ new(config, manager)           │
    │              │                  │                │──────────────>│                │
    │              │                  │                │               │                │
    │              │                  │                │               │ new()          │
    │              │                  │                │               │───────────────>│
    │              │                  │                │               │                │
    │ load_regions(cfg)               │                │               │                │
    │─────────────>│                  │                │               │                │
    │              │ load_regions()   │                │               │                │
    │              │─────────────────>│                │               │                │
    │              │                  │                │               │                │
    │              │                  │ read JSON ─────────────────────────────────────>│
    │              │                  │                │               │                │
    │              │                  │ parse regions  │               │                │
    │              │                  │                │               │                │
    │              │ update_masks(size)                │               │                │
    │              │─────────────────>│                │               │                │
    │              │                  │                │               │                │
    │              │                  │ for each region:               |                │
    │              │                  │   get_mask()   │               │                │
    │              │                  │                │               │                │
    │              │<─────────────────│ (ready)        │               │                │
    │<─────────────│                  │                │               │                │
    │              │                  │                │               │                │

5.2 Frame Processing Sequence

┌────────┐  ┌──────────────┐  ┌─────────────┐  ┌────────────┐  ┌─────────────┐  ┌─────────────┐
│  Main  │  │  Detection   │  │   Region    │  │   Hybrid   │  │   MOG2/     │  │  Tracker/   │
│        │  │   System     │  │   Manager   │  │  Detector  │  │  Frame/Adapt│  │   Alarm     │
└───┬────┘  └──────┬───────┘  └───────┬─────┘  └───────┬────┘  └───────┬─────┘  └───────┬─────┘
    │              │                  │                │               │                │
    │ process_frame(frame)            │                │               │                │
    │─────────────>│                  │                │               │                │
    │              │                  │                │               │                │
    │              │ update_masks()   │                │               │                │
    │              │─────────────────>│                │               │                │
    │              │                  │                │               │                │
    │              │ detect(frame)    │                │               │                │
    │              │─────────────────────────────────> │               │                │
    │              │                  │                │               │                │
    │              │                  │                │ detect_mog2() │                │
    │              │                  │                │──────────────>│                │
    │              │                  │                │<──────────────│ (fgmask1,evt1) │
    │              │                  │                │               │                │
    │              │                  │                │ detect_diff() │                │
    │              │                  │                │──────────────>│                │
    │              │                  │                │<──────────────│ (fgmask2,evt2) │
    │              │                  │                │               │                │
    │              │                  │                │ detect_adapt()│                │
    │              │                  │                │──────────────>│                │
    │              │                  │                │<──────────────│ (fgmask3,evt3) │
    │              │                  │                │               │                │
    │              │                  │                │               │                │
    │              │                  │                │ Mask Fusion   │                │
    │              │                  │                │ Morphological │                │
    │              │                  │                │ Processing    │                │
    │              │                  │                │               │                │
    │              │                  │ get_active_mask()              │                │
    │              │                  │<───────────────│               │                │
    │              │                  │───────────────>│ (active_mask) │                │
    │              │                  │                │               │                │
    │              │                  │                │ apply_region_mask()            │
    │              │                  │                │               │                │
    │              │                  │                │ analyze_contours()             │
    │              │                  │                │               │                │
    │              │                  │                │ merge_events_by_position()     │
    │              │                  │                │               │                │
    │              │                  │ filter_events_by_region(events)│                │
    │              │                  │<───────────────│               │                │
    │              │                  │───────────────>│ (filtered)    │                │
    │              │                  │                │               │                │
    │              │                  │                │ update_trackers(events)        │
    │              │                  │                │───────────────────────────────>│
    │              │                  │                │<───────────────────────────────│
    │              │                  │                │               │                │
    │              │<───────────────────────────────── │ (events)      │                │
    │              │                  │                │               │                │
    │              │ check_and_alert(events)           │               │                │
    │              │──────────────────────────────────────────────────────────────────> │
    │              │<────────────────────────────────────────────────────────────────── │
    │              │                  │                │               │                │
    │  draw_intrusion(frame, events, fgmask)           │               │                │
    │<─────────────│                  │                │               │                │
    │              │                  │                │               │                │

5.3 中英文对照 - Sequence Diagram

英文 中文
Main 主程序
Detection System 检测系统
Region Manager 区域管理器
Hybrid Detector 混合检测器
MOG2/Frame/Adapt MOG2/帧差法/自适应检测器
Tracker/Alarm 跟踪器/报警器
new(config) 创建实例(配置)
load_regions() 加载区域
read JSON 读取JSON文件
parse regions 解析区域
update_masks() 更新掩码
for each region 遍历每个区域
get_mask() 获取掩码
process_frame() 处理帧
detect() 检测
detect_mog2() MOG2检测
detect_diff() 帧差法检测
detect_adapt() 自适应检测
Mask Fusion 掩码融合
Morphological Processing 形态学处理
get_active_mask() 获取活动掩码
apply_region_mask() 应用区域掩码
analyze_contours() 分析轮廓
merge_events_by_position() 按位置合并事件
filter_events_by_region() 按区域过滤事件
update_trackers() 更新跟踪器
check_and_alert() 检查并报警
draw_intrusion() 绘制入侵

6. 类图

6.1 Class Diagram

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                                        Class Diagram                                    │
└─────────────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────┐        ┌─────────────────────────────┐
│       IntrusionEvent        │        │      IntrusionRegion        │
├─────────────────────────────┤        ├─────────────────────────────┤
│ - timestamp: float          │        │ - id: int                   │
│ - bbox: Tuple               │        │ - name: str                 │
│ - area: int                 │        │ - points: List              │
│ - centroid: Tuple           │        │ - enabled: bool             │
│ - duration: float           │        │ - sensitivity: float        │
│ - confidence: float         │        │ - min_area: int             │
│ - region_id: int            │        │ - max_area: int             │
└─────────────────────────────┘        ├─────────────────────────────┤
                                       │ + get_mask()                │
┌─────────────────────────────┐        │ + contains_point()          │
│      DetectionConfig        │        │ + contains_bbox()           │
├─────────────────────────────┤        └─────────────────────────────┘
│ - min_area: int             │                    ▲
│ - max_area: int             │                    │
│ - min_duration: float       │                    │ contains
│ - history: int              │        ┌───────────┴─────────────┐
│ - var_threshold: int        │        │  IntrusionRegionManager │
│ - detect_shadows: bool      │        ├─────────────────────────┤
│ - morph_kernel_size: int    │        │ - regions: List         │
│ - morph_iterations: int     │        │ - region_masks: Dict    │
│ - frame_diff_threshold: int │        │ - frame_size: Tuple     │
├─────────────────────────────┤        ├─────────────────────────┤
│ + load_config()             │        │ + add_region()          │
└─────────────────────────────┘        │ + remove_region()       │
                                       │ + update_masks()        │
                                       │ + get_active_mask()     │
                                       │ + filter_events_by_region()
                                       │ + draw_regions()        │
                                       │ + save/load_regions()   │
                                       └─────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                              Detector Hierarchy                                         │
└─────────────────────────────────────────────────────────────────────────────────────────┘

                              ┌─────────────────────────────┐
                              │     IntrusionDetector       │
                              │         (Abstract)          │
                              ├─────────────────────────────┤
                              │ # config: DetectionConfig   │
                              │ # region_manager: RegionMgr │
                              │ # prev_gray: ndarray        │
                              │ # background: ndarray       │
                              │ # verbose: int              │
                              ├─────────────────────────────┤
                              │ # preprocess()              │
                              │ # morphological_processing()│
                              │ # apply_region_mask()       │
                              │ # get_area_thresholds()     │
                              │ # analyze_contours()        │
                              │ + detect() (abstract)       │
                              └──────────────┬──────────────┘
                                             │
              ┌──────────────────────────────┼──────────────────────────────┐
              │                              │                              │
              ▼                              ▼                              ▼
┌─────────────────────────────┐  ┌─────────────────────────┐  ┌───────────────────────────┐
│      MOG2Detector           │  │ FrameDifferenceDetector │  │ AdaptiveBackgroundDetector│
├─────────────────────────────┤  ├─────────────────────────┤  ├───────────────────────────┤
│ - fgbg: BackgroundSubtractor│  │ (BaseClass)             │  │ - learning_rate: float    │
├─────────────────────────────┤  ├─────────────────────────┤  ├───────────────────────────┤
│ + create_fgbg()             │  │ + detect()              │  │ + detect()                │
│ + detect()                  │  └─────────────────────────┘  └───────────────────────────┘
└─────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                           Scene Recognition Classes                                     │
└─────────────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────┐  ┌─────────────────────────┐  ┌──────────────────────────┐
│   SceneFeatureExtractor │  │     SceneClassifier     │  │ AdaptiveParameterAdjuster│
├─────────────────────────┤  ├─────────────────────────┤  ├──────────────────────────┤
│ - frame_history: deque  │  │ - feature_history: deque│  │ - base_config            │
│ - previous_frame        │  │ - classification_history│  │ - current_scene          │
├─────────────────────────┤  ├─────────────────────────┤  │ - adjustments: Dict      │
│ + extract_all_features()│  │ + classify_lighting()   │  ├──────────────────────────┤
│ + extract_brightness()  │  │ + classify_weather()    │  │ + adjust()               │
│ + extract_contrast()    │  │ + classify_quality()    │  │ + _adjust_for_xxx()      │
│ + extract_texture()     │  │ + classify_motion()     │  └──────────────────────────┘
│ + extract_color()       │  │ + classify_scene()      │
│ + extract_noise()       │  │ + get_scene_summary()   │
│ + extract_motion()      │  └─────────────────────────┘
└─────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                           Helper Classes                                                │
└─────────────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────┐  ┌─────────────────────────┐  ┌───────────────────────────┐
│   IntrusionVisualizer   │  │     IntrusionAlarm      │  │      RegionDrawer         │
├─────────────────────────┤  ├─────────────────────────┤  ├───────────────────────────┤
│ - region_manager        │  │ - alarm_history: deque  │  │ - window_name             │
│ - colors: List          │  │ - alarm_cooldown: float │  │ - points: List            │
├─────────────────────────┤  │ - last_alarm_time: float│  │ - drawing: bool           │
│ + draw_intrusion()      │  ├─────────────────────────┤  ├───────────────────────────┤
│ + draw_statistics()     │  │ + check_and_alert()     │  │ + draw_regions_interactive│
└─────────────────────────┘  │ + get_alarm_summary()   │  └───────────────────────────┘
                             └─────────────────────────┘

┌─────────────────────────┐  ┌─────────────────────────────────────────────────────────┐
│       DebugUtils        │  │          IntelligentSceneRecognition                    │
├─────────────────────────┤  ├─────────────────────────────────────────────────────────┤
│ + save_debug_image()    │  │ - feature_extractor                                     │
│ + get_debug_filename()  │  │ - classifier                                            │
│ + format_event()        │  │ - parameter_adjuster                                    │
└─────────────────────────┘  │ - current_scene                                         │
                             │ - adaptation_enabled                                    │
                             ├─────────────────────────────────────────────────────────┤
                             │ + analyze_frame()                                       │
                             │ + enable_adaptation()                                   │
                             │ + print_analysis()                                      │
                             └─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                            Main System Class                                            │
└─────────────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                         IntrusionDetectionSystem                                        │
├─────────────────────────────────────────────────────────────────────────────────────────┤
│ - config: DetectionConfig                                                               │
│ - region_manager: IntrusionRegionManager                                                │
│ - detector: HybridIntrusionDetector                                                     │
│ - visualizer: IntrusionVisualizer                                                       │
│ - alarm: IntrusionAlarm                                                                 │
│ - scene_recognizer: IntelligentSceneRecognition                                         │
│ - fps: float                                                                            │
│ - verbose: int                                                                          │
├─────────────────────────────────────────────────────────────────────────────────────────┤
│ + set_verbose()                                                                         │
│ + set_config()                                                                          │
│ + load_regions()                                                                        │
│ + save_regions()                                                                        │
│ + create_regions_only()                                                                 │
│ + process_frame()                                                                       │
│ + run_on_video()                                                                        │
│ + run_on_camera()                                                                       │
└─────────────────────────────────────────────────────────────────────────────────────────┘

6.2 中英文对照 - Class Diagram

英文 中文
IntrusionEvent 入侵事件
IntrusionRegion 入侵区域
DetectionConfig 检测配置
IntrusionRegionManager 入侵区域管理器
IntrusionDetector (Abstract) 入侵检测器(抽象基类)
MOG2Detector MOG2检测器
FrameDifferenceDetector 帧差法检测器
AdaptiveBackgroundDetector 自适应背景检测器
SceneFeatureExtractor 场景特征提取器
SceneClassifier 场景分类器
AdaptiveParameterAdjuster 自适应参数调整器
IntrusionVisualizer 入侵可视化器
IntrusionAlarm 入侵报警器
RegionDrawer 区域绘制工具
DebugUtils 调试工具类
IntelligentSceneRecognition 智能场景识别
IntrusionDetectionSystem 入侵检测系统

7. 模块功能详解

7.1 DetectionConfig - 配置模块

方法 功能描述
load_config() 从JSON文件加载配置参数

7.2 IntrusionRegionManager - 区域管理模块

方法 功能描述
add_region() 添加一个入侵区域
remove_region() 根据ID移除区域
remove_last_region() 删除最后添加的区域
clear_regions() 清空所有区域
update_masks() 更新当前帧尺寸下的区域掩码
get_active_mask() 获取所有启用区域的合并掩码
filter_events_by_region() 根据区域过滤事件(互斥设计)
get_region_for_point() 获取点所在的区域
draw_regions() 在图像上绘制所有区域
save_regions() 保存区域配置到JSON文件
load_regions() 从JSON文件加载区域配置

7.3 SceneFeatureExtractor - 特征提取模块

方法 功能描述
extract_brightness_features() 提取亮度特征(均值、标准差、直方图)
extract_contrast_features() 提取对比度和动态范围
extract_texture_features() 提取纹理能量、边缘密度、梯度幅值
extract_color_features() 提取颜色方差、平均饱和度、主色调
extract_noise_features() 提取噪声水平和类型
extract_haze_features() 使用暗通道先验提取雾霾密度
extract_rain_features() 提取雨线密度
extract_motion_features() 提取运动能量和背景运动程度
extract_all_features() 提取所有场景特征

7.4 SceneClassifier - 场景分类模块

方法 功能描述
classify_lighting() 光照条件分类(白天/夜晚/黄昏)
classify_weather() 天气条件分类(雨/雾/雪)
classify_quality() 图像质量分类(模糊/噪点/低照度)
classify_motion_interference() 运动干扰分类(风吹树摇)
classify_scene() 综合场景分类
get_scene_summary() 获取场景分类摘要

7.5 IntrusionDetector (抽象基类) - 检测器基类

方法 功能描述
preprocess() 图像预处理(灰度化+高斯滤波)
morphological_processing() 形态学处理(开运算+闭运算)
apply_region_mask() 应用区域掩码过滤前景
get_area_thresholds() 根据位置获取面积阈值
analyze_contours() 轮廓分析提取入侵目标

7.6 MOG2Detector - MOG2背景减除检测器

方法 功能描述
create_fgbg() 创建MOG2背景建模器
detect() 执行MOG2检测,返回前景掩码

7.7 FrameDifferenceDetector - 帧差法检测器

方法 功能描述
detect() 执行帧差法检测

7.8 AdaptiveBackgroundDetector - 自适应背景检测器

方法 功能描述
detect() 执行自适应背景检测(EWMA)

7.9 HybridIntrusionDetector - 混合检测器

方法 功能描述
detect() 融合三种检测器,合并事件,更新跟踪器
merge_events_by_position() 基于位置距离合并事件
merge_bounding_boxes() 合并边界框为最小包围框
update_trackers() 更新目标跟踪器,跨帧关联

7.10 IntrusionVisualizer - 可视化模块

方法 功能描述
draw_intrusion() 绘制检测结果(区域、掩码、边框、标签)
draw_statistics() 绘制统计信息(数量、面积、区域分布)

7.11 IntrusionAlarm - 报警模块

方法 功能描述
check_and_alert() 检查并触发报警(带冷却机制)
get_alarm_summary() 获取报警摘要

7.12 RegionDrawer - 交互式绘制工具

方法 功能描述
draw_regions_interactive() 交互式多边形区域绘制

7.13 DebugUtils - 调试工具类

方法 功能描述
save_debug_image() 保存调试图像到文件
get_debug_filename() 生成调试文件名
format_event() 格式化事件用于调试输出

8. 命令行调用范例

8.1 基本用法

# 显示帮助信息
python intrusion_detection.py --help

# 检测视频文件(默认配置)
python intrusion_detection.py --action detect --source /path/to/video.mp4

# 检测摄像头
python intrusion_detection.py --action detect --source 0

# 仅绘制区域
python intrusion_detection.py --action regions --source /path/to/video.mp4 --regions /tmp/regions.json

# 创建测试视频
python intrusion_detection.py --action create_video --source /tmp/test.mp4

8.2 调试级别设置

# 静默模式 - 不输出调试信息
python intrusion_detection.py --verbose 0 --action detect --source video.mp4

# 低频信息 - 仅输出检测结果
python intrusion_detection.py --verbose 1 --action detect --source video.mp4

# 高频信息 - 详细步骤输出
python intrusion_detection.py --verbose 2 --action detect --source video.mp4

# 完整调试 - 保存所有中间图像
python intrusion_detection.py --verbose 3 --action detect --source video.mp4

8.3 配置文件示例

# 场景识别测试
python intrusion_detection.py --action scene_test --source demo.jpg

# 使用智能场景识别
python intrusion_detection.py --config smart --action detect --source video.mp4

# 使用自定义配置文件
python intrusion_detection.py --config /path/to/config.json --action detect --source video.mp4

# 自定义场景分析间隔(毫秒)
python intrusion_detection.py --config smart --scene_interval 5000 --action detect --source video.mp4

# 自定义区域配置文件
python intrusion_detection.py --regions /path/to/regions.json --action detect --source video.mp4

8.4 算法配置文件JSON示例

{
    "min_area": 800,
    "min_duration": 0.5,
    "history": 500,
    "var_threshold": 20,
    "detect_shadows": true,
    "morph_kernel_size": 5,
    "morph_iterations": 2,
    "frame_diff_threshold": 25,
    "out_dir": "/tmp/intrusion",
    "is_debug": false
}

8.5 区域配置文件JSON示例

[
    {
        "id": 1,
        "name": "Gate_Area",
        "points": [[150, 150], [350, 150], [350, 350], [150, 350]],
        "enabled": true,
        "sensitivity": 1.2,
        "min_area": 800,
        "max_area": 30000
    },
    {
        "id": 2,
        "name": "Right_Corner",
        "points": [[480, 200], [620, 200], [620, 450], [480, 450]],
        "enabled": true,
        "sensitivity": 1.0,
        "min_area": 500,
        "max_area": 10000
    }
]

9. 调参策略

9.1 参数调优指南

参数 说明 调优方向
min_area 最小入侵面积(像素) 降低=更敏感,提高=减少误报
min_duration 最小持续时间(秒) 降低=响应更快,提高=更稳定
var_threshold MOG2方差阈值 降低=更敏感,提高=减少阴影噪声
detect_shadows 阴影检测 True=白天更好,False=夜晚更好
morph_kernel_size 形态学核大小 增大=去噪更强,减小=保留细节
morph_iterations 形态学迭代次数 增多=滤波更强,减少=保留细节
frame_diff_threshold 帧差阈值 降低=检测慢速运动,提高=减少噪声
history 背景历史帧数 增大=背景稳定,减小=快速适应
sensitivity 区域敏感度 >1=更敏感,<1=更不敏感

9.2 优化工作流程

1. 使用默认参数开始
         │
         ▼
2. 使用测试视频验证
         │
         ▼
3. 识别问题:
   ┌─────────────────┬─────────────────┐
   │ 误报过多         │ 漏报过多          │
   └────────┬────────┴────────┬────────┘
            │                 │
            ▼                 ▼
   调整以下参数:        调整以下参数:
   - 提高 min_area      - 降低 min_area
   - 提高 min_duration  - 降低 min_duration
   - 提高 var_threshold - 降低 var_threshold
   - 增大形态学核        - 减小形态学核
            │                 │
            └────────┬────────┘
                     │
                     ▼
4. 针对特定场景微调
         │
         ▼
5. 用多个测试视频验证

10. 应用场景参数配置速查表

10.1 场景参数快速参考

场景 min_area var_threshold morph_kernel frame_diff detect_shadows min_duration history
白天 800 20 3 25 True 0.5 500
夜晚 400 8 7 20 False 0.8 300
大目标 2000 12 5 15 True 0.3 500
小目标 200 10 3 20 False 0.4 300
雪花噪点 800 25 9 35 False 0.6 200
清晰度不足 600 10 3 18 False 0.5 400
雨天 1000 18 7 30 False 0.8 300
风吹树摇 800 22 5 28 True 0.8 800
室内 500 14 5 25 True 0.5 600
室外 600 18 5 28 True 0.6 500
高空俯视 300 12 3 20 False 0.4 400

10.2 场景说明

场景 英文 说明
白天 Daytime 光照充足,背景清晰
夜晚 Nighttime 光照不足,噪声增加
大目标 Large Target 车辆、大型动物
小目标 Small Target 行人、小动物
雪花噪点 Snow Noise 信号干扰、低照度噪声
清晰度不足 Blurry 雾、雨、镜头脏污
雨天 Rainy 雨线干扰
风吹树摇 Windy 树木晃动造成的背景运动
室内 Indoor 光照稳定
室外 Outdoor 光照变化大
高空俯视 High Angle 目标尺寸小

10.3 支持场景枚举

场景(枚举) 场景(中文)
DAYTIME = “daytime” 白天
NIGHTTIME = “nighttime” 夜晚
DUSK = “dusk” 黄昏/黎明
INDOOR = “indoor” 室内
OUTDOOR = “outdoor” 室外
RAINY = “rainy” 雨天
FOGGY = “foggy” 雾天
SNOWY = “snowy” 雪天
BLURRY = “blurry” 模糊
NOISY = “noisy” 噪点多
WINDY = “windy” 风吹树摇
LOW_LIGHT = “low_light” 低照度
HIGH_CONTRAST = “high_contrast” 高对比度

11. 中英文对照表

11.1 术语表

英文 中文
Intrusion Detection 入侵检测
Background Subtraction 背景减除
Frame Difference 帧差法
Adaptive Background 自适应背景
Morphological Processing 形态学处理
Contour Analysis 轮廓分析
Event Merge 事件合并
Target Tracking 目标跟踪
Region of Interest (ROI) 感兴趣区域
False Positive (FP) 误报
False Negative (FN) 漏报
Sensitivity 敏感度
Confidence 置信度
Duration 持续时间
Threshold 阈值
Kernel
Iteration 迭代次数
Foreground Mask 前景掩码
Background Model 背景模型
Shadow Detection 阴影检测
Scene Recognition 场景识别
Feature Extraction 特征提取
Brightness 亮度
Contrast 对比度
Texture 纹理
Noise Level 噪声水平
Haze Density 雾霾密度
Rain Density 雨线密度
Motion Energy 运动能量
Background Motion 背景运动
Dynamic Range 动态范围
Edge Density 边缘密度
Gradient Magnitude 梯度幅值
Color Variance 颜色方差
Saturation 饱和度
Dominant Color 主色调

11.2 模块名称表

英文 中文
IntrusionRegionManager 入侵区域管理器
SceneFeatureExtractor 场景特征提取器
SceneClassifier 场景分类器
AdaptiveParameterAdjuster 自适应参数调整器
MOG2Detector MOG2检测器
FrameDifferenceDetector 帧差法检测器
AdaptiveBackgroundDetector 自适应背景检测器
HybridIntrusionDetector 混合入侵检测器
IntrusionVisualizer 入侵可视化器
IntrusionAlarm 入侵报警器
RegionDrawer 区域绘制工具
DebugUtils 调试工具类
IntelligentSceneRecognition 智能场景识别
IntrusionDetectionSystem 入侵检测系统

11.3 方法名称表

英文 中文
add_region 添加区域
remove_region 移除区域
clear_regions 清空区域
update_masks 更新掩码
get_active_mask 获取活动掩码
filter_events_by_region 按区域过滤事件
draw_regions 绘制区域
save_regions 保存区域
load_regions 加载区域
preprocess 预处理
morphological_processing 形态学处理
apply_region_mask 应用区域掩码
analyze_contours 分析轮廓
merge_events_by_position 按位置合并事件
update_trackers 更新跟踪器
check_and_alert 检查并报警
draw_intrusion 绘制入侵
draw_statistics 绘制统计
create_regions_only 单独创建区域
process_frame 处理帧
run_on_video 运行视频
run_on_camera 运行摄像头
set_verbose 设置调试级别
load_config 加载配置

附录

A. 依赖库

pip install opencv-python numpy

B. 版本历史

版本 日期 更新内容
2.0 2026.05.08 增加场景识别和自适应参数功能
3.0 2026.05.09 补充关键技术理论

C. 输出文件说明

文件 说明
/tmp/intrusion/out.mp4 检测结果视频
/tmp/intrusion/debug/*.jpg 调试中间图像(verbose=3时)
/tmp/intrusion/config_regions.json 区域配置文件

D. 测试案例

D.1. 场景识别测试:白天

在这里插入图片描述

======================================================================
智能场景识别结果
======================================================================
识别场景: HIGH_CONTRAST
置信度: 70.00%
场景摘要: high_contrast(1)
自适应状态: 启用

调整后的检测参数:
  min_area: 500
  min_duration: 0.5
  var_threshold: 16
  detect_shadows: True
  morph_kernel_size: 5
  frame_diff_threshold: 25
D.2. 场景识别测试:夜晚

在这里插入图片描述

======================================================================
智能场景识别结果
======================================================================
识别场景: NIGHTTIME
置信度: 85.00%
场景摘要: nighttime(1)
自适应状态: 启用

调整后的检测参数:
  min_area: 350
  min_duration: 0.7
  var_threshold: 8
  detect_shadows: False
  morph_kernel_size: 7
  frame_diff_threshold: 25
D.3. 入侵检测测试:飞鸟

bird

{
    "min_area": 5,
    "max_area": 50000,
    "min_duration": 0.5,
    "confidence_threshold": 0.6,
    "history": 500,
    "var_threshold": 3,
    "detect_shadows": true,
    "morph_kernel_size": 3,
    "morph_iterations": 2,
    "frame_diff_threshold": 5
}
D.4. 入侵检测测试:行人

person

{
    "min_area": 200,
    "max_area": 50000,
    "min_duration": 0.5,
    "confidence_threshold": 0.6,
    "history": 500,
    "var_threshold": 16,
    "detect_shadows": true,
    "morph_kernel_size": 5,
    "morph_iterations": 2,
    "frame_diff_threshold": 25
}
D.5. 入侵检测测试:车辆

car

{
    "min_area": 50,
    "max_area": 50000,
    "min_duration": 0.5,
    "confidence_threshold": 0.6,
    "history": 500,
    "var_threshold": 10,
    "detect_shadows": true,
    "morph_kernel_size": 5,
    "morph_iterations": 2,
    "frame_diff_threshold": 25
}


Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐