Exemplo n.º 1
0
        public void TestHugeGraph()
        {
            IGraph <int> graph      = ReadGraphFromFile("./graphs/Graph_ganzganzgross.txt");
            int          components = ConnectedComponents.Count(graph);

            Assert.AreEqual(306, components);
        }
        public ContentUserControlViewModel()
        {
            FilePath      = string.Empty;
            BrowseCommand = new DelegateCommand(() =>
            {
                OpenFileDialog dialog = new OpenFileDialog()
                {
                    Multiselect     = false,
                    CheckPathExists = true,
                    CheckFileExists = true,
                    Filter          = "画像ファイル|*.bmp;*.jpg;*.png",
                };
                bool?ret = dialog.ShowDialog();
                if (ret.HasValue && ret.Value)
                {
                    FilePath      = dialog.FileName;
                    Mat original  = Cv2.ImRead(dialog.FileName);
                    OriginalImage = ToBitmapSource(BitmapConverter.ToBitmap(original));

                    Mat grayscale = new Mat();
                    Cv2.CvtColor(original, grayscale, ColorConversionCodes.BGR2GRAY);
                    Mat binary = new Mat();
                    Cv2.Threshold(grayscale, binary, 0.0, 255.0, ThresholdTypes.Binary | ThresholdTypes.Otsu);
                    Mat labels = new Mat();
                    ConnectedComponents components = Cv2.ConnectedComponentsEx(binary);
                    Mat segmented = new Mat();
                    components.RenderBlobs(segmented);
                    SegmentedImage = ToBitmapSource(BitmapConverter.ToBitmap(segmented));
                }
            });
            System.Diagnostics.Debug.Print(Cv2.GetVersionString());
        }
Exemplo n.º 3
0
        public static int Labling(this WriteableBitmap src)
        {
            using (Mat mat = new Mat(src.PixelHeight, src.PixelWidth, MatType.CV_8UC3))
            {
                src.ToMat(mat);

                Mat gray = mat.CvtColor(ColorConversionCodes.BGR2GRAY);

                //Cv2.NamedWindow("image", WindowMode.Normal);
                //Cv2.ImShow("image", mat);
                Mat binary = gray.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);

                //Cv2.NamedWindow("image", WindowMode.Normal);
                //Cv2.ImShow("image", binary);
                //Cv2.WaitKey();
                //Cv2.DestroyWindow("image");
                ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);

                int c = 0;
                foreach (var i in cc.Blobs)
                {
                    c += i.Area > 3 ? 1 : 0;
                }


                return(c);
            }
        }
        public void Correctly_Returns_ConnectedComponents()
        {
            ConnectedComponents search = new ConnectedComponents(GraphMothers.ZeroBasedHandDrawnOnPage167);
            var count = search.FindConnectedComponents();

            Assert.AreEqual(count, 2);
        }
Exemplo n.º 5
0
        public void GraphConnectedComponentsEmpty()
        {
            var graph = new UndirectedGraph();
            var cc    = new ConnectedComponents(graph);

            Assert.AreEqual(0, cc.AmountOfComponents);
        }
        public void Test_Id()
        {
            ConnectedComponents cc = this.CreateCC();

            Assert.Equal(0, cc.Id(3));
            Assert.Equal(1, cc.Id(5));
        }
Exemplo n.º 7
0
        /// <summary>
        /// imageの白部分の面積がminArea以上のものだけ反映した画像を返す
        /// </summary>
        public static Bitmap GetImageOmitMinimumNoize(Bitmap image, int minArea)
        {
            var mat = Cv2.Split(image.ToMat())[0];

            ConnectedComponents cc = Cv2.ConnectedComponentsEx(mat);
            //var maxBlob = cc.GetLargestBlob();
            //var filtered = new Mat();
            //cc.FilterByBlob(mat, filtered, maxBlob);
            //Cv2.ImShow("max", filtered);

            List <ConnectedComponents.Blob> blobs = new List <ConnectedComponents.Blob>();

            for (int i = 0; i < cc.LabelCount; i++)
            {
                int area = cc.Blobs[i].Area;
                if (area >= minArea)
                {
                    blobs.Add(cc.Blobs[i]);
                }
            }

            var filtered = new Mat();

            cc.FilterByBlobs(mat, filtered, blobs);
            return(new Bitmap(filtered.ToBitmap()));
        }
Exemplo n.º 8
0
        public void TestMediumGraph()
        {
            IGraph <int> graph      = ReadGraphFromFile("./graphs/Graph3.txt");
            int          components = ConnectedComponents.Count(graph);

            Assert.AreEqual(4, components);
        }
Exemplo n.º 9
0
        public void ConnectedComponents_Test()
        {
            ConnectedComponents CC = new ConnectedComponents(basicGraph);

            Assert.AreEqual(2, CC.Count());
            Assert.AreEqual(0, CC.ID(0));
            Assert.AreEqual(1, CC.ID(8));
        }
Exemplo n.º 10
0
        private static void Blob()
        {
            Mat src       = new Mat("data/shapes.png", ImreadModes.Color);
            Mat gray      = src.CvtColor(ColorConversionCodes.BGR2GRAY);
            Mat binary    = gray.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat labelView = new Mat();
            Mat rectView  = binary.CvtColor(ColorConversionCodes.GRAY2BGR);

            ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);

            if (cc.LabelCount <= 1)
            {
                return;
            }

            // draw labels

            /*
             * Scalar[] colors = cc.Blobs.Select(_ => Scalar.RandomColor()).ToArray();
             * int height = cc.Labels.GetLength(0);
             * int width = cc.Labels.GetLength(1);
             * var labelViewIndexer = labelView.GetGenericIndexer<Vec3b>();
             * for (int y = 0; y < height; y++)
             * {
             *  for (int x = 0; x < width; x++)
             *  {
             *      int labelValue = cc.Labels[y, x];
             *      labelViewIndexer[y, x] = colors[labelValue].ToVec3b();
             *  }
             * }
             */
            cc.RenderBlobs(labelView);

            // draw bonding boxes except background
            foreach (var blob in cc.Blobs.Skip(1))
            {
                rectView.Rectangle(blob.Rect, Scalar.Red);
            }

            // filter maximum blob
            ConnectedComponents.Blob maxBlob = cc.GetLargestBlob();
            //cc.Blobs.Skip(1).OrderByDescending(b => b.Area).First();
            Mat filtered = new Mat();

            cc.FilterByBlob(src, filtered, maxBlob);

            using (new Window("src", src))
                using (new Window("binary", binary))
                    using (new Window("labels", labelView))
                        using (new Window("bonding boxes", rectView))
                            using (new Window("maximum blob", filtered))
                            {
                                Cv2.WaitKey();
                            }
        }
