目录
1 简介
Smart Blur(智能模糊) 是一种基于边缘检测的图像滤波算法,能够在平滑图像的同时保留边缘信息。与传统的模糊算法(如高斯模糊)不同,Smart Blur 通过检测图像中的边缘区域,并在这些区域减少模糊强度,从而在平滑图像的同时更好地保留边缘和细节。
Smart Blur 广泛应用于图像去噪、图像增强和艺术效果处理等领域。
2 算法原理
Smart Blur 的核心思想是结合边缘检测和模糊滤波,根据图像的边缘信息动态调整模糊强度。具体步骤如下:
-
边缘检测:
-
使用边缘检测算法(如 Sobel 或 Canny)检测图像中的边缘区域。
-
生成边缘掩码(Edge Mask),标记边缘区域。
-
-
模糊滤波:
-
对图像进行模糊滤波(如高斯模糊)。
-
根据边缘掩码调整模糊强度:在边缘区域减少模糊强度,在非边缘区域增加模糊强度。
-
-
图像融合:
-
将模糊后的图像与原始图像根据边缘掩码进行融合,得到最终结果。
-
3 代码实现
Smart Blur滤波的C语言代码实现如下
int SmartBlurOneChannel(unsigned char* srcData, int width, int height, int radius, int threshold)
{
int len = sizeof(unsigned long) * width * height;
int i, j;
int gray = 0;
unsigned char* tempData = (unsigned char*)malloc(sizeof(unsigned char) * height * width);
memcpy(tempData, srcData, sizeof(unsigned char) * height * width);
for (j = 0; j < height; j++)
{
for (i = 0; i < width; i++)
{
len = i + j * width;
gray = tempData[len];
int low = CLIP3(gray - threshold, 0, 255);
int high = CLIP3(gray + threshold, 0, 255);
int sum = 0;
int count = 0;
for (int n = -radius; n <= radius; n++)
{
for (int m = -radius; m <= radius; m++)
{
int x = CLIP3(i + m, 0, width - 1);
int y = CLIP3(j + n, 0, height - 1);
int pos = x + y * width;
gray = tempData[pos];
if (gray > low && gray < high)
{
sum += gray;
count++;
}
}
}
gray = count == 0 ? srcData[len] : sum / count;//sum / MAX2(count, 1);
srcData[len] = CLIP3(gray, 0, 255);
}
}
free(tempData);
return 0;
};
int mxSmartBlur(unsigned char* srcData, int nWidth, int nHeight, int nStride, int radius, int threshold)
{
int ret = 0;
if (srcData == NULL)
{
return ret;
}
if (radius == 0 || threshold == 0)
return ret;
unsigned char* yData = (unsigned char*)malloc(sizeof(unsigned char) * nWidth * nHeight);
unsigned char* cbData = (unsigned char*)malloc(sizeof(unsigned char) * nWidth * nHeight);
unsigned char* crData = (unsigned char*)malloc(sizeof(unsigned char) * nWidth * nHeight);
unsigned char* pSrc = srcData;
int Y, CB, CR;
unsigned char* pY = yData;
unsigned char* pCb = cbData;
unsigned char* pCr = crData;
for (int j = 0; j < nHeight; j++)
{
for (int i = 0; i < nWidth; i++)
{
RGBToYCbCr(pSrc[2], pSrc[1], pSrc[0], &Y, &CB, &CR);
*pY = Y;
*pCb = CB;
*pCr = CR;
pY++;
pCb++;
pCr++;
pSrc += 4;
}
}
SmartBlurOneChannel(yData, nWidth, nHeight, radius, threshold);
pSrc = srcData;
pY = yData;
pCb = cbData;
pCr = crData;
int R, G, B;
for (int j = 0; j < nHeight; j++)
{
for (int i = 0; i < nWidth; i++)
{
YCbCrToRGB(*pY, *pCb, *pCr, &R, &G, &B);
pSrc[0] = B;
pSrc[1] = G;
pSrc[2] = R;
pY++;
pCb++;
pCr++;
pSrc += 4;
}
}
free(yData);
free(cbData);
free(crData);
return ret;
}
4 演示Demo
4.1 开发环境
-
Windows 10 Pro x64
-
Visual Studio 2015
4.2 功能介绍
演示程序主界面如下图所示,具有图像读取、显示、保存、双边滤波、表面模糊、导向滤波、局部均值方差滤波、各向异性扩散滤波、Smart Blur滤波、处理耗时等功能。
原图
滤波效果图
4.3 下载地址
开发环境:
-
Windows 10 pro x64
-
Visual Studio 2015
参考
图像视频滤镜与人像美颜美妆算法详解. 胡耀武、谭娟、李云夕. 电子工业出版社、2020-07