我怎样才能加快这个直方图课程的速度?

xof*_*ofz 2 c# performance image-processing histogram

这应该计算8位灰度图像的直方图.使用1024x770测试位图,CreateTime最终在890ms左右.我怎样才能更快地完成这个(方式,方式)?

编辑:我应该提到,这实际上并没有计算直方图,它只从位图中获取值.所以我真的应该问,从8位灰度图像中检索所有像素值的最快方法是什么?

public class Histogram {

    private static int[,] values;

    public Histogram(Bitmap b) {
        var sw = Stopwatch.StartNew();
        values = new int[b.Width, b.Height];

        for (int w = 0; w < b.Width; ++w) {
            for (int h = 0; h < b.Height; ++h) {
                values[w, h] = b.GetPixel(w, h).R;
            }
        }

        sw.Stop();
        CreateTime = (sw.ElapsedTicks /
            (double)Stopwatch.Frequency) * 1000;
    }

    public double CreateTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

And*_*res 5

基本直方图算法类似于:

int[] hist = new hist[256];
//at this point dont forget to initialize your vector with 0s.

for(int i = 0; i < height; ++i)
{
   for(int j = 0 ; j < widthl ++j)
   {
        hist[ image[i,j] ]++;
   }
}
Run Code Online (Sandbox Code Playgroud)

该算法总结了您拥有的值为0的像素数,具有值= 1的多少像素,依此类推.基本思想是使用像素值作为您将计算的直方图位置的索引.

我有一个版本的这个算法使用非托管代码为C#编写(这很快)我不知道是否比你更快但随意采取它并测试,这里是代码:

    public void Histogram(double[] histogram, Rectangle roi)
    {
        BitmapData data = Util.SetImageToProcess(image, roi);

        if (image.PixelFormat != PixelFormat.Format8bppIndexed)
            return;

        if (histogram.Length < Util.GrayLevels)
            return;

        histogram.Initialize();
        int width = data.Width;
        int height = data.Height;
        int offset = data.Stride - width;

        unsafe
        {
            byte* ptr = (byte*)data.Scan0;

            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x, ++ptr)
                    histogram[ptr[0]]++;

                ptr += offset;
            }
        }
        image.UnlockBits(data);         
    }

    static public BitmapData SetImageToProcess(Bitmap image, Rectangle roi)
    {
        if (image != null)
            return image.LockBits(
                roi,
                ImageLockMode.ReadWrite,
                image.PixelFormat);

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

我希望我能帮助你.