[函数名称]
图像Sobel边缘检测函数SobelEdgeProcess(WriteableBitmap src)
[函数代码]
///
/// Sobel edge detection.
///
///Source image.
///
publicstaticWriteableBitmap SobelEdgeProcess(WriteableBitmap src)////12 Sobel边缘检测
{
if(src!=null )
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap sobelImage =newWriteableBitmap(w,h);
byte[] temp = src.PixelBuffer.ToArray();
byte[] tempMask = (byte[])temp.Clone();
int b = 0, g = 0, r = 0;
for (int j = 1; j < h - 1; j++)
{
for (int i = 4; i < w * 4 - 4; i += 4)
{
if (i == 0 || i == w - 4 || j == 0 || j == h - 1)
{
temp[i + j * w * 4] = (byte)0;
temp[i + 1 + j * w * 4] = (byte)0;
temp[i + 2 + j * w * 4] = (byte)0;
}
else
{
b =Math.Abs(tempMask[i - 4 + (j - 1) * w * 4] + 2 * tempMask[i - 4 + j * w * 4] + tempMask[i - 4 + (j + 1) * w * 4] - tempMask[i + 4 + (j - 1) * w * 4]
- 2 * tempMask[i + 4 + j * w * 4] - tempMask[i + 4 + (j + 1) * w * 4]) + Math.Abs(tempMask[i - 4 + (j - 1) * w * 4] + 2 * tempMask[i + (j - 1) * w * 4]
+ tempMask[i + 4 + (j - 1) * w * 4] - tempMask[i - 4 + (j + 1) * w * 4] - 2 * tempMask[i + (j + 1) * w * 4] - tempMask[i + 4 + (j + 1) * w * 4]);
g =Math.Abs(tempMask[i - 4 + 1 + (j - 1) * w * 4] + 2 * tempMask[i - 4 + 1 + j * w * 4] + tempMask[i - 4 + 1 + (j + 1) * w * 4] - tempMask[i + 4 + 1 + (j - 1) * w * 4]
- 2 * tempMask[i + 4 + 1 + j * w * 4] - tempMask[i + 4 + 1 + (j + 1) * w * 4]) +Math.Abs(tempMask[i - 4 + 1 + (j - 1) * w * 4] + 2 * tempMask[i + 1 + (j - 1) * w * 4]
+ tempMask[i + 4 + 1 + (j - 1) * w * 4] - tempMask[i - 4 + 1 + (j + 1) * w * 4] - 2 * tempMask[i + 1 + (j + 1) * w * 4] - tempMask[i + 1 + 4 + (j + 1) * w * 4]);
r =Math.Abs(tempMask[i - 4 + 2 + (j - 1) * w * 4] + 2 * tempMask[i - 4 + 2 + j * w * 4] + tempMask[i - 4 + 2 + (j + 1) *w * 4] - tempMask[i + 4 + 2 + (j - 1) * w * 4]
- 2 * tempMask[i + 4 + 2 + j * w * 4] - tempMask[i + 4 + 2 + (j + 1) * w * 4]) +Math.Abs(tempMask[i - 4 + 2 + (j - 1) * w * 4] + 2 * tempMask[i + 2 + (j - 1) * w * 4]
+ tempMask[i + 4 + 2 + (j - 1) * w * 4] - tempMask[i - 4 + 2 + (j + 1) * w * 4] - 2 * tempMask[i + 2 + (j + 1) * w * 4] - tempMask[i + 2 + 4 + (j + 1) * w * 4]);
temp[i + j * w * 4] = (byte)(b > 0 ? (b < 255 ? b : 255) : 0);
temp[i + 1 + j * w * 4] = (byte)(g > 0 ? (g < 255 ? g : 255) : 0);
temp[i + 2 + j * w * 4] = (byte)(r > 0 ? (r < 255 ? r : 255) : 0);
}
b = 0; g = 0; r = 0;
}
}
Stream sTemp = sobelImage.PixelBuffer.AsStream();
sTemp.Seek(0,SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return sobelImage;
}
else
{
returnnull;
}
}