Sobel 算子
由于 Sobel 算子结合了 Gaussian 平滑和微分,因此其结果或多或少对噪声有一定的鲁棒性。采用以下算子分别计算一阶 x 方向和 y 方向的图像差分:
#include <math.h>
// Sobel 算子
// 1. pImageData 图像数据
// 2. nWidth 图像宽度
// 3. nHeight 图像高度
// 4. nWidthStep 图像行大小
BOOL Sobel(unsigned char *pImageData, int nWidth, int nHeight, int nWidthStep)
{
int i = 0;
int j = 0;
int nDx = 0;
int nDy = 0;
int nValue = 0;
unsigned char *pLine[3 = { NULL, NULL, NULL };
for (j = 1; j < nHeight - 1; j++)
{
pLine[0 = pImageData + nWidthStep * (j - 1);
pLine[1 = pImageData + nWidthStep * j;
pLine[2 = pImageData + nWidthStep * (j + 1);
for (i = 1; i < nWidth - 1; i++)
{
nDx =
pLine[0][i+1 - pLine[0][i-1 +
pLine[1][i+1 * 2 - pLine[1][i-1 * 2 +
pLine[2][i+1 - pLine[2][i-1];
nDy =
pLine[2][i-1 - pLine[0][i-1 +
pLine[2][i * 2 - pLine[0][i * 2 +
pLine[2][i+1 - pLine[0][i+1];
nValue = (int) sqrt((float) (nDx * nDx + nDy * nDy));
if (nValue > 0xFF)
{
nValue = 0xFF;
}
pLine[0][i-1 = (unsigned char) nValue;
}
}
return TRUE;
}
Sobel 边缘检测效果:
![Sobel 算子 - illidan - illidan的博客 Sobel 算子 - illidan - illidan的博客](http://img.blog.163.com/photo/-x5iA6eDwnQsptC1Ba9d4g==/287667426198900792.jpg)
![Sobel 算子 - illidan - illidan的博客 Sobel 算子 - illidan - illidan的博客](http://img.blog.163.com/photo/Abyjrm16W02zZ1xAZcbeAw==/4258997872609991187.jpg)
#include <math.h>
// Sobel 算子
// 1. pImageData 图像数据
// 2. nWidth 图像宽度
// 3. nHeight 图像高度
// 4. nWidthStep 图像行大小
BOOL Sobel(unsigned char *pImageData, int nWidth, int nHeight, int nWidthStep)
{
int i = 0;
int j = 0;
int nDx = 0;
int nDy = 0;
int nValue = 0;
unsigned char *pLine[3 = { NULL, NULL, NULL };
for (j = 1; j < nHeight - 1; j++)
{
pLine[0 = pImageData + nWidthStep * (j - 1);
pLine[1 = pImageData + nWidthStep * j;
pLine[2 = pImageData + nWidthStep * (j + 1);
for (i = 1; i < nWidth - 1; i++)
{
nDx =
pLine[0][i+1 - pLine[0][i-1 +
pLine[1][i+1 * 2 - pLine[1][i-1 * 2 +
pLine[2][i+1 - pLine[2][i-1];
nDy =
pLine[2][i-1 - pLine[0][i-1 +
pLine[2][i * 2 - pLine[0][i * 2 +
pLine[2][i+1 - pLine[0][i+1];
nValue = (int) sqrt((float) (nDx * nDx + nDy * nDy));
if (nValue > 0xFF)
{
nValue = 0xFF;
}
pLine[0][i-1 = (unsigned char) nValue;
}
}
return TRUE;
}
Sobel 边缘检测效果:
![Sobel 算子 - illidan - illidan的博客 Sobel 算子 - illidan - illidan的博客](http://img.blog.163.com/photo/-x5iA6eDwnQsptC1Ba9d4g==/287667426198900792.jpg)
![Sobel 算子 - illidan - illidan的博客 Sobel 算子 - illidan - illidan的博客](http://img.blog.163.com/photo/6E2VGluM5QjWEqVZKK-Qwg==/4258997872609991188.jpg)