private void btnGaussSmooth_Click(object sender, EventArgs e)
        {
            Data.clear();
            double sigma    = double.Parse(txtGaussSigma.Text);
            int    maskSize = (int)nudMaskSize.Value;
            var    watch    = System.Diagnostics.Stopwatch.StartNew();

            ConstructGraph.Diffcolors(ImageMatrix);
            MST.getMST();
            //ConstructGraph.CalcDist();
            var k = ExtractClusters.getKK();

            txtGaussSigma.Text = k.ToString();
            ExtractClusters.extractClusters(maskSize);
            ExtractClusters.getClustersColors();
            // outPut
            watch.Stop();
            long elapsedMs = watch.ElapsedMilliseconds;

            timeTxt.Text       = (elapsedMs / 1000).ToString();
            MSTSum.Text        = Math.Round(Data.sum, 3).ToString();
            TimeM.Text         = (elapsedMs % 1000).ToString();
            txtDiffColors.Text = Data.colorsNum.ToString();
            ImageOperations.DisplayImage(ColorMapping.NewColors(ImageMatrix), pictureBox2);
        }
        }//Total_complexity = E(N^2) --> N = width or height

        public static RGBPixel[,] ReduceImageColor(RGBPixel[,] Image_matrix, int Desireable_NumberOfColor)
        {
            MST mst = MST_Weight(Image_matrix);

            RGBPixelD[,,] pallete = Extract_color_palette(mst, Desireable_NumberOfColor);
            Quntization(Image_matrix, pallete);
            return(Image_matrix);
        }
Beispiel #3
0
        private void Operations()
        {
            numberofcolor.Text = ImageOperations.Get_Number_of_color(ImageMatrix).ToString();
            MST mst = ImageOperations.MST_Weight(ImageMatrix);

            MST_Sum.Text          = mst.Weight.ToString();
            RGBPixelD[,,] pallete = ImageOperations.Extract_color_palette(mst, Convert.ToInt32(clusterTxT.Text));
            ImageOperations.Quntization(ImageMatrix, pallete);
            ImageOperations.DisplayImage(ImageMatrix, pictureBox2);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            int             K = Convert.ToInt32(textBox1.Text.ToString());
            distinct_colors c = new distinct_colors();

            c.get_colors(ImageMatrix);
            MessageBox.Show(c.count.ToString());
            MST tree = new MST(c.count, c.colors);

            tree.MST_Construct();
            tree.total_cost();
            double d = tree.cost;

            MessageBox.Show(d.ToString());
            Cluster cc = new Cluster(tree.L, c.colors, K);

            cc.function();
            cc.Color_Pallette();
            cc.Quantize_the_image(ImageMatrix);
            //----------------------------------------------------------
            double sigma    = double.Parse(txtGaussSigma.Text);
            int    maskSize = (int)nudMaskSize.Value;

            //ImageMatrix = ImageOperations.GaussianFilter1D(ImageMatrix, maskSize, sigma);

            ImageOperations.DisplayImage(ImageMatrix, pictureBox2);
            //----------------------------------------------------------
            //-------------------------------------------------
            var fd = new SaveFileDialog();

            fd.Filter       = "Bmp(*.BMP;)|*.BMP;| Jpg(*Jpg)|*.jpg";
            fd.AddExtension = true;
            if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                switch (System.IO.Path.GetExtension(fd.FileName).ToUpper())
                {
                case ".BMP":
                    pictureBox2.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case ".JPG":
                    pictureBox2.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case ".PNG":
                    pictureBox2.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Png);
                    break;

                default:
                    break;
                }
            }
            //-------------------------------------------------
        }
