电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

WPF:图像处理二值化


发布日期:2021/10/30
 
using System;

using SystemWindowsMedia;

using SystemWindowsMediaImaging;

namespace SplashImaging

{

/// <summary>

/// 二值化方法

/// </summary>

public enum BinarizationMethods

{

Otsu // 大津法

Iterative // 迭代法

}

/// <summary>

/// 图像处理图像二值化

/// </summary>

public static partial class Binarize

{

/// <summary>

/// 全局阈值图像二值化

/// </summary>

/// <param name=bitmap>原始图像</param>

/// <param name=method>二值化方法</param>

/// <param name=threshold>输出全局阈值</param>

/// <returns>二值化后的图像数组</returns>

public static Byte[] ToBinaryArray(this BitmapSource bitmap BinarizationMethods method out Int threshold)

{ // 位图转换为灰度数组

Byte[] GrayArray = bitmapToGrayArray()

// 计算全局阈值

if (method == BinarizationMethodsOtsu)

threshold = OtsuThreshold(GrayArray)

else

threshold = IterativeThreshold(GrayArray)

// 根据阈值进行二值化

Int PixelHeight = bitmapPixelHeight;

Int PixelWidth = bitmapPixelWidth;

Byte[] BinaryArray = new Byte[PixelHeight PixelWidth];

for (Int i = ; i < PixelHeight; i++)

{

for (Int j = ; j < PixelWidth; j++)

{

BinaryArray[ij] = ConvertToByte((GrayArray[ij] > threshold) ? :

}

}

return BinaryArray;

}

/// <summary>

/// 全局阈值图像二值化

/// </summary>

/// <param name=bitmap>原始图像</param>

/// <param name=method>二值化方法</param>

/// <param name=threshold>输出全局阈值</param>

/// <returns>二值化图像</returns>

public static BitmapSource ToBinaryBitmap(this BitmapSource bitmap BinarizationMethods method out Int threshold)

{ // 位图转换为灰度数组

Byte[] GrayArray = bitmapToGrayArray()

// 计算全局阈值

if (method == BinarizationMethodsOtsu)

threshold = OtsuThreshold(GrayArray)

else

threshold = IterativeThreshold(GrayArray)

// 将灰度数组转换为二值数据

Int PixelHeight = bitmapPixelHeight;

Int PixelWidth = bitmapPixelWidth;

Int Stride = ((PixelWidth + ) >> ) 《 ;

Byte[] Pixels = new Byte[PixelHeight * Stride];

for (Int i = ; i < PixelHeight; i++)

{

Int Base = i * Stride;

for (Int j = ; j < PixelWidth; j++)

{

if (GrayArray[i j] > threshold)

{

Pixels[Base + (j 》 )] |= ConvertToByte(x 》 (j & x))

}

}

}

// 从灰度数据中创建灰度图像

return BitmapSourceCreate(PixelWidth PixelHeight PixelFormatsIndexed BitmapPalettesBlackAndWhite Pixels Stride)

}

}

}

上一篇:老生常谈:建造者模式

下一篇:WCF中的Data Contract:Data Contract概览