c#实现图片二值化例子(黑白效果)
2014-08-15 08:50
946 查看
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#实现主窗体工具栏上按钮两幅图片的交互效果
- C# 实现桌面图片飘浮效果
- C#实现图片轮转效果
- JS实现QQ图片一闪一闪的效果小例子
- C# 鼠标拖放图片透明缩略图效果实现思路
- C#实现绘制浮雕图片效果实例
- 折腾了一早上的C# WPF ListView+Grid 实现图片+文字 自动换行排列 类似Windows资源管理器效果
- C#实现,黑白照片的代码,联想可以实现老照片效果
- C#图像处理(各种旋转、改变大小、柔化、锐化、雾化、底片、浮雕、黑白、滤镜效果,滤波,图像截取) 对图片的处理 : 亮度调整 抓屏 翻转 随鼠标画矩形
- CSS3实用技巧:几行代码实现图片黑白效果
- C# 实现的 批量彩色图片转黑白图片的小工具 (附源码)
- renderScript实现图片放大,黑白,添加光源,怀旧效果实例附源码
- JS实现QQ图片一闪一闪的效果小例子
- c#实现显示图片的动态效果
- C#实现淡入淡出显示图像效果显示图片。
- .net里实现图片切换的效果/C#实现图片切换的效果
- c#简单实现图片二值化
- C#实现主窗体工具栏上按钮两幅图片的交互效果
- 类似 MSDN CSDN 导航树效果 ASP.Net(C#) + JavaScript 实现!