Exemplo n.º 11
0
        public void Test()
        {
            var g  = GraphGenerator.graph4ConnectedComponents();
            var cc = new ConnectedComponents(g);

            console.WriteLine("count: {0}", cc.Count);
            for (var v = 0; v < g.V(); ++v)
            {
                console.WriteLine(v + "\t:" + cc.componentId(v));
            }
        }
        private ConnectedComponents CreateCC()
        {
            Graph graph = new Graph(6);

            graph.AddEdge(0, 1);
            graph.AddEdge(1, 2);
            graph.AddEdge(2, 3);
            graph.AddEdge(4, 5);

            return(ConnectedComponents.Create(graph));
        }
Exemplo n.º 13
0
        public void GraphConnectedComponentsSelfLoop()
        {
            var graph = new UndirectedGraph(1);

            graph.AddEdge(0, 0);
            var cc = new ConnectedComponents(graph);

            Assert.AreEqual(1, cc.AmountOfComponents);
            Assert.AreEqual(0, cc.ComponentId(0));
            Assert.IsTrue(cc.Connected(0, 0));
        }
Exemplo n.º 14
0
        public GraphProperties(Graph g)
        {
            var connectedComponents = new ConnectedComponents(g);

            if (!connectedComponents.IsConnected)
            {
                throw new NotConnectedGraphException("Graph properties require a connected graph.");
            }

            _g = g;
        }
Exemplo n.º 15
0
        public void ConnectedComponentsWhenEveryVertexIsolated()
        {
            WeightedGraph <int> graph = new WeightedGraph <int>
            {
                new WeightedEdge <int>(1, 1),
                new WeightedEdge <int>(2, 2),
                new WeightedEdge <int>(3, 3)
            };

            ConnectedComponents <int> cc = new ConnectedComponents <int>(graph);

            Assert.AreEqual(3, cc.Count());
        }
Exemplo n.º 16
0
        public void ConnectedComponentsWhenEveryVertexIsolatedNoVerticesConnected(int vertex1, int vertex2)
        {
            WeightedGraph <int> graph = new WeightedGraph <int>
            {
                new WeightedEdge <int>(1, 1),
                new WeightedEdge <int>(2, 2),
                new WeightedEdge <int>(3, 3)
            };

            ConnectedComponents <int> cc = new ConnectedComponents <int>(graph);

            Assert.IsFalse(cc.Connected(vertex1, vertex2));
        }
Exemplo n.º 17
0
        public void ConnectedComponentsTwoVerticesConnected()
        {
            WeightedGraph <int> graph = new WeightedGraph <int>
            {
                new WeightedEdge <int>(1, 2),
                new WeightedEdge <int>(2, 3),
                new WeightedEdge <int>(3, 4)
            };

            ConnectedComponents <int> cc = new ConnectedComponents <int>(graph);

            Assert.IsTrue(cc.Connected(4, 2));
        }
        public static void DoTest()
        {
            var graph = new UndirectedSparseGraph <string>();

            // Add vertices
            var verticesSet1 = new string[] { "a", "b", "c", "d", "e", "f", "s", "v", "x", "y", "z" };

            graph.AddVertices(verticesSet1);

            // Add edges
            // Connected Component #1
            // the vertex "e" won't be connected to any other vertex

            // Connected Component #2
            graph.AddEdge("a", "s");
            graph.AddEdge("a", "d");
            graph.AddEdge("s", "x");
            graph.AddEdge("x", "d");

            // Connected Component #3
            graph.AddEdge("b", "c");
            graph.AddEdge("b", "v");
            graph.AddEdge("c", "f");
            graph.AddEdge("c", "v");
            graph.AddEdge("f", "b");

            // Connected Component #4
            graph.AddEdge("y", "z");


            // Get connected components
            var connectedComponents = ConnectedComponents.Compute <string>(graph);

            connectedComponents = connectedComponents.OrderBy(item => item.Count).ToList();

            Debug.Assert(connectedComponents.Count == 4);

            // the case of the (e) vertex
            Debug.Assert(connectedComponents[0].Count == 1);
            Debug.Assert(connectedComponents[0][0] == "e");

            // the case of (y) and (z) vertices
            Debug.Assert(connectedComponents[1].Count == 2);
            Debug.Assert(connectedComponents[1].Contains("y"));
            Debug.Assert(connectedComponents[1].Contains("z"));

            // the case of the rest
            Debug.Assert(connectedComponents[2].Count == 4);
            Debug.Assert(connectedComponents[3].Count == 4);
        }
Exemplo n.º 19
0
        public void TestCase1()
        {
            var g = new Graph(13);

            g.AddEdge(0, 6);
            g.AddEdge(0, 2);
            g.AddEdge(0, 1);
            g.AddEdge(0, 5);
            g.AddEdge(3, 5);
            g.AddEdge(3, 4);
            g.AddEdge(4, 5);
            g.AddEdge(4, 6);
            g.AddEdge(7, 8);
            g.AddEdge(9, 11);
            g.AddEdge(9, 10);
            g.AddEdge(9, 12);
            g.AddEdge(11, 12);
            var cc       = new ConnectedComponents(g);
            var expected = new int[][]
            {
                new int[] { 0, 1, 2, 3, 4, 5, 6 },
                new int[] { 7, 8 },
                new int[] { 9, 10, 11, 12 }
            };
            var actual = new int[3][];

            Assert.Equal(3, cc.Count);
            var ids = new List <int> [cc.Count];

            foreach (var v in Enumerable.Range(0, g.V))
            {
                var id = cc.ID(v);
                if (ids[id] is null)
                {
                    ids[id] = new List <int>()
                    {
                        v
                    };
                }
                else
                {
                    ids[id].Add(v);
                }
            }
            foreach (var i in Enumerable.Range(0, cc.Count))
            {
                actual[i] = ids[i].ToArray();
            }
            Assert.Equal(expected, actual);
        }
