欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-14 10:26:46
c#将图片2值化示例代码,原图及二值化后的图片如下: 原图: 二值化后的图像: 实现代码: using system; using system....

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

原图:

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

二值化后的图像:

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

实现代码:

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