手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#实现图片二值化例子(黑白效果)
c#实现图片二值化例子(黑白效果)
摘要:C#将图片2值化示例代码,原图及二值化后的图片如下:原图:二值化后的图像:实现代码:usingSystem;usingSystem.Draw...

C#将图片2值化示例代码,原图及二值化后的图片如下:

原图:

c#实现图片二值化例子(黑白效果)1

二值化后的图像:

c#实现图片二值化例子(黑白效果)2

实现代码:

using System; using System.Drawing; namespace BMP2Grey { class Program { static void ToGrey(Bitmap img1) { for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); //计算灰度值 int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B); Color newColor = Color.FromArgb(grey, grey, grey); img1.SetPixel(i, j, newColor); } } } static void Thresholding(Bitmap img1) { int[] histogram = new int[256]; int minGrayValue=255, maxGrayValue=0; //求取直方图 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); histogram[pixelColor.R]++; if (pixelColor.R > maxGrayValue) maxGrayValue = pixelColor.R; if (pixelColor.R < minGrayValue) minGrayValue = pixelColor.R; } } //迭代计算阀值 int threshold = -1; int newThreshold = (minGrayValue + maxGrayValue) / 2; for(int iterationTimes = 0; threshold != newThreshold && iterationTimes < 100; iterationTimes++) { threshold = newThreshold; int lP1 =0; int lP2 =0; int lS1 = 0; int lS2 = 0; //求两个区域的灰度的平均值 for (int i = minGrayValue;i < threshold;i++) { lP1 += histogram[i] * i; lS1 += histogram[i]; } int mean1GrayValue = (lP1 / lS1); for (int i = threshold+1;i < maxGrayValue;i++) { lP2 += histogram[i] * i; lS2 += histogram[i]; } int mean2GrayValue = (lP2 / lS2); newThreshold = (mean1GrayValue + mean2GrayValue) / 2; } //计算二值化 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); if (pixelColor.R > threshold) img1.SetPixel(i, j, Color.FromArgb(255, 255, 255)); else img1.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } } } static void Main(string[] args) { try { //打开位图文件 Bitmap img1 = new Bitmap("test.jpg", true); //灰度化 ToGrey(img1); //二值化 Thresholding(img1); //写回位图文件 img1.Save("output.jpg"); Console.WriteLine("Converted."); } catch (ArgumentException) { Console.WriteLine("Invalid usage!"); Console.WriteLine("Usage: bmp2grey source object"); } } } }

【c#实现图片二值化例子(黑白效果)】相关文章:

c#实现16进制和字符串之间转换的代码

C# 获取程序集版本、文件版本

关于C#程序优化的五十种方法

C#实现图片分割方法与代码

C# 将字节流转换为图片的实例方法

c# 删除所有的空文件夹的小例子

c# 重载WndProc,实现重写“最小化”的实现方法

c#数据的序列化和反序列化(推荐版)

C#中实现网段扫描的代码

c# 实现窗体拖到屏幕边缘自动隐藏

精品推荐
分类导航