从点数组中绘制直方图

Ham*_*Net 1 c# histogram

我正在做一个图像处理项目.

我想为图像绘制直方图.我从图像中得到红色,但我不知道如何将其绘制为直方图,所以我需要你的帮助.

这是我的代码:

class MainClass
{

    public static void Main(string[] args)
    {
        Bitmap bmp = new Bitmap("F://DSC_0242.jpg");
        int[] histogram_r = new int[255];
        int max = 0;

        for (int i = 0; i < bmp.Width; i++)
        {
            for (int j = 0; j < bmp.Height; j++)
            {
                histogram_r[bmp.GetPixel(i,j).R]++;
                if (max < histogram_r[bmp.GetPixel(i,j).R])
                    max = histogram_r[bmp.GetPixel(i,j).R];
            }
        }

        Bitmap img = new Bitmap(256, max + 10);
        Point[] points = new Point[256];

        for (int i = 0; i < histogram_r.Length; i++)
        {
            points[i] = new Point(i, img.Height-(histogram_r.Length/100));

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

daz*_*sed 6

首先,你需要声明你的直方图数组大小为256而不是255.我在下面的代码中进行了一些通用的清理,但与你的问题相关的事情如下......

  • 您可以使用Graphics类直接写入输出图像
  • 要确定直方图中每条线的高度,首先要确定您要处理的最大值的百分比.然后绘制一条线,该线是所需输出大小的百分比.
  • 下面的代码创建的输出图像比histHeight中指定的图像高10个像素.直方图中的每一行从底部开始5个像素,在顶部和底部给出5像素边框.

我使用了Win7中包含的一个示例文件,因此您必须将其更改为您的图片.我也将直方图输出到临时文件夹,所以你也需要做任何你需要的东西.

        private void Test()
        {
            Bitmap bmp = new Bitmap(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");
            int[] histogram_r = new int[256];
            float max = 0;

            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    int redValue = bmp.GetPixel(i, j).R;
                    histogram_r[redValue]++;
                    if (max < histogram_r[redValue])
                        max = histogram_r[redValue];
                }
            }

            int histHeight = 128;
            Bitmap img = new Bitmap(256, histHeight + 10);
            using (Graphics g = Graphics.FromImage(img))
            {
                for (int i = 0; i < histogram_r.Length; i++)
                {
                    float pct = histogram_r[i] / max;   // What percentage of the max is this value?
                    g.DrawLine(Pens.Black,
                        new Point(i, img.Height - 5),
                        new Point(i, img.Height - 5 - (int)(pct * histHeight))  // Use that percentage of the height
                        );
                }
            }
            img.Save(@"c:\temp\test.jpg");
        }
     }
 }
Run Code Online (Sandbox Code Playgroud)