边缘检测类算法(4) (2008-06-06 19:55:56)

hegangben
2025-07-14 / 0 评论 / 0 阅读 / 正在检测是否收录...

//

/// 按水平边缘检测算子进行边缘检测

///

///

///

public Bitmap EdgeDetectHorizontal(Bitmap b)

{

int[,] kernel = {

{ 0, 0, 0, 0, 0, 0, 0},

{ 0, 0, 0, 0, 0, 0, 0},

{-1, -1, -1, -1, -1, -1, -1},

{ 0, 0, 0, 0, 0, 0, 0},

{ 1, 1, 1, 1, 1, 1, 1},

{ 0, 0, 0, 0, 0, 0, 0},

{ 0, 0, 0, 0, 0, 0, 0},

};

MatrixNxN m = new MatrixNxN();

m.Kernel = kernel;

return m.Convolute(b);

} // end of EdgeDetectHorizontal

///

/// 按垂直边缘检测算子进行边缘检测

///

///

///

public Bitmap EdgeDetectVertical(Bitmap b)

{

int[,] kernel = {

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

{ 0, 0, -1, 0, 1, 0, 0},

};

MatrixNxN m = new MatrixNxN();

m.Kernel = kernel;

return m.Convolute(b);

} // end of EdgeDetectVertical

///

/// 边缘增强

///

/// 位图流

/// 阈值

///

public Bitmap EdgeEnhance(Bitmap b, int threshold)

{

int width = b.Width;

int height = b.Height;

Bitmap dstImage = (Bitmap)b.Clone();

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);

// 图像实际处理区域

// 不考虑最左 1 列和最右 1 列

// 不考虑最上 1 行和最下 1 行

int rectTop = 1;

int rectBottom = height - 1;

int rectLeft = 1;

int rectRight = width - 1;

unsafe

{

byte src = (byte)srcData.Scan0;

byte dst = (byte)dstData.Scan0;

int stride = srcData.Stride;

int offset = stride - width * BPP;

int pixel = 0;

int maxPixel = 0;

// 指向第 1 行

src += stride;

dst += stride;

for (int y = rectTop; y < rectBottom; y++)

{

// 指向每行第 1 列像素

src += BPP;

dst += BPP;

for (int x = rectLeft; x < rectRight; x++)

{

// Alpha

dst[3] = src[3];

// 处理 B, G, R 三分量

for (int i = 0; i < 3; i++)

{

// 右上-左下

maxPixel = src[i - stride + BPP] - src[i + stride - BPP];

if (maxPixel < 0) maxPixel = -maxPixel;

// 左上-右下

pixel = src[i - stride - BPP] - src[i + stride + BPP];

if (pixel < 0) pixel = -pixel;

if (pixel > maxPixel) maxPixel = pixel;

// 上-下

pixel = src[i - stride] - src[i + stride];

if (pixel < 0) pixel = -pixel;

if (pixel > maxPixel) maxPixel = pixel;

// 左-右

pixel = src[i - BPP] - src[i + BPP];

if (pixel < 0) pixel = -pixel;

if (pixel > maxPixel) maxPixel = pixel;

// 进行阈值判断

if (maxPixel < threshold) maxPixel = 0;

dst[i] = (byte)maxPixel;

}

// 向后移一像素

src += BPP;

dst += BPP;

} // x

// 移向下一行

// 这里得注意要多移 1 列,因最右边还有 1 列不必处理

src += offset + BPP;

dst += offset + BPP;

} // y

}

// b.UnlockBits(srcData);

dstImage.UnlockBits(dstData);

b.Dispose();

return dstImage;

} // end of EdgeEnhance

}

0

评论 (0)

取消