索贝尔算子(Sobeloperator)主要用作边缘检测,在技术上,它是一离散性差分算子,用来运算图像亮度函数的灰度之近似值。在图像的任何一点使用此算子,将会产生对应的灰度矢量或是其法矢量
Sobel卷积因子为:
http://blog.csdn.net/goodshot/article/details/10170073
http://blog.csdn.net/yanmy2012/article/details/8110316
为了加快算法速度:
先缩小图像,步长为2,然后计算梯度,
void getGrads(unsigned char* g_lpTemp, unsigned char* g_lpDivide, int IMGW, int IMGH, long r)
{
long x, y, i, j;
long vx, vy, lvx, lvy;
unsigned char *lpSrc = NULL;
unsigned char *lpDiv = NULL;
long num;
int gradSum;
int grad;
r=6;
for(y = 0; y < IMGH/2; y++)
{
for(x = 0; x < IMGW/2; x++)
{
lpDiv = g_lpDivide + 2*y*IMGW + 2*x;
lvx = 0;
lvy = 0;
num = 0;
gradSum = 0;
for(i = -r; i <= r; i++) // 为提高速度,步长为2
{
if(y+i<1 || y+i>=IMGH/2-1) continue;
for(j = -r; j <= r; j++) // 为提高速度,步长为2
{
if(x+j<1 || x+j>=IMGW/2-1) continue;
lpSrc = g_lpTemp + (y+i)*(IMGW/2) + x+j;
//求x方向偏导
vx = *(lpSrc + IMGW/2 + 1) - *(lpSrc + IMGW/2 - 1) +
*(lpSrc + 1)*2 - *(lpSrc - 1)*2 +
*(lpSrc - IMGW/2 + 1) - *(lpSrc - IMGW/2 - 1);
//求y方向偏导
vy = *(lpSrc + IMGW/2 - 1) - *(lpSrc - IMGW/2 - 1) +
*(lpSrc + IMGW/2)*2 - *(lpSrc - IMGW/2)*2 +
*(lpSrc + IMGW/2 + 1) - *(lpSrc - IMGW/2 + 1);
gradSum += (labs(vx)+labs(vy));
//gradSum += vx*vx+vy*vy;
num++;
}
}
if(num == 0)
num = 1;
// 求幅值,保存到g_lpDivide中,用于分割前景背景
grad = gradSum/num;
if(grad > 255)
grad = 255;
*lpDiv = (BYTE)grad;
*(lpDiv + 1) = (BYTE)grad;
*(lpDiv + IMGW) = (BYTE)grad;
*(lpDiv + IMGW + 1) = (BYTE)grad;
}
}
}