Exemplo n.º 20
0
        public void GraphConnectedComponents()
        {
            var g  = graph.DeepCopy();
            var cc = new ConnectedComponents(g);

            Assert.AreEqual(3, cc.AmountOfComponents);
            Assert.IsTrue(cc.Connected(0, 1));
            Assert.IsTrue(cc.Connected(7, 8));
            Assert.IsTrue(cc.Connected(9, 12));
            CollectionAssert.AreEqual(new List <int>()
            {
                7, 8
            }, cc.GetVerticesForComponent(1));
        }
        public void Reset()
        {
            foreach (var node in Nodes)
            {
                node.Reset();
            }

            NodeStack.Clear();
            ConnectedComponents.Clear();

            ArticulationPoints.Clear();
            CriticalVertices.Clear();

            Time = 0;
        }
        private void CalculateConnectedComponents(IGraph graph, bool stronglyConnected)
        {
            ResultItemCollection <Component> components;

            if (stronglyConnected)
            {
                var result = new StronglyConnectedComponents().Run(graph);
                components = result.Components;
            }
            else
            {
                var result = new ConnectedComponents().Run(graph);
                components = result.Components;
            }

            if (components.Count > 0)
            {
                // generate a color array
                var colors = GenerateColors(false, components.Count);

                var visitedEdges = new HashSet <IEdge>();

                for (var i = 0; i < components.Count; i++)
                {
                    var component = components[i];
                    var color     = colors[i];

                    foreach (var edge in component.InducedEdges)
                    {
                        // each edge of the same cycle get the same tag
                        visitedEdges.Add(edge);
                        var tag = InitializeTag(edge);
                        tag.CurrentColor = color;
                    }
                    component.Nodes.ForEach(node => {
                        InitializeTag(node).CurrentColor = color;
                    });
                }

                foreach (var edge in graph.Edges)
                {
                    if (visitedEdges.Add(edge))
                    {
                        InitializeTag(edge);
                    }
                }
            }
        }
Exemplo n.º 23
0
        public void SmokeTest()
        {
            var graph = new Graph();

            graph.AddEdge(0, 1);
            graph.AddEdge(0, 2);
            graph.AddEdge(0, 3);
            graph.AddEdge(0, 4);

            graph.AddEdge(5, 6);
            graph.AddEdge(5, 7);
            graph.AddEdge(5, 8);
            graph.AddEdge(5, 9);

            graph.AddEdge(10, 11);
            graph.AddEdge(12, 13);
            graph.AddEdge(14, 15);

            var cc = new ConnectedComponents(graph);

            Assert.AreEqual(5, cc.Count);
            Assert.AreEqual(-1, cc.GetId(999));

            Assert.AreEqual(0, cc.GetId(0));
            Assert.AreEqual(0, cc.GetId(1));
            Assert.AreEqual(0, cc.GetId(2));
            Assert.AreEqual(0, cc.GetId(3));
            Assert.AreEqual(0, cc.GetId(4));

            Assert.AreEqual(1, cc.GetId(5));
            Assert.AreEqual(1, cc.GetId(6));
            Assert.AreEqual(1, cc.GetId(7));
            Assert.AreEqual(1, cc.GetId(8));
            Assert.AreEqual(1, cc.GetId(9));

            Assert.AreEqual(2, cc.GetId(10));
            Assert.AreEqual(2, cc.GetId(11));

            Assert.AreEqual(3, cc.GetId(12));
            Assert.AreEqual(3, cc.GetId(13));

            Assert.AreEqual(4, cc.GetId(14));
            Assert.AreEqual(4, cc.GetId(15));
        }
        public void Run()
        {
            Mat src       = new Mat(FilePath.Image.Shapes, ImreadModes.Color);
            Mat gray      = src.CvtColor(ColorConversionCodes.BGR2GRAY);
            Mat binary    = gray.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat labelView = src.EmptyClone();
            Mat rectView  = binary.CvtColor(ColorConversionCodes.GRAY2BGR);

            ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);

            if (cc.LabelCount <= 1)
            {
                return;
            }

            // draw labels
            cc.RenderBlobs(labelView);

            // draw bonding boxes except background
            foreach (var blob in cc.Blobs.Skip(1))
            {
                rectView.Rectangle(blob.Rect, Scalar.Red);
            }

            // filter maximum blob
            var maxBlob  = cc.GetLargestBlob();
            var filtered = new Mat();

            cc.FilterByBlob(src, filtered, maxBlob);

            //using (new Window("src", src))
            //using (new Window("binary", binary))
            //using (new Window("labels", labelView))
            //using (new Window("bonding boxes", rectView))
            //using (new Window("maximum blob", filtered))
            //{
            //    Cv2.WaitKey();
            //}
            src.SaveImage("src.png");
            binary.SaveImage("binary.png");
            labelView.SaveImage("labels.png");
            rectView.SaveImage("boxes.png");
            filtered.SaveImage("maximumblob.png");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Marks the cycle nodes and edges.
        /// </summary>
        private void MarkCycles(IGraph graph, CycleEdges.Result cycleResult)
        {
            // hides all non-cycle edges to be able to find independent cycles
            var cycleEdgeSet  = new HashSet <IEdge>(cycleResult.Edges);
            var filteredGraph = new FilteredGraphWrapper(graph, node => true, edge => cycleEdgeSet.Contains(edge));

            // now find independent cycles
            var result = new ConnectedComponents().Run(filteredGraph);

            // find the components that are affected by the user's move, if any
            var affectedComponents = GetAffectedNodeComponents(result.NodeComponents);
            // find the component with the larger number of elements
            var largestComponent = GetLargestComponent(affectedComponents);
            // hold a color for each affected components
            var color2AffectedComponent = new Dictionary <Component, Color>();
            // generate the colors for the components
            var colors = GenerateColors(false);

            for (var i = 0; i < result.Components.Count; i++)
            {
                var component = result.Components[i];

                foreach (var edge in component.InducedEdges)
                {
                    // the source and target node get the same color, depending on their connecting edge
                    var color = DetermineElementColor(colors, component, affectedComponents, color2AffectedComponent, largestComponent, result.Components, graph, edge);
                    edge.Tag = new Tag {
                        CurrentColor = color,
                        Directed     = Directed
                    };
                    var source = edge.GetSourceNode();
                    source.Tag = new Tag {
                        CurrentColor = color
                    };

                    var target = edge.GetTargetNode();
                    target.Tag = new Tag {
                        CurrentColor = color
                    };
                }
            }
        }
