public static GradientVector[,] SuppressMaximums(this GradientVector[,] vecs) { GradientVector[,] res = new GradientVector[vecs.GetLength(0), vecs.GetLength(1)]; for (int y = 1; y < vecs.GetLength(0) - 1; y++) { for (int x = 1; x < vecs.GetLength(1) - 1; x++) { res[y, x].Angle = vecs[y, x].Angle; switch (vecs[y, x].Angle) { case 0: { res[y, x].Length = vecs[y, x].Length >= vecs[y, x + 1].Length && vecs[y, x].Length >= vecs[y, x - 1].Length ? vecs[y, x].Length : 0; break; } case 90: { res[y, x].Length = vecs[y, x].Length >= vecs[y + 1, x].Length && vecs[y, x].Length >= vecs[y - 1, x].Length ? vecs[y, x].Length : 0; break; } case 45: { res[y, x].Length = vecs[y, x].Length >= vecs[y - 1, x - 1].Length && vecs[y, x].Length >= vecs[y + 1, x + 1].Length ? vecs[y, x].Length : 0; break; } case -45: { res[y, x].Length = vecs[y, x].Length >= vecs[y + 1, x - 1].Length && vecs[y, x].Length >= vecs[y - 1, x + 1].Length ? vecs[y, x].Length : 0; break; } } } } return(res); }
/// <summary> /// Finds gradients and angle of gradients (Sobel); /// </summary> /// <param name="pic">Picture.</param> /// <returns>Array of Gradients.</returns> public static GradientVector[,] FindGradients(this Bitmap pic) { GradientVector[,] vecs = new GradientVector[pic.Height, pic.Width]; double[,] gYMask = new double[, ] { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } }; double[,] gXMask = new double[, ] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } }; for (int x = 1; x < pic.Width - 1; x++) { for (int y = 1; y < pic.Height - 1; y++) { double gYRes = 0; double gXRes = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { byte b = pic.GetPixel(x + j, y + i).R; gXRes += pic.GetPixel(x + j, y + i).R *gXMask[i + 1, j + 1]; gYRes += pic.GetPixel(x + j, y + i).R *gYMask[i + 1, j + 1]; } } vecs[y, x].Length = Math.Sqrt(gXRes * gXRes + gYRes * gYRes); vecs[y, x].Angle = GetCorrectAngle(Math.Atan(gYRes / gXRes)); } } return(vecs); }