Sobel主要用于初步寻找图像的边缘信息,同时也可以起到图像锐化作用。常用的3*3的模板卷积实现,主要是通过水平和垂直两个方向卷积实现。
具体代码实现:
void sobel(image_t* src, grad_t *grad)
{
int y, x;
int w = src->w;
int h = src->h;
grad->w = w;
grad->h = h;
int gx = 0, gy = 0;
uchar *src_ptr = src->data + w;
uchar *gx_ptr = grad->gx + w;
uchar *gy_ptr = grad->gy + w;
uchar *mag_ptr = grad->mag + w;
uchar *angle_ptr = grad->angle + w;
for (y = 1; y < h - 1; y++)
{
for (x = 1; x < w - 1; x++)
{
gx = src_ptr[x + 1 - w]
+ src_ptr[x + 1] * 2
+ src_ptr[x + 1 + w]
- src_ptr[x - 1 - w]
- src_ptr[x - 1] * 2
- src_ptr[x - 1 + w];
gy = src_ptr[x - 1 - w]
+ src_ptr[x - w] * 2
+ src_ptr[x + 1 - w]
- src_ptr[x - 1 + w]
- src_ptr[x + w] * 2
- src_ptr[x + 1 + w];
gx_ptr[x] = gx;
gy_ptr[x] = gy;
mag_ptr[x] = abs(gx) + abs(gy);
if (gx == 0)
angle_ptr[x] = PI / 2;
if (gy == 0)
angle_ptr[x] = 0;
else
angle_ptr[x] = atan(gy / gx);
}
gx_ptr += w;
gy_ptr += w;
mag_ptr += w;
angle_ptr += w;
}
}
若有不当之处,欢迎指正,谢谢!