对比度

让颜色暗的更暗,亮的更亮,把颜色拉开

使用的对比度调整算法基本都相同

128 + (Value - 128) * nPercent / 100
由RGB颜色分量 Value 和对比度调整数值计算新的颜色分量值

PhotoShop中稍有不同的是,基准值并不是采用128而是使用了图片的亮度平均值

亮度算法 .299   *   red   +   .587   *   green   +   .114   *   blue

http://hi.baidu.com/alphablend/blog/item/cd43f32e2a52b6301f3089c5.html

当值比较小时女孩身上的白色衣服花纹还能看清楚,发丝清晰可见

image

当值比较大时衣服上的花纹就被忽略了,头发丝也模糊了

image

 

PhotoShop中对比度调整的效果就要添加一步亮度直方图的计算:

public int GetHistogram(Bitmap b)
{
    int width = b.Width;
    int height = b.Height;
    double allLightValue = 0;

    BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                 b.PixelFormat);
    //Bytes Per Pixel
    int BPP = 4;
    unsafe
    {
        byte* p = (byte*)data.Scan0;
        int offset = data.Stride - width * BPP;

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                //计算亮度
                allLightValue += (p[2]*0.299 + p[1]*0.587 + p[0]*0.114);                      

                p += BPP;
            }

            p += offset;
        }

        b.UnlockBits(data);

        return (int)allLightValue/width/height;
    }
}

 

其他主要代码

public Bitmap Contrast(Bitmap b,int deep)
{
    if (deep < 0)
        deep = 0;
    else if (deep > 255)
        deep = 255;

    int width = b.Width;
    int height = b.Height;

    int histogram = GetHistogram(b);

    BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                 b.PixelFormat);
    //Bytes Per Pixel
    int BPP = 4;
    unsafe
    {
        byte* p = (byte*)data.Scan0;
        int offset = data.Stride - width * BPP;
        int pixel;

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                for (int i = 0; i < 3; i++)
                {
                    pixel = histogram + (p[i] - histogram) * deep / 100;
                    if (pixel < 0)
                        pixel = 0;
                    if (pixel > 255)
                        pixel = 255;
                    p[i] = (byte)pixel;
                }

                p += BPP;
            }

            p += offset;
        }

        b.UnlockBits(data);

        return b;
    }
}

posted on 2010-01-18 10:38  六道众生  阅读(444)  评论(0编辑  收藏  举报

导航