Beispiel #5
0
        public static void Clustering_BFS(int s, ref int Cluster_num, ref MST m)
        {
            int Red = 0, Green = 0, Blue = 0;

            m.Cluster.Add(new List <int>());  //new cluster for New Node

            Queue <int> q = new Queue <int>();

            q.Enqueue(s);
            while (q.Count != 0)
            {
                int p = q.Dequeue();
                if (m.Graph[m.li[p].red, m.li[p].green, m.li[p].blue] != null) // if he not Visited and Have a childs
                {
                    if (!m.check[p])
                    {
                        m.check[p] = true;             // Just Marked Him as true
                        m.Cluster[Cluster_num].Add(p); // add him in cluster
                        Red   += m.li[p].red;
                        Green += m.li[p].green;
                        Blue  += m.li[p].blue;
                    }
                    for (int i = 0; i < m.Graph[m.li[p].red, m.li[p].green, m.li[p].blue].Count; i++) // Loop to push his childs
                    {
                        if (!m.check[m.Graph[m.li[p].red, m.li[p].green, m.li[p].blue][i]])
                        {
                            q.Enqueue(m.Graph[m.li[p].red, m.li[p].green, m.li[p].blue][i]);
                        }
                    }
                }
                else if (!m.check[p])  // Not Visited and no childs
                {
                    m.check[p] = true;
                    m.Cluster[Cluster_num].Add(p);
                    Red   += m.li[p].red;
                    Green += m.li[p].green;
                    Blue  += m.li[p].blue;
                }
            }
            Red   = Red / m.Cluster[Cluster_num].Count;
            Green = Green / m.Cluster[Cluster_num].Count;
            Blue  = Blue / m.Cluster[Cluster_num].Count;

            for (int i = 0; i < m.Cluster[Cluster_num].Count; i++)
            {
                m.RGB[m.li[m.Cluster[Cluster_num][i]].red, m.li[m.Cluster[Cluster_num][i]].green, m.li[m.Cluster[Cluster_num][i]].blue]
                    = new RGBPixel(Red, Green, Blue);
            }
            Cluster_num++;
        }
        private void calculate_std_mean()
        {
            double segma = 0;

            tree = new MST(colors.Count, colors);
            tree.MST_Construct();
            MSTree = tree.L;
            tree.total_cost();
            total = tree.cost;
            mean  = total / (MSTree.Count);
            for (int i = 1; i < MSTree.Count; i++)
            {
                segma += (MSTree[i].weight * MSTree[i].weight) - (mean * mean);
            }
            stddiv = Math.Sqrt(segma / MSTree.Count);
            clnum2 = 0;
        }
