zoukankan      html  css  js  c++  java
  • 一种图象二值化的算法(C#)

    源代码:
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Runtime.InteropServices;

    namespace Nobugz {
      static class Util {
        public static Bitmap BitmapTo1Bpp(Bitmap img) {
          int w = img.Width;
          int h = img.Height;
          Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
          BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
          for (int y = 0; y < h; y++) {
            byte[] scan = new byte[(w + 7) / 8];
            for (int x = 0; x < w; x++) {
              Color c = img.GetPixel(x, y);
              if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
            }
            Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
          }
          return bmp;
        }
      }
    }
    调用方法:
    Bitmap bmp = Nobugz.Util.BitmapTo1Bpp(new Bitmap(@"c:\temp\test1.bmp"));
    bmp.Save(@"c:\temp\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
    说明:
    A few remarks with this code.  Sadly, I couldn't avoid the pointer arithmetic in the Marshal.Copy() call, the code is not going to work in 64-bit apps.  And it is not going to be terribly fast, Bitmap.GetPixel() is slow.  Hope it works for you.
  • 相关阅读:
    团队作业4_项目冲刺
    Scrum冲刺_Day07
    Scrum冲刺_Day06
    Srcum冲刺_Day05
    Day1-7【Scrum 冲刺博客集合】
    团队作业6——事后诸葛亮分析
    团队作业6——Alpha阶段项目复审
    团队作业5——测试与发布(Alpha版本)
    Day7 【Scrum 冲刺博客】
    Day6【Scrum 冲刺博客】
  • 原文地址:https://www.cnblogs.com/xqzhao/p/1051327.html
Copyright © 2011-2022 走看看