Exemplo n.º 26
0
        public int GetBlobs(Mat img, bool showImage = false)
        {
            Mat gray = img.CvtColor(ColorConversionCodes.BGR2GRAY);
            //Mat binary = gray.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat binary = gray.Threshold(50, 255, ThresholdTypes.Binary);


            //2.Define/search ROI area
            Mat labelView          = img.EmptyClone();
            Mat rectView           = binary.CvtColor(ColorConversionCodes.GRAY2BGR);
            ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);

            if (cc.LabelCount <= 1)
            {
                throw new Exception("no blob found");
            }

            //draw lables
            cc.RenderBlobs(labelView);

            //draw boxes except background
            foreach (var blob in cc.Blobs.Skip(1))
            {
                rectView.Rectangle(blob.Rect, Scalar.Red);
            }

            if (showImage == true)
            {
                using (new Window("blob image", rectView))
                //using (new Window("labelview image", labelView))
                {
                    //Cv2.WaitKey(1000);
                    Cv2.WaitKey(0);
                    Cv2.DestroyWindow("blob image");
                    //Cv2.DestroyWindow("labelview image");
                }
            }
            return(cc.LabelCount - 1);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 処理実行
        /// </summary>
        public ImageProcessValue Execute(SettingsObj obj)
        {
            try
            {
                // webカメラキャプチャ
                var camera = new OpenCvSharp.VideoCapture(0)
                {
                    //// 解像度の指定
                    FrameWidth  = 1920,
                    FrameHeight = 1080
                };

                using (camera)
                {
                    // カメラ内部パラメータ格納用
                    Mat mtx  = new Mat();
                    Mat dist = new Mat();

                    // ymlファイルを読み来み計算パラメータを取得
                    using (var fs = new FileStorage(obj.CalibratinFilePath, FileStorage.Mode.Read))
                    {
                        mtx  = fs["mtx"].ReadMat();
                        dist = fs["dist"].ReadMat();
                    }

                    var src = new Mat();

                    // 撮影画像の読み取り
                    camera.Read(src);

                    if (src.Empty())
                    {
                        return(null);
                    }

                    Mat calib = new Mat();
                    // 歪み補正
                    Cv2.Undistort(src, calib, mtx, dist);

                    // 画像処理
                    var tmp = new Mat();
                    // OpenCVのカラーの並びに変換
                    Cv2.CvtColor(calib, tmp, OpenCvSharp.ColorConversionCodes.RGB2BGR);
                    // BGR画像をHSV画像に変換
                    var hsv = new Mat();
                    Cv2.CvtColor(tmp, hsv, OpenCvSharp.ColorConversionCodes.BGR2HSV);
                    // inRange関数で範囲指定2値化 -> マスク画像として使う
                    var msk = new Mat();
                    Cv2.InRange(hsv, new Scalar(obj.HueMin, obj.SaturationMin, obj.ValueMin), new Scalar(obj.HueMax, obj.SaturationMax, obj.ValueMax), msk);

                    // bitwise_andで元画像にマスクをかける -> マスクされた部分の色だけ残る
                    var msk_src = new Mat();
                    Cv2.BitwiseAnd(hsv, hsv, msk_src, msk);
                    var show_msk = new Mat();
                    // 元の色に戻す
                    Cv2.CvtColor(msk_src, show_msk, ColorConversionCodes.HSV2BGR);
                    // グレースケール変換
                    var gray = new Mat();
                    Cv2.CvtColor(show_msk, gray, ColorConversionCodes.BGR2GRAY);
                    // 2値化
                    var th = new Mat();
                    Cv2.Threshold(gray, th, 130, 255, ThresholdTypes.Otsu);

                    // ブロブとラベリング
                    var label              = new Mat();
                    var stats              = new Mat();
                    var centroids          = new Mat();
                    ConnectedComponents cc = Cv2.ConnectedComponentsEx(th);

                    if (cc.LabelCount <= 1)
                    {
                        return(null);
                    }
                    // draw labels
                    //cc.RenderBlobs(show_msk);
                    // draw bonding boxes except background
                    foreach (var blob in cc.Blobs.Skip(1))
                    {
                        show_msk.Rectangle(blob.Rect, Scalar.Red);
                    }

                    // filter maximum blob
                    var maxBlob  = cc.GetLargestBlob();
                    var filtered = new Mat();
                    cc.FilterByBlob(show_msk, filtered, maxBlob);

                    // 矩形探索
                    // マスク画像から矩形探索
                    Point[][]        contours;
                    HierarchyIndex[] hierarchy;
                    Cv2.FindContours(th, out contours, out hierarchy, RetrievalModes.List, ContourApproximationModes.ApproxNone);
                    // 見つからなかったら何もしない
                    if (contours.Length == 0)
                    {
                        return(null);
                    }

                    // 回転を考慮した外接矩形
                    foreach (var cont in contours)
                    {
                        var rect = Cv2.MinAreaRect(cont);
                        var box  = Cv2.BoxPoints(rect).Select(x => (Point)x);
                    }

                    Cv2.DrawContours(show_msk, contours, -1, Scalar.Yellow, 3);
                    //Cv2.ImShow("show_msk", show_msk);

                    // 画像、画像上の位置発火
                    var val = new ImageProcessValue();
                    val.CameraImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(show_msk);
                    val.Blob        = maxBlob;

                    // メモリリーク対策でDispose呼ぶ
                    mtx.Dispose();
                    dist.Dispose();
                    calib.Dispose();
                    tmp.Dispose();
                    hsv.Dispose();
                    msk.Dispose();
                    msk_src.Dispose();
                    show_msk.Dispose();
                    gray.Dispose();
                    th.Dispose();
                    label.Dispose();
                    stats.Dispose();
                    centroids.Dispose();
                    filtered.Dispose();

                    return(val);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            string result = string.Empty;

            var graph = new UndirectedSparseGraph <string>();

            // Add vertices
            var verticesSet1 = new string[] { "a", "b", "c", "d", "e", "f", "s", "v", "x", "y", "z" };

            graph.AddVertices(verticesSet1);

            result = result + "Vertices: " + "'a', 'b', 'c', 'd', 'e', 'f', 's', 'v', 'x', 'y', 'z'" + "\n\n";

            // Add edges
            // Connected Component #1
            // the vertex "e" won't be connected to any other vertex

            // Connected Component #2
            graph.AddEdge("a", "s");
            graph.AddEdge("a", "d");
            graph.AddEdge("s", "x");
            graph.AddEdge("x", "d");

            // Connected Component #3
            graph.AddEdge("b", "c");
            graph.AddEdge("b", "v");
            graph.AddEdge("c", "f");
            graph.AddEdge("c", "v");
            graph.AddEdge("f", "b");

            // Connected Component #4
            graph.AddEdge("y", "z");

            result = result + "Edges: ";
            result = result + graph.ToReadable() + "\r\n\n";


            // Get connected components
            var connectedComponents = ConnectedComponents.Compute(graph);

            connectedComponents = connectedComponents.OrderBy(item => item.Count).ToList();

            result = result + "# of Connected Components: " + connectedComponents.Count() + "\n";


            result = result + "Components are: \n";
            foreach (var items in connectedComponents)
            {
                string edge = string.Empty;
                foreach (var item in items)
                {
                    edge = edge + item + " -> ";
                }

                result = result + edge.Remove(edge.Length - 4) + "\n";
            }

            HtmlString html = StringHelper.GetHtmlString(result);

            return(View(html));
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            // StringProblems
            //Test calls for Reverse string
            string input = "jacob";

            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jake";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jdshjdh@#$%^&)";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));

            ReplaceSpaces.TestReplaceSpacesInplace();
            Anagrams.TestIsAnagramAlgo();
            StringRotation.TestIsThisRotatedString();
            RemoveDuplicates.TestRemoveDuplicatesFromString();
            StringToLongConverter.TestStringToLong();
            RegexMatching.TestMatch();
            SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray();
            SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray();
            PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue();
            PalindromeInStringPermutation.TestPalindromeInStringPermutation();
            EditDistanceBetweenStrings.TestEditDistanceBetweenStrings();
            AnagramIsPalindrome.TestAnagramIsPalindrome();
            GreatestPalindrome.TestGreatestPalindrome();
            ReverseStringWithoutVowels.TestReverseStringWithoutVowels();
            LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars();
            // Pattern Matching
            NativePatternMatching.TestNativePatternMatching();
            KMPPatternMatching.TestKMPPatternMatching();
            BoyerMoorePatternMatching.TestPatternMatching();
            RabinKarp.TestRabinKarp();

            //Console.ReadLine();

            //Array Problems
            ArrayOfNumsIncrement.TestIncrementArrayOfNumbers();
            MajorityElement.TestFindMajorityElement();
            Merge2SortedArrays.TestMergeSortedArrays();
            MaxDistanceInArray.TestMaxDistanceInArray();
            MovingAverage.TestMovingAverage();
            TotalAverage.TestTotalAverage();
            ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight();
            WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram();
            CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum();
            //Median.TestGetMedianOf2SortedArray();

            // Sorting Problems
            SelectionSort.TestSorting();
            BubbleSort.TestSorting();
            InsertionSort.TestSorting();
            ShellSort.TestSorting();
            MergeSort.TestMergeSort();
            QuickSort.TestQuickSort();
            HeapSortTester.TestHeapSort();
            CountingSort.TestSorting();
            RadixSort.TestRadixSort();
            DutchNationalFlag.TestDutchNationalFlag();
            SortedSquares.TestSortedSquares();

            // Matrix Problem
            Rotate_Matrix_90_degree.TestRotateMatrix();
            Matrix_Column_Rows_0.TestMakeRowColZero1();
            Matrix_Column_Rows_0.TestMakeRowColZero2();
            RotateMatrix180.TestRotateMatrix180();
            SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements();
            SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix();
            SearchWordInMatrix.TestSearchWordInMatrix();
            MaxOnesInRow.TestMaxOnesInRow();
            MatrixAsTriangle.TestMatrixAsTriangle();
            MinRangeInMatrix.TestMinRangeInMatrix();
            PrintMatrixAsSnake.TestPrintMatrixAsSnake();
            PrintMatrixInSpiral.TestPrintMatrixInSpiral();
            MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix();
            TicTacToeWinner.TestTicTacToeWinner();
            WaterfallCreation.TestWaterfallCreation();

            // Linked list Problems
            DeleteLinkedListNode.TestDeleteFirstNode();
            DeleteDuplicatesFromLinkedList.TestDeleteDuplicates();
            NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList();
            DeleteNodeWithDirectReference.TestDeleteNode();
            AddNumbers.TestAddNumbersRepresentedByLinkedList();
            CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode();
            CommonElementInTwoLinkedList.TestCommonElement();
            ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes();
            MergeSortedLinkedList.TestMerge();
            CycleInLinkedList.TestStartOfCycleInLinkedList();
            MedianForCircularLinkedList.TestGetMedian();
            ReverseLinkedList.TestReverseLinkedList();
            SortedCircularLinkedList.TestCircularLinkedList();

            // stack and queue problem
            ThreeStackWithOneArray.TestThreeStackWithOneArray();
            StackWithMinElement.TestStackWithMinElement();
            StackOfPlates.TestStackOfPlates();
            SortAStack.TestSortAStackAscending();
            WellFormedExpression.TestWellFormedExpression();
            QueueVia2Stack.TestQueueVia2Stack();
            LRUCache.TestLRUCache();
            EvaluatePrefixNotation.TestGetPrefixNotationResult();
            EvaluateInflixNotation.TestGetInflixNotationResults();
            EvaluatePostfixNotation.TestGetPostfixNotationResult();
            TestCircularQueue.TestCircularQueueWithDifferentCases();
            LargestAreaInHistogram.TestLargestAreaInHistogram();
            TextEditerWithUndo.TestTextEditerWithUndo();

            //Recursion Problem
            TowerOfHanoi.TestTowerOfHanoi();
            MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums();

            // Back tracking problems
            Sudoku.TestSudokuSolver();
            HamiltonianCycle.TestHamiltonianCycle();
            GraphColoringWithMColors.TestGraphColoringWithMColors();
            MakeLargestIsland.TestMakeLargestIsland();

            //Misc Problem
            MinNumOfCoins.TestMinNumOfCoins();
            IsPrime.TestCheckPrime();
            SquareRoot.TestCalculateSquareRoot();
            CreditCardCheck.TestLuhnAlgo();
            ExcelFirstRowConversion.TestCovertExcelColumnToLong();
            Skyline.TestSkyline();
            SumOfSquaresWithoutMultiplication.TestSumOfSquares();
            MergeIntervals.TestMergeIntervals();
            WidthOfCalendar.TestWidthOfCalendar();
            JosephusProblem.TestJosephusProblem();

            // Permutation and Combination problem
            ShuffleAList.TestFisherYatesAlgo();
            CombinationsOfBinaryString.TestCombinationsOfBinaryString();
            AllCombinationsOfString.TestAllCombinationsOfString();
            AllPermutationsOfString.TestAllPermutationsOfString();
            PhoneNumberToWords.TestPhoneNumberToWords();
            AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits();
            DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff();
            PowerSet.TestPowerSet();
            AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis();
            GoodDiceRoll.TestGoodDiceRoll();
            PermutationsOfValidTime.TestPermutationsOfValidTime();

            // Tree Problems
            TreeFromExpression.TestCreateTreeFromExpression();
            TestBinarySearchTree.TestDifferentOperationsOnBST();
            AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST();
            CheckBTisBST.TestCheckBTisBST();
            MaxSumOnTreeBranch.TestMaxSum();
            WalkTheTree.TestWalkTheTree();
            SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST();
            CheckIfTheTreeIsBalanced.TestIsTreeBalanced();
            LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth();
            PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel();
            PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally();
            TreeSubtreeOfAnother.TestMatchTree();
            AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT();
            AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT();
            LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT();
            ExteriorOfBT.TestPrintExteriorOfBT();
            DepthOfTree.TestGetDepthOfTree();
            TreeToColumns.TestTreeToColumns();
            KthSmallestElementFromBST.TestKthSmallestElementFromBST();
            MakeBSTFromPreOrder.TestMakeBSTFromPreOrder();
            MirrorATree.TestMirrorATree();
            CloneABTWithRandPointer.TestCloneABTWithRandPointer();
            TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder();
            TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder();
            TreePathSumsToValue.TestTreePathSumsToValue();
            AllPathInNArayTree.TestAllPathInNArayTree();
            SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree();
            SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree();
            AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree();
            AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT();

            // Trie problems
            CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie();
            // ToDo: have a problem of suffix trees
            ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet();

            // Dynamic Programming problems
            LongestCommonSubsequence.TestGetLongestCommonSubsequence();
            LongestPalindromeSubString.TestGetLongestPalindromeSubString();
            LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence();
            MaximumAs.TestGetMaximumAs();
            MinNumberOfJumps.TestGetMinimumNumberOfJumps();
            LongestCommonSubString.TestGetLongestCommonSubString();
            KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight();
            TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits();
            WordBreaking.TestBreakTheWords();
            DistanceOfWords.TestDistanceOfWords();
            LongestIncreasingSubSequence.TestLongestIncreasingSubSequence();
            MinCostPath.TestMinCostPath();
            DifferentWaysForCoinChange.TestDifferentWaysForCoinChange();
            MatrixMultiplication.TestMatrixMultiplication();
            BinomialCoefficient.TestBinomialCoefficient();
            BoxStacking.TestBoxStacking();
            WordWrapping.TestWordWrapping();
            MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes();
            LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum();
            PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets();
            MaxSumRectangle.TestMaxSumRectangle();
            RegularExpressionMatch.TestRegularExpressionMatch();
            NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares();
            LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString();
            StringDecodeAsAlphabets.TestStringDecodeAsAlphabets();
            BalloonBursting.TestBalloonBursting();
            TravellingSalesmanProblem.TestTravellingSalesmanProblem();
            MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements();
            MaxPathThroughMatrix.TestMaxPathThroughMatrix();
            BrickLaying.TestBrickLaying();
            JobSchedullingWithConstraints.TestJobSchedullingWithConstraints();
            EggDropMinTrials.TestEggDropMinTrials();

            // Graph Problems
            ShortestPath.TestGetShortestPathBetween2Vertex();
            CycleInDirectedGraph.TestIsCycleInDirectedGraph();
            CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph();
            SolveAMaze.TestSolveAMaze();
            AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex();
            AllPaths.TestGetAllPathsInGraphFromStartVertex();
            ColorVertices.TestColorVerticesWithDifferentColor();
            CheckBipartiteGraph.TestCheckBipartiteGraph();
            TransformOneWordToAnother.TestGetTransformation();
            ConstraintsVerification.TestConstraintsVerification();
            ExtendedContactsInSocialNetwork.TestComputeExtendedContacts();
            CourseScheduling.TestCourseScheduling();
            SnakeAndLadder.TestSnakeAndLadder();
            IsGraphATree.TestIsGraphATree();
            ReverseGraph.TestReverseGraph();
            StronglyConnectedGraph.TestStronglyConnectedGraph();
            ConnectedComponents.TestConnectedComponents();
            ContinentalDivide.TestContinentalDivide();
            CloneGraph.TestCloneGraph();
            Wordament.TestWordament();
            // ShortestPathAlgo
            FloydWarshall.TestFloydWarshall();
            DijkstraAlgorithm.TestDijkstraAlgorithm();
            BellmanFord.TestBellmanFord();
            TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix();
            HeuristicSearch.TestHeuristicSearch();
            AStar.TestAStar();
            ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved();
            ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates();
            //MaxFlow
            FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp();
            MinCut.TestMinCut();
            MaximumBipartiteMatching.TestMaximumBipartiteMatching();
            //Minimum Spanning Tree
            KruskalAlgorithm.TestKruskalAlgorithm();
            PrimsAlgorithm.TestPrimsAlgorithm();


            //Heap problems
            BasicMaxHeap.TestMaxHeap();
            BasicMinHeap.TestMinHeap();
            TestMinHeapMap.DoTest();
            TestPriorityQueue.Run();
            MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers();

            //DisjointSets
            TestingDisjointSet.Run();
            //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it

            //Geometry
            ClosestPairOfPoints.TestClosestPairOfPoints();
            RectangleIntersection.TestRectangleIntersection();
            LineSegmentIntersection.TestLineSegmentIntersection();
            ConvexHull.TestConvexHull();
            KClosestPointToOrigin.TestKClosestPointToOrigin();

            //Greedy Algorithm
            HuffmanCoding.TestHuffmanCoding();

            //Randomized Algorithm
            RandomGeneration.TestRandomGeneration();

            // Bit Algorithms
            IntHaveOppositeSigns.TestIntHaveOppositeSigns();
            Parity.TestParity();

            //Math Problem
            ZerosInFactorial.TestZerosInFactorial();
            GetAllPrimeFactors.TestGetAllPrimeFactors();
            NumberOfFactors.TestNumberOfFactors();
            AllFactors.TestAllFactors();
            MultiplyLongNumbers.TestMultiplyLongNumbers();
            NextLargestPermutation.TestNextLargestPermutation();
            AllPrimesTillN.TestAllPrimesTillN();
            PascalsTriangle.TestPascalsTriangle();
            SubtractLongNumbers.TestSubtractLongNumbers();

            //Search problems
            SearchInSortedRotatedArray.TestSearchInSortedRotatedArray();
            KClosestElementInArray.TestKClosestElementInArray();
            SearchInSortedMatrix.TestSearchInSortedMatrix();
            BinarySearchUnbounded.TestBinarySearchUnbounded();
            LinkedListSublistSearch.TestLinkedListSublistSearch();
            NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray();
            GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray();

            //Distributed algorithms
            KWayMerge.TestKWayMerge();


            Console.ReadLine();
        }
