Sobel算法实现(C语言) 1 void MySobel(IplImage* gray, IplImage* gradient)
2 {
3 /* Sobel template
4 a00 a01 a02
5 a10 a11 a12
6 a20 a21 a22
7 */
8
9 unsigned char a00, a01, a02;
10 unsigned char a10, a11, a12;
11 unsigned char a20, a21, a22;
12 CvScalar color ;
13 for (int i=1; i<gray->height-1; ++i)
14 {
15 for (int j=1; j<gray->width-1; ++j)
16 {
17
18 a00 = cvGet2D(gray, i-1, j-1).val[0];
19 a01 = cvGet2D(gray, i-1, j).val[0];
20 a02 = cvGet2D(gray, i-1, j+1).val[0];
21
22 a10 = cvGet2D(gray, i, j-1).val[0];
23 a11 = cvGet2D(gray, i, j).val[0];
24 a12 = cvGet2D(gray, i, j+1).val[0];
25
26 a20 = cvGet2D(gray, i+1, j-1).val[0];
27 a21 = cvGet2D(gray, i+1, j).val[0];
28 a22 = cvGet2D(gray, i+1, j+1).val[0];
29
30 // x方向上的近似导数
31 double ux = a20 * (1) + a21 * (2) + a22 * (1)
32 + (a00 * (-1) + a01 * (-2) + a02 * (-1));
33
34 // y方向上的近似导数
35 double uy = a02 * (1) + a12 * (2) + a22 * (1)
36 + a00 * (-1) + a10 * (-2) + a20 * (-1);
37
38 color.val[0] = sqrt(ux*ux + uy*uy);
39
40 cvSet2D(gradient, i, j, color);
41 }
42 }
43 }
//注释:该程序需要在安装Opencv软件下运行。