0
我想實現Sobel算法以檢測圖像的邊緣。索貝爾算法
我寫了下面的代碼:
bmp = new Bitmap(pictureBox1.Image);
int[][] sobelx = {new int[] {-1, 0, 1},
new int[] {-2, 0, 2},
new int[] {-1, 0, 1}};
int[][] sobely = {new int[] {-1, -2, -1},
new int[] { 0, 0, 0},
new int[] { 1, 2, 1}};
for (int i = 1; i < bmp.Width - 1; i++)
{
for (int j = 1; j < bmp.Height - 1; j++)
{int dx = bmp.GetPixel(i - 1, j - 1).R * sobelx[0][0] + bmp.GetPixel(i, j - 1).R * sobelx[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobelx[0][2]
+ bmp.GetPixel(i - 1, j).R * sobelx[1][0] + bmp.GetPixel(i, j).R * sobelx[1][1] + bmp.GetPixel(i + 1, j).R * sobelx[1][2]
+ bmp.GetPixel(i - 1, j + 1).R * sobelx[2][0] + bmp.GetPixel(i, j + 1).R * sobelx[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobelx[2][2];
int dy = bmp.GetPixel(i - 1, j - 1).R * sobely[0][0] + bmp.GetPixel(i, j - 1).R * sobely[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobely[0][2]
+ bmp.GetPixel(i - 1, j).R * sobely[1][0] + bmp.GetPixel(i, j).R * sobely[1][1] + bmp.GetPixel(i + 1, j).R * sobely[1][2]
+ bmp.GetPixel(i - 1, j + 1).R * sobely[2][0] + bmp.GetPixel(i, j + 1).R * sobely[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobely[2][2];
double derivata = Math.Sqrt((dx * dx) + (dy * dy));
if (derivata > 255)
{
bmp.SetPixel(i, j, Color.White);
}
else
{
bmp.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
}
}
}
pictureBox2.Image = bmp;
這是轉換圖像:
我不知道我做錯了。任何人都可以幫我嗎?
謝謝先進!