3

我需要一些帮助来优化我的 CCL 算法实现。我用它来检测图像上的黑色区域。在 2000x2000 上需要 11 秒,这差不多。我需要将运行时间减少到可能达到的最低值。另外,我很高兴知道是否有任何其他算法可以让你做同样的事情,但比这个更快。所以这是我的代码:

    //The method returns a dictionary, where the key is the label
    //and the list contains all the pixels with that label
    public Dictionary<short, LinkedList<Point>> ProcessCCL()
    {
        Color backgroundColor = this.image.Palette.Entries[1];
        //Matrix to store pixels' labels
        short[,] labels = new short[this.image.Width, this.image.Height];
        //I particulary don't like how I store the label equality table
        //But I don't know how else can I store it
        //I use LinkedList to add and remove items faster
        Dictionary<short, LinkedList<short>> equalityTable = new Dictionary<short, LinkedList<short>>();
        //Current label
        short currentKey = 1;
        for (int x = 1; x < this.bitmap.Width; x++)
        {
            for (int y = 1; y < this.bitmap.Height; y++)
            {
                if (!GetPixelColor(x, y).Equals(backgroundColor))
                {
                    //Minumum label of the neighbours' labels
                    short label = Math.Min(labels[x - 1, y], labels[x, y - 1]);
                    //If there are no neighbours
                    if (label == 0)
                    {
                        //Create a new unique label
                        labels[x, y] = currentKey;
                        equalityTable.Add(currentKey, new LinkedList<short>());
                        equalityTable[currentKey].AddFirst(currentKey);
                        currentKey++;
                    }
                    else
                    {
                        labels[x, y] = label;
                        short west = labels[x - 1, y], north = labels[x, y - 1];
                        //A little trick:
                        //Because of those "ifs" the lowest label value
                        //will always be the first in the list
                        //but I'm afraid that because of them
                        //the running time also increases
                        if (!equalityTable[label].Contains(west))
                            if (west < equalityTable[label].First.Value)
                                equalityTable[label].AddFirst(west);
                        if (!equalityTable[label].Contains(north))
                            if (north < equalityTable[label].First.Value)
                                equalityTable[label].AddFirst(north);
                    }
                }
            }
        }
        //This dictionary will be returned as the result
        //I'm not proud of using dictionary here too, I guess there 
        //is a better way to store the result
        Dictionary<short, LinkedList<Point>> result = new Dictionary<short, LinkedList<Point>>();
        //I define the variable outside the loops in order 
        //to reuse the memory address
        short cellValue;
        for (int x = 0; x < this.bitmap.Width; x++)
        {
            for (int y = 0; y < this.bitmap.Height; y++)
            {
                cellValue = labels[x, y];
                //If the pixel is not a background
                if (cellValue != 0)
                {
                    //Take the minimum value from the label equality table 
                    short value = equalityTable[cellValue].First.Value;
                    //I'd like to get rid of these lines
                    if (!result.ContainsKey(value))
                        result.Add(value, new LinkedList<Point>());
                    result[value].AddLast(new Point(x, y));
                }
            }
        }
        return result;
    }

提前致谢!

4

3 回答 3

1

您可以将图片拆分为多个子图片并并行处理它们,然后合并结果。1 pass:4 个任务,每个任务处理一个 1000x1000 的子图片 2 pass:2 个任务,每个任务处理来自 pass 1 的 2 个子图片 3 pass:1 个任务,处理 pass 2 的结果

对于 C#,我推荐Task Parallel Library (TPL),它允许轻松定义相互依赖和等待的任务。以下代码项目文章为您提供了对 TPL 的基本介绍:通过 C# 的任务并行化基础知识

于 2012-08-28T19:31:13.673 回答
1

我将一次处理一条扫描线,跟踪每次黑色像素运行的开始和结束。

然后,我会在每条扫描线上将其与前一行的运行进行比较。如果当前行上的运行与前一行上的运行不重叠,则它表示一个新的 blob。如果上一行的运行与当前行的运行重叠,它将获得与前一行相同的 blob 标签。等等等等。你明白了。

