温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Bitmap图像在C#中的直方图均衡

发布时间:2024-07-16 10:30:07 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

直方图均衡是一种用于增强图像对比度的技术,通过对图像的像素值进行调整,使得图像的亮度分布更均匀。在C#中,可以使用以下代码实现对Bitmap图像的直方图均衡:

using System;
using System.Drawing;
using System.Drawing.Imaging;

class Program
{
    static void Main()
    {
        // 读取图像
        Bitmap bmp = new Bitmap("image.jpg");

        // 获取图像的直方图
        int[] histogram = new int[256];
        for (int y = 0; y < bmp.Height; y++)
        {
            for (int x = 0; x < bmp.Width; x++)
            {
                Color pixel = bmp.GetPixel(x, y);
                int gray = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);
                histogram[gray]++;
            }
        }

        // 计算累积分布函数
        int[] cdf = new int[256];
        cdf[0] = histogram[0];
        for (int i = 1; i < 256; i++)
        {
            cdf[i] = cdf[i - 1] + histogram[i];
        }

        // 归一化
        for (int i = 0; i < 256; i++)
        {
            cdf[i] = (int)((double)(cdf[i] - cdf[0]) / ((bmp.Width * bmp.Height) - cdf[0]) * 255);
        }

        // 应用直方图均衡
        for (int y = 0; y < bmp.Height; y++)
        {
            for (int x = 0; x < bmp.Width; x++)
            {
                Color pixel = bmp.GetPixel(x, y);
                int gray = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);
                int newGray = cdf[gray];
                Color newPixel = Color.FromArgb(newGray, newGray, newGray);
                bmp.SetPixel(x, y, newPixel);
            }
        }

        // 保存均衡化后的图像
        bmp.Save("equalized_image.jpg", ImageFormat.Jpeg);
    }
}

在这段代码中,首先读取了一张图像,然后计算了图像的直方图并根据直方图计算了累积分布函数。接着对图像的每个像素进行直方图均衡的处理,最后保存均衡化后的图像。通过这个过程,可以将图像的对比度得到增强,使得图像更加清晰和易于分析。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI