110,580
社区成员
发帖
与我相关
我的任务
分享
int[,] h = new int[10000, 10000];
int[] t = new int[5000];
Color c = Color.FromArgb(128);
// Color cc = new Color();
int i, j;
int r;
int max = 0;
Bitmap pic = new Bitmap(pictureBox2.Image);
for (i = 1; i < pictureBox2.Image.Width; i++)
{
for (j = 1; j < pictureBox2.Image.Height; j++)
{
c = pic.GetPixel(i, j);
r = c.R;
h[i, j] = r;
}
}
for (i = 1; i < pictureBox2.Image.Width; i++)
{
for (j = 1; j < pictureBox2.Image.Height; j++)
{
for (r = 0; r < 255; r++)
{
if (h[i, j] == r)
{
t[r] = t[r] + 1;
}
}
}
}
//获得直方图的高度
max = t[0];
for (i = 0; i < t.Length - 1; i++)
{
if (t[i] > max)
{
max = t[i];
}
}
max = max / 2 + 1;
Bitmap currentBitmap = new Bitmap(500, max);
// Bitmap currentBitmap = new Bitmap(pictureBox3.Image);
for (r = 0; r < 500; r++)
{
for (j = 1; j < t[r]; j++)
{
currentBitmap.SetPixel(r, max - j / 2 - 1, c);
}
pictureBox3.Refresh();
pictureBox3.Image = currentBitmap;
}
public Bitmap GetGrayScale(Bitmap bmp)
{
if (bmp == null) return null;
int[] scales = new int[256];
int maxScale = 1;
int grayscale = 0;
int h = bmp.Height;
int w = bmp.Width;
BitmapData src = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
unsafe
{
byte* p = (byte*)src.Scan0.ToPointer();
int stride = src.Stride;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
grayscale = (p[2] + p[1] + p[0]) / 3; //换RGB到灰度(亮度)
scales[grayscale]++; //该亮度的统计增一
if (scales[grayscale] > maxScale)
{
maxScale = scales[grayscale]; //记住最大的数值
}
p += 3;
}
p += stride - w * 3;
}
}
bmp.UnlockBits(src);
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 y = 0; y < result.Height; y++)
{
g.DrawLine(Pens.Yellow, 0, y, scales[y], y); //每个色阶画一条线,长度依据该色阶的统计数值
}
}
return result;
}
private void button1_Click(object sender, EventArgs e)
{
int[] scales = new int[256]; //保存各阶亮度的统计
Bitmap bmp = new Bitmap( pictureBox1.Image );
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 = (c.R + c.G + c.B) / 3; //换RGB到灰度(亮度)
scales[grayscale]++; //该亮度的统计增一
if (scales[grayscale] > maxScale)
{
maxScale = scales[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 y=0; y<result.Height; y++)
{
g.DrawLine(Pens.Yellow, 0, y, scales[y], y); //每个色阶画一条线,长度依据该色阶的统计数值
}
}
pictureBox2.Image = result;
pictureBox2.Refresh();
}