为了从图像中检测边缘,我尝试实现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;但所得到的图像大多是白色的。这是原图:

这是经过变换的图像:

我不知道我做错了什么。有人能帮我吗?
谢谢你的进阶!
发布于 2017-06-03 18:46:49
使用另一个位图保存输出如下:
Bitmap res = new Bitmap(bmp.Width, bmp.Height);
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)
{
res.SetPixel(i, j, Color.White);
}
else
{
res.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
}
}
}https://stackoverflow.com/questions/44347201
复制相似问题