Beispiel #7
0
        static int getK(MST mst)
        {
            int    clusters      = 1;
            double size          = mst.getEdgesHeap().getSize();
            int    distictcolors = (int)size;
            double cost          = mst.totalCost;
            double brevSTDev     = 0;
            double curSTDev      = mst.STDev;
            double Mean          = mst.Mean;

            Edge[] edges = mst.getEdgesHeap().Sortedges();
            int    j = edges.Length - 1;
            int    i = 0;
            double curSTDevRed = 0, brevSTDevRed = 0;

            while (Math.Abs(curSTDev - brevSTDev) > 0.0001)
            {
                brevSTDev = curSTDev;
                if (Math.Abs(edges[i].weight - Mean) > Math.Abs(edges[j].weight - Mean))
                {
                    cost -= edges[i].weight;
                    i++;
                }
                else
                {
                    cost -= edges[j].weight;
                    j--;
                }
                size--;
                Mean = cost / size;
                double sum = 0;
                for (int k = i; k <= j; k++)
                {
                    sum += Math.Abs(edges[k].weight - Mean) * Math.Abs(edges[k].weight - Mean);
                }
                curSTDev = Math.Sqrt(sum / Convert.ToDouble(size - 1));
                // curSTDevRed = Math.Abs(curSTDev - brevSTDev);
                clusters++;
            }
            if (distictcolors > clusters)
            {
                return(clusters);
            }
            return(distictcolors);
        }
        private void btnDisplay_Click(object sender, EventArgs e)
        {
            var stopwatch      = Stopwatch.StartNew();
            int imageWidth     = ImageOperations.GetWidth(ImageMatrix);  //O(1)
            int imageHeight    = ImageOperations.GetHeight(ImageMatrix); //O(1)
            int maxDistinctNum = 60000;                                  //Maximum number of distinic in the given test cases //O(1)

            //Dictionary that contains MinSpanningTree
            Dictionary <int, KeyValuePair <int, double> > MSTree = new Dictionary <int, KeyValuePair <int, double> >(maxDistinctNum);//O(1)

            //Helper Dictionary for keeping struct values concatenated as integer (Key) and the struct as Value
            Dictionary <int, RGBPixel> distinctHelper = new Dictionary <int, RGBPixel>(maxDistinctNum);                        //O(1)
            //Checks visited nodes in minimum spanning tree
            Dictionary <int, bool> visited = new Dictionary <int, bool>(maxDistinctNum);                                       //O(1)
            int color = 0;                                                                                                     //O(1)
            //Any node that we start from the Minimum Spanning
            KeyValuePair <int, KeyValuePair <int, double> > minVertix = new KeyValuePair <int, KeyValuePair <int, double> >(); //O(1)
            //O(D^2)
            int noDistinctColors = MST.FindDistinctColors(ImageMatrix, ref MSTree, ref distinctHelper, ref visited, ref color, ref minVertix);
            //List that contains mimimum spanning edges sorted
            List <KeyValuePair <double, int> > edges = new List <KeyValuePair <double, int> >(maxDistinctNum);              //O(1)
            double MST_Sum = MST.FindMinimumSpanningTree(ref MSTree, distinctHelper, visited, color, minVertix, ref edges); //O(D^2)

            int k = int.Parse(txtGetK.Text);                                                                                //O(N)
            //Dictionary carries each original color as key and representative color of each cluster as value
            Dictionary <int, RGBPixel> represntativeColor = new Dictionary <int, RGBPixel>(maxDistinctNum);
            //O(K+D) = O(D)
            Dictionary <int, List <int> > clusteredGraph = Clustering.ProduceKClusters(k, edges, MSTree, maxDistinctNum, visited);

            //O(E+V) =O(V) = O(D)
            Clustering.DFS(clusteredGraph, visited, maxDistinctNum, k, ref represntativeColor, distinctHelper);
            //O(N^2)
            MST.Coloring(ref ImageMatrix, represntativeColor);

            ImageOperations.DisplayImage(ImageMatrix, pictureBox2);
            stopwatch.Stop();
            double Miliseconds = (stopwatch.Elapsed.TotalMilliseconds);

            txtMili.Text = Miliseconds.ToString(); //O(1)
            double Seconds = (stopwatch.Elapsed.TotalSeconds);

            txtSec.Text      = Seconds.ToString();          //O(1)
            txtDistinct.Text = noDistinctColors.ToString(); //O(1)
            txtMST.Text      = MST_Sum.ToString();          //O(1)
        }
Beispiel #9
0
        /// <summary>
        /// Apply Gaussian smoothing filter to enhance the edge detection
        /// </summary>
        /// <param name="ImageMatrix">Colored image matrix</param>
        /// <param name="filterSize">Gaussian mask size</param>
        /// <param name="sigma">Gaussian sigma</param>
        /// <returns>smoothed color image</returns>
        public static RGBPixel[,] GaussianFilter1D(RGBPixel[,] ImageMatrix, int filterSize, double sigma)
        {
            /////hereeeeeeeeeeeeeee
            List <RGBPixelD> listRGP = findDistinctColors(ImageMatrix); //O(N^2)
            MST mst = new MST(listRGP);

            mst.prim(); //O(E log V)
            cLustring = new CLustring(mst.getEdgesHeap(), listRGP, mst.getMSTList());
            ///AutoClustring  autoClustring =new AutoClustring(listRGP);


            Console.WriteLine();
            cLustring.buildCustring(getK(mst));
            // CLustring cLustring = new CLustring(autoClustring.getListOfColors(), autoClustring.getMSTDictionary());
            // cLustring.buildAutoCustring();
            ///return replaceNewColors(autoClustring.autoClustring(filterSize, listRGP, listRGP.Count), ImageMatrix);
            //return replaceNewColors(cLustring.getMatrix(), ImageMatrix);

            return(ImageMatrix);
        }