Exemplo n.º 30
0
        /// <summary>
        /// 是否需要保存图片
        /// </summary>
        /// <param name="mat">指的是刚刚读进来的灰度图片</param>
        /// <returns></returns>
        public static bool IsNeedToSave(Mat mat)
        {
            if (mat == null || mat.IsDisposed)
            {
                return(false);
            }

            #region 预判断

            if ((DateTime.Now - lastCallTime).TotalMilliseconds < 600)
            {
                //调用间隔至少为600ms
                NLogHelper.Trace("调用频繁,不需要截图");
                return(false);
            }

            lastCallTime = DateTime.Now;

            #endregion

            #region 加载背景图片
            if (backgroundMat == null || backgroundMat.IsDisposed)
            {
                if (!File.Exists(backgroundFile))
                {
                    NLogHelper.Trace("未找到背景图片:" + backgroundFile);
                    backgroundMat = null;
                }
                else
                {
                    try
                    {
                        backgroundMat = Cv2.ImRead(backgroundFile, ImreadModes.GrayScale);
                        //去噪
                        backgroundMat = backgroundMat.MedianBlur(3);
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Trace("加载背景图片失败:" + ex);
                        if (backgroundMat != null && backgroundMat.IsEnabledDispose)
                        {
                            backgroundMat.Dispose();
                        }
                        backgroundMat = null;
                    }
                }
            }
            #endregion

            #region 图片处理

            ////进行图像灰度化
            if (mat.Channels() > 1)
            {
                Mat outMat = new Mat();
                Cv2.CvtColor(mat, outMat, ColorConversionCodes.BGRA2GRAY);
                mat = outMat;
            }
            //图片去噪
            mat = mat.MedianBlur(3);
            int width  = mat.Width;
            int height = mat.Height;
            //当前使用的背景图片
            Mat usedBackgroundMat = null;
            if (backgroundMat != null)
            {
                if (backgroundMat.Width != width || backgroundMat.Height != height)
                {
                    NLogHelper.Trace("背景图片与原图大小不一样,进行缩放");
                    usedBackgroundMat = backgroundMat.Resize(new Size(width, height));
                }
                else
                {
                    usedBackgroundMat = backgroundMat;
                }
            }

            //是否使用了lightMethod 光照模型去除背景, 拍摄同样一张图片但是不带物体
            bool usedLightMethod = false;
            if (usedBackgroundMat != null && usedBackgroundMat.Width == width && usedBackgroundMat.Height == height)
            {
                if (lightMethod == 0)
                {
                    mat             = usedBackgroundMat - mat;
                    usedLightMethod = true;
                }
                else if (lightMethod == 1)
                {
                    mat.ConvertTo(mat, MatType.CV_32F);
                    usedBackgroundMat.ConvertTo(usedBackgroundMat, MatType.CV_32F);
                    mat = (1 - (usedBackgroundMat / mat)) * 255;
                    mat.ConvertTo(mat, MatType.CV_8U);
                    usedLightMethod = true;
                }
            }

            //二值化图像
            if (usedLightMethod)
            {
                mat = mat.Threshold(30, 255, ThresholdTypes.Binary);
            }
            else
            {
                mat = mat.Threshold(140, 255, ThresholdTypes.Binary);
            }

            #endregion

            #region 联通组件

            ConnectedComponents components = mat.ConnectedComponentsEx();

            List <ConnectedComponents.Blob> blobList = new List <ConnectedComponents.Blob>();

            for (int i = 0; i < components.Blobs.Count; i++)
            {
                if (i == 0)
                {
                    //背景,
                    continue;
                }

                ConnectedComponents.Blob blob = components.Blobs[i];
                //实际区域大小
                if (blob.Area > MinArea && blob.Width > MinWidth && blob.Height > MinHeight)
                {
                    if (blob.Width > width * 0.9 && blob.Height > 0.9)
                    {
                        //发现超大物体,此物体有可能是背景或者其它干扰
                        NLogHelper.Trace("超大物体忽略");
                    }
                    else
                    {
                        //一瓶矿泉水  width = 227 height=171 area=15907
                        blobList.Add(blob);
                    }
                }
            }

            NLogHelper.Trace(string.Format("原图共有{0}个物体", blobList.Count));
            #endregion

            #region 判断是否需要截图

            //获取上一次的blobs
            List <ConnectedComponents.Blob> oldLastBlobs = lastBlobList;
            lastBlobList = blobList;

            if (blobList.Count == 0)
            {
                //没有图片,不需要保存
                NLogHelper.Trace("没有图片,不需要保存");
                return(false);
            }

            //获取最大的宽度的项
            ConnectedComponents.Blob maxItem = blobList.OrderByDescending(r => r.Width).First();

            if (oldLastBlobs == null || oldLastBlobs.Count == 0)
            {
                //之前没有图片 或者 中间范围内没有图片
                if (maxItem.Width > width * 0.7 && maxItem.Height > height * 0.4)
                {
                    //最大的物体很大
                    NLogHelper.Trace("之前没有图像,最大的物体很大,进行保存");
                    return(true);
                }
                else
                {
                    //查找位于中间的个体数量
                    List <ConnectedComponents.Blob> middleBlobs = FindMiddleObjects(width, blobList, 0.81);
                    if (middleBlobs.Count > 0)
                    {
                        //中间有物体
                        NLogHelper.Trace("之前没有图像,中间有物体,进行保存");
                        return(true);
                    }
                    else
                    {
                        //中间没有物体或者物体没有完全到中间
                        NLogHelper.Trace("之前没有图像,中间没有物体或者物体没有完全到中间,进行保存");
                        return(false);
                    }
                }
            }
            else
            {
                //if (maxItem.Width > width*0.7 && maxItem.Height> height*0.4)
                //{
                //    //最大的物体很大
                //    return true;
                //}

                //之前图片有物体
                List <ConnectedComponents.Blob> newMiddleBlobs = FindMiddleObjects(width, blobList, 0.81);
                //获取中间旧的
                List <ConnectedComponents.Blob> oldMiddleBlobs = FindMiddleObjects(width, oldLastBlobs, 0.81);

                if (newMiddleBlobs.Count == 0)
                {
                    //中间没有,认为不需要截图
                    NLogHelper.Trace("之前有图像,新图中间没有,认为不需要截图");
                    return(false);
                }

                //新的中间有图
                if (oldMiddleBlobs.Count == 0)
                {
                    //之前有图片,但图片不在中间,新的又有了
                    NLogHelper.Trace("之前有图片,但图片不在中间,新的又有了,需要截图");
                    return(true);
                }
                else
                {
                    int minDiff = 1;//任务现在和之前相差超过minDiff个物体需要截图
                    //现在和以前均有图片
                    if ((newMiddleBlobs.Count - oldMiddleBlobs.Count) > minDiff)
                    {
                        //现在跟置前有两个以上的不同图片
                        NLogHelper.Trace("现在跟之前有两个以上的不同图片,需要截图");
                        return(true);
                    }
                    else
                    {
                        ////先按最左点排序,再按中心点排序,再按照面积排序  升序
                        newMiddleBlobs = newMiddleBlobs.OrderBy(r => r.Left).ThenBy(r => r.Width).ThenBy(r => r.Centroid.Y).ThenBy(r => r.Area).ToList();
                        oldMiddleBlobs = oldMiddleBlobs.OrderBy(r => r.Left).ThenBy(r => r.Width).ThenBy(r => r.Centroid.Y).ThenBy(r => r.Area).ToList();

                        var lcsTuple = LCS(newMiddleBlobs, oldMiddleBlobs);
                        List <ConnectedComponents.Blob> commonBlobs  = lcsTuple.Item1;
                        List <ConnectedComponents.Blob> onlyNewBlobs = lcsTuple.Item2;
                        List <ConnectedComponents.Blob> onlyOldBlobs = lcsTuple.Item3;

                        if (commonBlobs.Count == 0)
                        {
                            //现在和以前没有公共部分,截图
                            NLogHelper.Trace("现在和以前没有公共部分,需要截图");
                            return(true);
                        }
                        else if (onlyNewBlobs.Count == 0 && onlyOldBlobs.Count == 0)
                        {
                            //全部是公共部分
                            NLogHelper.Trace("现在和以前全部是公共部分,不需要截图");
                            return(false);
                        }
                        else if (onlyOldBlobs.Count == 0)
                        {
                            //新的部分多了,除此之外都是公共的
                            NLogHelper.Trace("新的部分多了,除此之外都是公共的,需要截图");
                            return(true);
                        }
                        else if (onlyNewBlobs.Count == 0)
                        {
                            //旧的部分多了,除此之外全是公共的
                            NLogHelper.Trace("旧的部分多了,除此之外全是公共的,不需要截图");
                            return(false);
                        }
                        else
                        {
                            //旧的部分,新的部分,公共的部分都有
                            NLogHelper.Trace("旧的部分,新的部分,公共的部分都有,需要截图");
                            return(true);
                        }
                    }
                }
            }

            #endregion
        }
Exemplo n.º 31
0
 public void TestEmpty()
 {
     var g = Graph.Graph.Bidirectional<int,int> ();
     var cc = new ConnectedComponents<int, int>(g);
     Assert.AreEqual (0, cc.Count);
 }