边缘检测类(包括Roberts, Sobel, Prewitt, Kirsch等算子的边缘检测算法)
public class EdgeDetect : ImageInfo
{
///
/// 对两幅图像进行梯度运算
///
/// 位图 1
/// 位图 2
///
private Bitmap Gradient(Bitmap b1, Bitmap b2)
{
int width = b1.Width;
int height = b1.Height;
BitmapData data1 = b1.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
BitmapData data2 = b2.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
unsafe
{
byte p1 = (byte)data1.Scan0;
byte p2 = (byte)data2.Scan0;
int offset = data1.Stride - width * BPP;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int i = 0; i < 3; i++)
{
int power = (int)Math.Sqrt((p1[i] p1[i] + p2[i] p2[i]));
p1[i] = (byte)(power > 255 ? 255 : power);
} // i
p1 += BPP;
p2 += BPP;
} // x
p1 += offset;
p2 += offset;
} // y
}
b1.UnlockBits(data1);
b2.UnlockBits(data2);
Bitmap dstImage = (Bitmap)b1.Clone();
b1.Dispose();
b2.Dispose();
return dstImage;
} // end of Gradient
///
/// 按 Roberts 算子进行边缘检测
///
/// 位图流
///
public Bitmap Roberts(Bitmap b)
{
int width = b.Width;
int height = b.Height;
Bitmap dstImage = new Bitmap(width, height);
BitmapData srcData = b.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
BitmapData dstData = dstImage.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
int stride = srcData.Stride;
int offset = stride - width * BPP;
unsafe
{
byte src = (byte)srcData.Scan0;
byte dst = (byte)dstData.Scan0;
int A, B; // A(x-1, y-1) B(x, y-1)
int C, D; // C(x-1, y) D(x, y)
// 指向第一行
src += stride;
dst += stride;
// 不处理最上边和最左边
for (int y = 1; y < height; y++)
{
// 指向每行第一列
src += BPP;
dst += BPP;
for (int x = 1; x < width; x++)
{
for (int i = 0; i < 3; i++)
{
A = src[i - stride - BPP];
B = src[i - stride];
C = src[i - BPP];
D = src[i];
dst[i] = (byte)(Math.Sqrt((A - D) (A - D) + (B - C) (B - C)));
} // i
dst[3] = src[3];
src += BPP;
dst += BPP;
} // x
src += offset;
dst += offset;
} // y
}
b.UnlockBits(srcData);
dstImage.UnlockBits(dstData);
b.Dispose();
return dstImage;
} // end of Roberts
评论 (0)