Beispiel #10
0
        public static RGBPixelD[,,] Extract_color_palette(MST mst, int Num_of_clusters)
        {
            RGBPixelD[ , , ] Color_palette = new RGBPixelD[256, 256, 256]; //O(1)
            bool[]         v   = new bool[mst.parent.Length];              //O(1)
            List <node2>[] adj = new List <node2> [mst.parent.Length];     //O(1)

            ///<summary>
            ///make cluster of a tree
            /// </summary>
            for (int l = 0; l < Num_of_clusters - 1; l++) //E(K)
            {
                int    i     = 0;                         //O(1)
                int    index = 0;                         //O(1)
                double W     = double.MinValue;           //O(1)
                foreach (Node color in mst.tree)          //E(D)
                {
                    if (W < color.weight)                 //O(1)
                    {
                        W     = color.weight;             //O(1)
                        index = i;                        //O(1)
                    }
                    i++;                                  //O(1)
                }
                //total loop --> O(D) --> D = number of distinct colors

                mst.tree.RemoveAt(index);//O(D)
            }
            //total loop Order --> E(D*K)

            ///<summary>
            ///convert clustered tree from list representation to adjacent list representation
            /// </summary>
            for (int r = 0; r < mst.parent.Length; r++)
            {
                v[r] = false;//O(1)
            }
            //total loop --> O(D) --> D = number of distinct colors

            for (int i = 0; i < mst.parent.Length; i++) //O(D) --> D = number of distinct colors
            {
                adj[i] = new List <node2>();            //O(1)
            }
            //total loop --> O(D) --> D = number of distinct colors

            int k = 0;                       //O(1)

            foreach (Node color in mst.tree) //E(D)
            {
                if (k == 0)                  //O(1)
                {
                    k++;                     //O(1)
                    continue;                //O(1)
                }
                node2 n  = new node2();      //O(1)
                node2 n2 = new node2();      //O(1)
                n.weight  = color.weight;    //O(1)
                n.to      = color.to;        //O(1)
                n2.weight = color.weight;    //O(1)
                n2.to     = color.index;     //O(1)
                adj[color.index].Add(n);     //O(1)
                adj[color.to].Add(n2);       //O(1)
            }
            ///<summary>
            ///for loop to catch each root of the cluster and move forward
            /// to all his adjacent and make a pallete with new color
            /// </summary>
            for (int r = 0; r < mst.parent.Length; r++)                      // Exact(D) --> total number of disinct colors
            {
                if (v[r] == false)                                           //O(1)
                {
                    avgcolor_BFS(mst.index_color, r, Color_palette, v, adj); //Exact(E + D)
                }
            }
            //total for loop ---> Exact (K * D) -->  K = number of clusters, D = number of distinct colors
            //BFS was called , K = number of clusters

            return(Color_palette);
        }