我会尽量不使用字典等。根据我的经验,随机停止程序表明这些事情可能会使编程变得越来越容易,但由于new-ing 会导致严重的性能成本。

于 2012-08-28T20:32:23.423 回答
1

问题在于GetPixelColor(x, y),访问图像数据需要很长时间。Set/GetPixel 函数在 C# 中非常慢,所以如果你需要大量使用它们,你应该使用 Bitmap.lockBits 来代替。

private void ProcessUsingLockbits(Bitmap ProcessedBitmap)
{
    BitmapData bitmapData = ProcessedBitmap.LockBits(new Rectangle(0, 0, ProcessedBitmap.Width, ProcessedBitmap.Height), ImageLockMode.ReadWrite, ProcessedBitmap.PixelFormat);
    int BytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(ProcessedBitmap.PixelFormat) / 8;
    int ByteCount = bitmapData.Stride * ProcessedBitmap.Height;
    byte[] Pixels = new byte[ByteCount];
    IntPtr PtrFirstPixel = bitmapData.Scan0;
    Marshal.Copy(PtrFirstPixel, Pixels, 0, Pixels.Length);
    int HeightInPixels = bitmapData.Height;
    int WidthInBytes = bitmapData.Width * BytesPerPixel;
    for (int y = 0; y < HeightInPixels; y++)
    {
        int CurrentLine = y * bitmapData.Stride;
        for (int x = 0; x < WidthInBytes; x = x + BytesPerPixel)
        {
            int OldBlue = Pixels[CurrentLine + x];
            int OldGreen = Pixels[CurrentLine + x + 1];
            int OldRed = Pixels[CurrentLine + x + 2];
            // Transform blue and clip to 255:
            Pixels[CurrentLine + x] = (byte)((OldBlue + BlueMagnitudeToAdd > 255) ? 255 : OldBlue + BlueMagnitudeToAdd);
            // Transform green and clip to 255:
            Pixels[CurrentLine + x + 1] = (byte)((OldGreen + GreenMagnitudeToAdd > 255) ? 255 : OldGreen + GreenMagnitudeToAdd);
            // Transform red and clip to 255:
            Pixels[CurrentLine + x + 2] = (byte)((OldRed + RedMagnitudeToAdd > 255) ? 255 : OldRed + RedMagnitudeToAdd);
        }
    }
    // Copy modified bytes back:
    Marshal.Copy(Pixels, 0, PtrFirstPixel, Pixels.Length);
    ProcessedBitmap.UnlockBits(bitmapData);
}

这是访问像素数据的基本代码。

我做了一个函数来把它转换成一个二维矩阵,它更容易操作(但慢一点)

    private void bitmap_to_matrix()
    {
        unsafe
        {
            bitmapData = ProcessedBitmap.LockBits(new Rectangle(0, 0, ProcessedBitmap.Width, ProcessedBitmap.Height), ImageLockMode.ReadWrite, ProcessedBitmap.PixelFormat);
            int BytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(ProcessedBitmap.PixelFormat) / 8;
            int HeightInPixels = ProcessedBitmap.Height;
            int WidthInPixels = ProcessedBitmap.Width;
            int WidthInBytes = ProcessedBitmap.Width * BytesPerPixel;
            byte* PtrFirstPixel = (byte*)bitmapData.Scan0;

            Parallel.For(0, HeightInPixels, y =>
            {
                byte* CurrentLine = PtrFirstPixel + (y * bitmapData.Stride);

                for (int x = 0; x < WidthInBytes; x = x + BytesPerPixel)
                {
                    // Conversion in grey level                       
                    double rst = CurrentLine[x] * 0.0721 + CurrentLine[x + 1] * 0.7154 + CurrentLine[x + 2] * 0.2125;

                    // Fill the grey matix
                    TG[x / 3, y] = (int)rst;
                }
            });               
        }
    }

以及代码所在的网站 “高性能SystemDrawingBitmap”

感谢作者的出色工作!希望这会有所帮助!

于 2015-02-12T18:36:22.597 回答