Monday, 20 November 2017

Connected Component Labeling Algorithm

using System;
using System.Collections.Generic;
using System.Text;

namespace ConnectedComponentLabeling
{
    internal class Label
    {
        #region Public Properties

        public int Name { get; set; }

        public Label Root { get; set; }

        public int Rank { get; set; }

        #endregion

        #region Constructor

        public Label(int Name)
        {
            this.Name = Name;
            this.Root = this;
            this.Rank = 0;
        }

        #endregion

        #region Public Methods

        internal Label GetRoot()
        {
            if (this.Root != this)
            {
                this.Root = this.Root.GetRoot();//Compact tree
            }

            return this.Root;
        }

        internal void Join(Label root2)
        {
            if (root2.Rank < this.Rank)//is the rank of Root2 less than that of Root1 ?
            {
                root2.Root = this;//yes! then Root1 is the parent of Root2 (since it has the higher rank)
            }
            else //rank of Root2 is greater than or equal to that of Root1
            {
                this.Root = root2;//make Root2 the parent

                if (this.Rank == root2.Rank)//both ranks are equal ?
                {
                    root2.Rank++;//increment Root2, we need to reach a single root for the whole tree
                }
            }
        }

        #endregion
    }
}

public interface IConnectedComponentLabeling
{
    IDictionary<int, Bitmap> Process(Bitmap input);
}

IConnectedComponentLabeling target = new CCL();
Bitmap input = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + @"\Test.bmp");

var images= target.Process(input);
foreach (var image in images)
{
    image.Value.Save(savePath + image.Key + ".bmp");
}

private Dictionary<int, List<Pixel>> AggregatePatterns(Dictionary<int,
          Label> allLabels, int width, int height)
{
    var patterns = new Dictionary<int, List<Pixel>>();

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            int patternNumber = _board[j, i];

            if (patternNumber != 0)
            {
                patternNumber = allLabels[patternNumber].GetRoot().Name;

                if (!patterns.ContainsKey(patternNumber))
                {
                    patterns.Add(patternNumber, new List<Pixel>());
                }

                patterns[patternNumber].Add(new Pixel(new Point(j, i), Color.Black));
            }
        }
    }

    return patterns;
}

No comments:

Post a Comment