图像灰度化将图像中的所有像素按照 0.3*r+0.59*g+0.11*b 的方式灰度处理
直方均衡算法
1.统计每个灰度阶像素的数目
2.求每个灰度级占总数的概率
3.求每个灰度级的累积概率 c[]
4.按照c[src[x][y]]*range+min 确定新图像的灰度,其中range是这个图像的灰度范围,min是整个图像最小的灰度值
int maxScale=1;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Color c = bmp.GetPixel(x, y);
int grayscale =(int) (0.3*c.R +0.59* c.G +0.11*c.B); //换RGB到灰度(亮度)
Color temp = Color.FromArgb(100,grayscale,grayscale,grayscale);
bmp.SetPixel(x,y,temp);
scales[grayscale]++; //该亮度的统计增一
if (scales[grayscale] > max)
maxScale = scales[grayscale]; //记住最大的数值
if (grayscale > max)
max = grayscale; //记住最大的数值
if (grayscale < min)
min = grayscale; //记住最小的数值
}
}
for (int i = 0; i < scales.Length; i++)
scales[i] = scales[i] * 255 / maxScale; //把亮度数组缩小到0~255区间,以便用图像直观表示出来
Bitmap result = new Bitmap(256, 256); //准备一个直方图
using (Graphics g = Graphics.FromImage(result))
{
for (int x = 0; x < result.Height; x++)
g.DrawLine(Pens.Black, x, result.Height, x, result.Height - scales[x]); //每个色阶画一条线,长度依据该色阶的统计数值
}
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Color c = bmp.GetPixel(x, y);
grayscale=(int)(p[c.R]*range+min);
Color temp = Color.FromArgb(100,grayscale,grayscale,grayscale);
bmp.SetPixel(x, y, temp);
}
}