C#: Sobel gradient magnitude on a diagonal edge
The Sobel operator uses two 3×3 kernels, one for the horizontal gradient Gx and one for the vertical gradient Gy. The strength of an edge at a pixel is the gradient magnitude √(Gx² + Gy²), and the angle of the edge normal is atan2(Gy, Gx).
C#
using System;
class Program {
static void Main() {
int[,] image = new int[5, 5];
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 5; c++) {
image[r, c] = c >= r ? 100 : 0;
}
}
int[,] kx = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
int[,] ky = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
for (int r = 1; r < 4; r++) {
string row = "";
for (int c = 1; c < 4; c++) {
int gx = 0, gy = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int pixel = image[r - 1 + i, c - 1 + j];
gx += pixel * kx[i, j];
gy += pixel * ky[i, j];
}
}
row += ((int)Math.Round(Math.Sqrt(gx * gx + gy * gy))).ToString().PadLeft(5);
}
Console.WriteLine(row);
}
}
}