灰度图像转化为黑白图像、转化图像为一位位深度的图像(仅保留黑色)

/// <summary>
/// 灰度图像处理
/// </summary>
public class PicGray
{
    /// <summary>
    /// 获取pic图像对应的黑白图像
    /// </summary>
    /// <param name="pic"></param>
    /// <param name="NumGray">像素灰度值</param>
    /// <returns></returns>
    public static Bitmap ToBlack(Bitmap pic, int NumGray = 220)
    {
        // 灰度图像转化为黑白图像
        if (isGrayPic(pic))
        {
            Color Black = Color.FromArgb(255, 0, 0, 1);
            Color White = Color.FromArgb(255, 255, 255, 254);

            Bitmap tmp = new Bitmap(pic.Width, pic.Height);
            for (int h = 0; h < pic.Height; h++)
            {
                for (int w = 0; w < pic.Width; w++)
                {
                    Color C = pic.GetPixel(w, h);
                    Color D = (C.R < NumGray && C.G < NumGray && C.B < NumGray) ? Black : White;
                    tmp.SetPixel(w, h, D);
                }
            }

            return tmp;
        }
        else return pic;
    }

    /// <summary>
    /// 判断图像是否为灰度图像
    /// </summary>
    /// <param name="pic"></param>
    /// <returns></returns>
    public static bool isGrayPic(Bitmap pic)
    {
        int stepH = pic.Height / 100;
        int stepW = pic.Width / 100;
        if (stepH < 1) stepH = 1;
        if (stepW < 1) stepW = 1;

        for (int h = 0; h < pic.Height; h = h + stepH)
        {
            for (int w = 0; w < pic.Width; w = w + stepW)
            {
                Color C = pic.GetPixel(w, h);
                if (C.R != C.G || C.G != C.B) return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 转化为一位位深度的图像(仅保留黑色)
    /// </summary>
    /// <param name="pic"></param>
    /// <returns></returns>
    private Bitmap To1Bit(Bitmap pic)
    {
        var newbitmap = pic.Clone(new Rectangle(0, 0, pic.Width, pic.Height), PixelFormat.Format1bppIndexed);
        return newbitmap;
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值