国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

c#實現圖片二值化例子(黑白效果)

2020-01-24 02:31:53
字體:
來源:轉載
供稿:網友

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");      }    }  }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南安市| 平果县| 深水埗区| 巴彦淖尔市| 濮阳市| 福鼎市| 敦煌市| 应用必备| 土默特右旗| 湘潭县| 来安县| 中牟县| 龙游县| 巨鹿县| 凤庆县| 衡阳县| 大厂| 岳阳市| 萨迦县| 许昌县| 昌图县| 长岛县| 安化县| 南川市| 天气| 如东县| 明溪县| 洮南市| 海原县| 绿春县| 安溪县| 张家口市| 仙桃市| 灵宝市| 海盐县| 鹤岗市| 东方市| 游戏| 阿拉善盟| 南召县| 慈溪市|