Beispiel #11
0
        public static MST MST_Weight(RGBPixel[,] ImageMatrix)
        {
            long            size;                                                //O(1)
            List <RGBPixel> color_list  = List_of_Dstinected_Color(ImageMatrix); //O(1)
            List <Color>    index_color = list_of_indexed_color(color_list);     //O(1)
            List <Node>     tree        = new List <Node>();                     //Exact(1)
            heap            heap        = new heap();                            //O(1)

            size = color_list.Count;                                             //O(1)
            bool[]   k = new bool[size];                                         //O(1)
            int[]    p = new int[size];                                          //O(1)
            double[] d = new double[size];                                       //O(1)

            for (int i = 1; i < size; i++)                                       //O(N) --> N = number of distinct colors
            {
                k[i] = false;                                                    //O(1)
                d[i] = double.MaxValue;                                          //O(1)
                p[i] = -1;                                                       //O(1)
            }
            //total loop -> O(N) --> N = number of distinct colors
            p[0] = -1;               //O(1)
            d[0] = 0;                //O(1)
            //node
            Node node0 = new Node(); //O(1)

            node0.index  = -1;       //O(1)
            node0.weight = 0;        //O(1)
            node0.to     = 0;        //O(1)
            heap.insert(node0);      //O(log(V))

            while (!heap.empty())    //O(V)
            {
                //node
                Node node  = heap.extract_Min();                                                           //O(Log(V))
                int  index = node.to;                                                                      //O(1)
                if (k[index] == true)                                                                      //O(1)
                {
                    continue;                                                                              //O(1)
                }
                k[index] = true;                                                                           //O(1)
                RGBPixel color1 = index_color[index].val;                                                  //O(1)
                int      i      = 0;                                                                       //O(1)
                tree.Add(node);                                                                            //O(1)
                foreach (var color2 in color_list)                                                         //O(V) --> V = Number of distinct colors
                {
                    if (i != index)                                                                        //O(1)
                    {
                        double Red_Diff   = (color1.red - color2.red) * (color1.red - color2.red);         //O(1)
                        double Green_Diff = (color1.green - color2.green) * (color1.green - color2.green); //O(1)
                        double Blue_Diff  = (color1.blue - color2.blue) * (color1.blue - color2.blue);     //O(1)
                        double Total_Diff = Math.Sqrt(Red_Diff + Green_Diff + Blue_Diff);                  //O(1)

                        if (k[i] == false && Total_Diff < d[i])                                            //O(1)
                        {
                            d[i] = Total_Diff;                                                             //O(1)
                            p[i] = index;                                                                  //O(1)
                            Node node1 = new Node();                                                       //O(1)
                            node1.weight = Total_Diff;                                                     //O(1)
                            node1.index  = index;                                                          //O(1)
                            node1.to     = i;                                                              //O(1)
                            heap.insert(node1);                                                            //O(Log(V))
                        }
                    }
                    i++;
                }
                //total loop --> O(V * Log(V))
            }
            double weight = 0;             //O(1)

            for (int i = 0; i < size; i++) //O(N) --> N = number of distinct colors
            {
                weight += d[i];            //O(1)
            }
            //total loop --> O(N)
            MST mST = new MST(weight, tree, p, index_color); //O(1)

            return(mST);                                     //O(1)

            //total function's complexity ---> O(E * log V)
        }
Beispiel #12
0
        /// <summary>
        /// Apply Gaussian smoothing filter to enhance the edge detection
        /// </summary>
        /// <param name="ImageMatrix">Colored image matrix</param>
        /// <param name="filterSize">Gaussian mask size</param>
        /// <param name="sigma">Gaussian sigma</param>
        /// <returns>smoothed color image</returns>
        public static RGBPixel[,] GaussianFilter1D(RGBPixel[,] ImageMatrix, ref List <RGBPixel> li, ref int sigma, ref MST m)
        {
            int Graph_constrauction = 0;             // Cnt TO COnstrauct garph
            int Cluster_num         = 0;

            m.Cluster = new List <List <int> >(sigma);
            m.path    = m.path.OrderBy(Edge => Edge.cost).ToList();  // Sort Quick Sort NlogN
            m.check   = Enumerable.Repeat(false, li.Count).ToList(); // Re Use to Check if Take it in Clustering or Not
            m.Graph   = new List <int> [256, 256, 256];

            foreach (Edge i in m.path)
            {
                if (Graph_constrauction < m.path.Count - (sigma - 1))
                {
                    if (m.Graph[li[i.from].red, li[i.from].green, li[i.from].blue] == null)
                    {
                        m.Graph[li[i.from].red, li[i.from].green, li[i.from].blue] = new List <int>();
                    }
                    if (m.Graph[li[i.to].red, li[i.to].green, li[i.to].blue] == null)
                    {
                        m.Graph[li[i.to].red, li[i.to].green, li[i.to].blue] = new List <int>();
                    }

                    m.Graph[li[i.from].red, li[i.from].green, li[i.from].blue].Add(i.to);
                    m.Graph[li[i.to].red, li[i.to].green, li[i.to].blue].Add(i.from);
                    Graph_constrauction++;
                }
                else
                {
                    if (!m.check[i.from])
                    {
                        Clustering_BFS(i.from, ref Cluster_num, ref m);
                    }
                    if (!m.check[i.to])
                    {
                        Clustering_BFS(i.to, ref Cluster_num, ref m);
                    }
                }
            }
            return(ImageMatrix);
        }
 private void mailestoneOne()
 {
     numberofcolor.Text = ImageOperations.Get_Number_of_color(ImageMatrix).ToString();
     mst          = ImageOperations.MST_Weight(ImageMatrix);
     MST_Sum.Text = mst.Weight.ToString();
 }