- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
使用方框滤波器模糊图像。
该函数使用以下内核来平滑图像:
K
=
α
[
1
1
…
1
1
1
…
1
⋮
⋮
⋱
⋮
1
1
…
1
]
K = \alpha \begin{bmatrix} 1 & 1 & \dots & 1 \\ 1 & 1 & \dots & 1 \\ \vdots & \vdots & \ddots & \vdots \\ 1 & 1 & \dots & 1 \end{bmatrix}
K=α
11⋮111⋮1……⋱…11⋮1
其中
α
=
{
1
ksize.width*ksize.height
when
normalize=true
1
otherwise
\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise} \end{cases}
α={ksize.width*ksize.height11when normalize=trueotherwise
未归一化的方框滤波对于计算每个像素邻域内的各种积分特征非常有用,例如图像导数的协方差矩阵(用于密集光流算法等)。如果你需要在可变大小的窗口上计算像素总和,请使用 cv::integral。
支持的输入矩阵数据类型为 CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1。输出图像必须与输入图像具有相同的类型、大小和通道数。
注意:
如果硬件支持,则进行四舍五入到最近的偶数;如果不支持,则四舍五入到最近的整数。
函数文本ID是 “org.opencv.imgproc.filters.boxfilter”。
cv::gapi::boxFilter 是 OpenCV 的 G-API 模块中用于应用方框滤波(Box Filter)到图像的一个函数。这个函数可以在图像上执行快速的均值模糊处理。
函数原型
GMat cv::gapi::boxFilter
(
const GMat & src,
int dtype,
const Size & ksize,
const Point & anchor = Point(-1,-1),
bool normalize = true,
int borderType = BORDER_DEFAULT,
const Scalar & borderValue = Scalar(0)
)
参数
- 参数src: 源图像。
- 参数dtype: 输出图像深度(设为 -1 表示使用输入图像的数据类型)。
- 参数 ksize: 模糊内核大小。
- 参数anchor: 内核中的锚点位置。默认值 (-1,-1) 表示锚点位于内核中心。
- 参数 normalize: 标记,指定是否通过其面积对内核进行归一化处理。
- 参数 borderType: 像素外推方法,参见 cv::BorderTypes。
- 参数 borderValue: 在使用常量边界类型时使用的边界值。
代码示例
#include <opencv2/opencv.hpp>
#include <opencv2/gapi/imgproc.hpp> // 包含G-API imgproc模块
#include <opencv2/gapi/core.hpp> // 包含G-API核心模块
int main()
{
// 加载图像
cv::Mat img = cv::imread("/media/dingxin/data/study/OpenCV/sources/images/Lenna.png");
if (img.empty())
{
std::cerr << "无法加载图像" << std::endl;
return -1;
}
// 定义G-API计算图
cv::GMat in;
auto out = cv::gapi::boxFilter(in, img.depth(), cv::Size(15, 15), // 使用与输入相同的深度
cv::Point(-1, -1), true, cv::BORDER_DEFAULT);
// 创建并运行G-API编译器
cv::GComputation comp(cv::GIn(in), cv::GOut(out));
cv::Mat dst;
// 使用所有的内核
comp.apply(img, dst, cv::compile_args(cv::gapi::kernels()));
// 显示结果
cv::imshow("Original Image", img);
cv::imshow("Filtered Image", dst);
cv::waitKey();
return 0;
}