gpt4 book ai didi

c# - 确定图像整体亮度

转载 作者:太空狗 更新时间:2023-10-29 18:32:44 26 4
gpt4 key购买 nike

我需要在图片上叠加一些文字;根据整体图像亮度,此文本应更亮或更暗。如何计算图像的整体(感知)亮度?

为单像素发现了一些有趣的东西: Formula to determine brightness of RGB color

最佳答案

由我解决:

    public static double CalculateAverageLightness(Bitmap bm)
{
double lum = 0;
var tmpBmp = new Bitmap(bm);
var width = bm.Width;
var height = bm.Height;
var bppModifier = bm.PixelFormat == PixelFormat.Format24bppRgb ? 3 : 4;

var srcData = tmpBmp.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
var stride = srcData.Stride;
var scan0 = srcData.Scan0;

//Luminance (standard, objective): (0.2126*R) + (0.7152*G) + (0.0722*B)
//Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B)
//Luminance (perceived option 2, slower to calculate): sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 )

unsafe
{
byte* p = (byte*)(void*)scan0;

for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int idx = (y * stride) + x * bppModifier;
lum += (0.299*p[idx + 2] + 0.587*p[idx + 1] + 0.114*p[idx]);
}
}
}

tmpBmp.UnlockBits(srcData);
tmpBmp.Dispose();
var avgLum = lum / (width * height);


return avgLum/255.0;
}

关于c# - 确定图像整体亮度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7964839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com