Ejemplo n.º 1
0
 public void Message_Pass_WhenPercentageDropsButUncoveredCodeDoesNotGrow()
 {
     var threshold = new Threshold(_results66Percent, _results50PercentOf2Lines, 0.30);
     Assert.AreEqual(
         "NCoverCopTask: PASSED: -- There is no newly uncovered code. \r\n\tSequence Points Summary: 2 not excluded, 1 hit\r\n\tPercentage Summary: 50.00% [Minimum Required: 66.67%]\r\n",
         threshold.Message);
 }
Ejemplo n.º 2
0
 public void Message_Fail_WhenPercentageDropsAndUncoveredCodeGrows()
 {
     var threshold = new Threshold(_results66Percent, _results50PercentOf4Lines, 0.30);
     Assert.AreEqual(
         "NCoverCopTask: FAILED: -- WARNING: ** Uncovered code introduced! **\r\n\tSequence Points Summary: 4 not excluded, 2 hit\r\n\tPercentage Summary: 50.00% [Minimum Required: 66.67%]\r\nk m \t\t Line 2-2 in doc\r\n",
         threshold.Message);
 }
Ejemplo n.º 3
0
        protected virtual void TraceWindow(Threshold severity, string message, params object[] values)
        {
            if (severity < threshold)
                return;

            lock (Sync)
                Trace.WriteLine(severity, message.FormatMessage(values));
        }
Ejemplo n.º 4
0
        protected virtual void DebugWindow(Threshold severity, string message, params object[] values)
        {
            if (severity < threshold)
                return;

            lock (Sync)
                System.Diagnostics.Debug.WriteLine(severity, message.FormatMessage(values));
        }
Ejemplo n.º 5
0
        public void Message_PassWithDiff_WhenPercentageIncreasesButNewUncoveredCodeIntroduced()
        {
            var before = new NCoverResults(new[] { _covered1, _uncovered2, _uncovered3 });
            var after  = new NCoverResults(new[] { _covered1, _uncovered2, _covered3, _uncovered4, _uncovered5 });

            var threshold = new Threshold(before, after, 0.30);
            Assert.AreEqual(
                "NCoverCopTask: PASSED: -- WARNING: ** Uncovered code introduced! ** -- but your coverage is better, so I'll let you off.\r\n\tSequence Points Summary: 5 not excluded, 2 hit\r\n\tPercentage Summary: 40.00% [Minimum Required: 33.33%]\r\nk m \t\t Line 4-5 in doc\r\n",
                threshold.Message);
        }
Ejemplo n.º 6
0
		protected virtual void Log(ConsoleColor color, Threshold severity, string message, params object[] values)
		{
			if (severity < this.threshold)
				return;

			lock (Sync)
			{
				Console.ForegroundColor = color;
				Console.WriteLine(message.FormatMessage(this.typeToLog, values));
				Console.ForegroundColor = this.originalColor;
			}
		}
Ejemplo n.º 7
0
        public static MarketStepReturn MarketStep(MarketStepInput input)
        {
            Trend calcTrend = new Trend();
            calcTrend = TrendCalc(input.mid, input.curTrend, input.curLowThreshold, input.curHighThreshold);

            Threshold calcThreshold = new Threshold();
            calcThreshold = ThresholdCalc(calcTrend, input.mid, input.percent, input.curLowThreshold, input.curHighThreshold);

            string calcEventText = EventText(calcTrend, calcThreshold);

            MarketStepReturn outValue = new MarketStepReturn()
            {
                percent = input.percent,
                newTrend = calcTrend.newTrend,
                newLowThreshold = calcThreshold.newLowThreshold,
                newHighThreshold = calcThreshold.newHighThreshold,
                trendOvershoot = calcTrend.trendOvershoot,
                trendReversal = calcTrend.trendReversal,
                eventText = calcEventText
            };
            return outValue;
        }
Ejemplo n.º 8
0
        public static string EventText(Trend uTrend, Threshold uThresholds)
        {
            string retString = "";

            if (NoTrendEvent(uTrend))
            {
                retString = "NO EVENT";
            }
            else if (uTrend.trendOvershoot == iTRUE)
            {
                if (uTrend.newTrend == iTREND_UP)
                {
                    retString = "TREND: UP OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
                else
                {
                    retString = "TREND: DOWN OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }

            }
            else if (uTrend.trendReversal == iTRUE)
            {
                if (uTrend.newTrend == iTREND_UP)
                {
                    retString = "REVERSAL NEW TREND: UP OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
                else
                {
                    retString = "REVERSAL NEW TREND: DOWN OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
            }
            else
            {
                retString = "ERROR INVALID STATE";
            }
            return retString;
        }
Ejemplo n.º 9
0
        private static IEnumerable <(string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)> GetNotSameResults(CommandLineOptions args, Threshold testThreshold, Threshold noiseThreshold)
        {
            foreach (var pair in ReadResults(args)
                     .Where(result => result.baseResult.Statistics != null && result.diffResult.Statistics != null)) // failures
            {
                var baseValues = pair.baseResult.GetOriginalValues();
                var diffValues = pair.diffResult.GetOriginalValues();

                var userTresholdResult = StatisticalTestHelper.CalculateTost(MannWhitneyTest.Instance, baseValues, diffValues, testThreshold);
                if (userTresholdResult.Conclusion == EquivalenceTestConclusion.Same)
                {
                    continue;
                }

                var noiseResult = StatisticalTestHelper.CalculateTost(MannWhitneyTest.Instance, baseValues, diffValues, noiseThreshold);
                if (noiseResult.Conclusion == EquivalenceTestConclusion.Same)
                {
                    continue;
                }

                yield return(pair.id, pair.baseResult, pair.diffResult, userTresholdResult.Conclusion);
            }
        }
Ejemplo n.º 10
0
        public Bitmap edgeDetection()
        {
            Bitmap          colorImg      = (Bitmap)videoSourcePlayer1.GetCurrentVideoFrame();
            Grayscale       grayfilter    = new Grayscale(cr, cg, cb);
            GaussianBlur    blurFilter    = new GaussianBlur();
            GaussianSharpen sharpenFilter = new GaussianSharpen();
            Bitmap          originalImage;

            if (gausianToggle == 0)
            {
                originalImage = (Bitmap)grayfilter.Apply(colorImg);
            }
            else if (gausianToggle == 1)
            {
                originalImage = sharpenFilter.Apply((Bitmap)colorImg);
                originalImage = (Bitmap)grayfilter.Apply(originalImage);
            }
            else
            {
                originalImage = blurFilter.Apply((Bitmap)colorImg);
                originalImage = (Bitmap)grayfilter.Apply(originalImage);
            }
            switch (caseValue)
            {
            case 1:
                //canny
                scrollableImagePanel1.Image = originalImage;
                CannyEdgeDetector edgeDectector = new CannyEdgeDetector();
                edgeDectector.HighThreshold = (byte)cannyUpperThresholdSlider.Value;
                edgeDectector.LowThreshold  = (byte)cannyLowerThresholdSlider.Value;
                edgeDectector.ApplyInPlace(scrollableImagePanel1.Image);
                return((Bitmap)scrollableImagePanel1.Image);

            case 2:
                //gray scale
                scrollableImagePanel3.Image = originalImage;
                Grayscale customGrayScale = new Grayscale((cr * (graySlider.Value / 100)), (cb * (graySlider.Value / 100)), (cg * (graySlider.Value / 100)));
                originalImage = customGrayScale.Apply(colorImg);
                return(originalImage);

            case 3:
                //Black and White
                scrollableImagePanel2.Image = originalImage;
                Threshold thresholdFilter = new Threshold();
                thresholdFilter.ThresholdValue = hScrollBar1.Value;
                thresholdFilter.ApplyInPlace(scrollableImagePanel2.Image);
                return((Bitmap)scrollableImagePanel2.Image);

            case 4:
                //Mixed Color Edits
                scrollableImagePanel5.Image = colorImg;
                ChannelFiltering colorChannelFilter = new ChannelFiltering();
                colorChannelFilter.Red   = new IntRange(0, redSlider.Value);
                colorChannelFilter.Blue  = new IntRange(0, blueSlider.Value);
                colorChannelFilter.Green = new IntRange(0, greenSlider.Value);
                colorChannelFilter.ApplyInPlace((Bitmap)scrollableImagePanel5.Image);
                return((Bitmap)scrollableImagePanel5.Image);

            case 5:
                //Specific Color edits
                ColorFiltering colorFilter = new ColorFiltering();
                if (colorToggle == 1)
                {
                    Console.WriteLine("Red disabled");
                    colorFilter.Red   = new IntRange(0, 0);
                    colorFilter.Blue  = new IntRange(0, 255);
                    colorFilter.Green = new IntRange(0, 255);
                    colorFilter.Apply(colorImg);
                    originalImage = colorImg;
                    return(originalImage);
                }
                else if (colorToggle == 2)
                {
                    Console.WriteLine("Blue disabled");
                    colorFilter.Red   = new IntRange(0, 255);
                    colorFilter.Blue  = new IntRange(0, 0);
                    colorFilter.Green = new IntRange(0, 255);
                    colorFilter.Apply(colorImg);
                    originalImage = colorImg;
                    return(originalImage);
                }
                else if (colorToggle == 3)
                {
                    Console.WriteLine("Green disabled");
                    colorFilter.Red   = new IntRange(0, 255);
                    colorFilter.Blue  = new IntRange(0, 255);
                    colorFilter.Green = new IntRange(0, 0);
                    colorFilter.Apply(colorImg);
                    originalImage = colorImg;
                    return(originalImage);
                }
                else
                {
                    return(colorImg);
                }
            }
            return(originalImage);
        }
Ejemplo n.º 11
0
        private void JpegLiveSource1LiveNotificationEvent(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                if (OnMainThread)
                {
                    LiveContentEventArgs args = e as LiveContentEventArgs;
                    if (args != null && args.LiveContent != null)
                    {
                        // UI thread is too busy - discard this frame from display
                        args.LiveContent.Dispose();
                    }
                    return;
                }
                OnMainThread = true;
                // Make sure we execute on the UI thread before updating UI Controls
                BeginInvoke(new EventHandler(JpegLiveSource1LiveNotificationEvent), new[] { sender, e });
            }
            else
            {
                LiveContentEventArgs args = e as LiveContentEventArgs;
                if (args != null)
                {
                    if (args.LiveContent != null)
                    {
                        // Display the received JPEG
                        //textBoxLength.Text = "" + args.LiveContent.Content.Length;

                        int width  = args.LiveContent.Width;
                        int height = args.LiveContent.Height;

                        MemoryStream ms = new MemoryStream(args.LiveContent.Content);
                        //Bitmap newBitmap = testBox();
                        Bitmap newBitmap = new Bitmap(ms);

                        if (referenceBitmap == null)
                        {
                            referenceBitmap = newBitmap;
                        }

                        textBoxResolution.Text = "" + width + "x" + height;

                        if (pictureBoxOriginal.Size.Width != 0 && pictureBoxOriginal.Size.Height != 0)
                        {
                            if ((newBitmap.Width != pictureBoxOriginal.Width || newBitmap.Height != pictureBoxOriginal.Height))
                            {
                                pictureBoxOriginal.Image = new Bitmap(newBitmap, pictureBoxOriginal.Size);
                            }
                            else
                            {
                                pictureBoxOriginal.Image = newBitmap;
                            }
                        }

                        textBoxDecodingStatus.Text = args.LiveContent.HardwareDecodingStatus;



                        ms.Close();
                        ms.Dispose();

                        _count++;
                        textBoxCount.Text = "" + _count;

                        args.LiveContent.Dispose();



                        /// Star processing frame
                        grayImage            = gfilter.Apply(newBitmap);
                        pictureBoxGray.Image = grayImage;

                        try
                        {
                            if (counter == 4000)
                            {
                                counter    = 0;
                                background = null;
                                analyticsImageProcessing.resetBackground();
                            }

                            if (background == null)
                            {
                                background = analyticsImageProcessing.GetBackGound(grayImage);

                                /// Show mensaje
                                Bitmap   bitmap = new Bitmap(320, 240);
                                Graphics g      = Graphics.FromImage(bitmap);
                                g.FillRectangle(System.Drawing.Brushes.Black, 0, 0, bitmap.Width, bitmap.Height);
                                g.DrawString("Processing Background...", new Font(FontFamily.GenericMonospace, 12), Brushes.White, new PointF(20, pictureBoxOriginal.Height / 2 - 20));
                                g.Dispose();
                                pictureBoxBackgound.Image = new Bitmap(bitmap, pictureBoxOriginal.Size);
                                bitmap.Dispose();
                            }
                            else
                            {
                                pictureBoxBackgound.Image = background;
                                background2 = gfilter.Apply(background);

                                Bitmap backgroundMask = analyticsImageProcessing.diff(grayImage, background2);
                                pictureBox1.Image = backgroundMask;


                                // create filter
                                //   Median filter = new Median();
                                // apply the filter
                                //   Bitmap backgroundMask2 = filter.Apply(backgroundMask);

                                //     pictureBox2.Image = backgroundMask2;

                                // create filter
                                Pixellate pxfilter = new Pixellate(20);
                                // apply the filter
                                Bitmap result = pxfilter.Apply(backgroundMask);
                                //      pictureBox3.Image = result;

                                // create filter
                                Threshold thfilter = new Threshold(1);
                                // apply the filter
                                Bitmap result2 = thfilter.Apply(result);

                                pictureBox4.Image = result2;

                                ApplyMask appmask = new ApplyMask(result2);
                                foreground = appmask.Apply(newBitmap);
                            }


                            /// PocessImage
                            if (foreground != null)
                            {
                                Blob[] blobs = analyticsImageProcessing.GetBlobs(foreground, blobCounter);
                                textBoxMetadata.Text = metadataHandler.SendMetadataBox(blobs, _jpegLiveSource.Width, _jpegLiveSource.Height);
                                PaintHeatMap(blobs);
                                pictureBoxHeatmap.Image = bitmapHeatMap;

                                /// Debug tool


                                if (blobs[0] != null && blobs.Length > 0)
                                {
                                    blobCounter.ExtractBlobsImage(foreground, blobs[0], false);
                                    pictureBoxBlob1.Image = blobs[0].Image.ToManagedImage();
                                    textBoxAreaBlob1.Text = blobs[0].Area.ToString();
                                    textBoxXBlob1.Text    = blobs[0].CenterOfGravity.X.ToString();
                                    textBoxYBlob1.Text    = blobs[0].CenterOfGravity.Y.ToString();
                                }
                                else
                                {
                                    pictureBoxBlob1.Image = null;
                                }

                                if (blobs[1] != null && blobs.Length > 1)
                                {
                                    blobCounter.ExtractBlobsImage(foreground, blobs[1], false);
                                    pictureBoxBlob2.Image = blobs[1].Image.ToManagedImage();
                                    textBoxAreaBlob2.Text = blobs[1].Area.ToString();
                                    textBoxXBlob2.Text    = blobs[1].CenterOfGravity.X.ToString();
                                    textBoxYBlob2.Text    = blobs[1].CenterOfGravity.Y.ToString();
                                }
                                else
                                {
                                    pictureBoxBlob2.Image = null;
                                }

                                if (blobs[2] != null && blobs.Length > 2)
                                {
                                    blobCounter.ExtractBlobsImage(foreground, blobs[2], false);
                                    pictureBoxBlob3.Image = blobs[2].Image.ToManagedImage();
                                    textBoxAreaBlob3.Text = blobs[2].Area.ToString();
                                    textBoxXBlob3.Text    = blobs[2].CenterOfGravity.X.ToString();
                                    textBoxYBlob3.Text    = blobs[2].CenterOfGravity.Y.ToString();
                                }
                                else
                                {
                                    pictureBoxBlob3.Image = null;
                                }

                                if (blobs[3] != null && blobs.Length > 3)
                                {
                                    blobCounter.ExtractBlobsImage(foreground, blobs[3], false);
                                    pictureBoxBlob4.Image = blobs[3].Image.ToManagedImage();
                                    textBoxAreaBlob4.Text = blobs[3].Area.ToString();
                                    textBoxXBlob4.Text    = blobs[3].CenterOfGravity.X.ToString();
                                    textBoxYBlob4.Text    = blobs[3].CenterOfGravity.Y.ToString();
                                }
                                else
                                {
                                    pictureBoxBlob4.Image = null;
                                }
                            }
                        }
                        catch (Exception r)
                        {
                            Console.WriteLine(r.Message);
                        }
                    }
                    else if (args.Exception != null)
                    {
                        // Handle any exceptions occurred inside toolkit or on the communication to the VMS

                        Bitmap   bitmap = new Bitmap(320, 240);
                        Graphics g      = Graphics.FromImage(bitmap);
                        g.FillRectangle(System.Drawing.Brushes.Black, 0, 0, bitmap.Width, bitmap.Height);
                        g.DrawString("Connection lost to server ...", new Font(FontFamily.GenericMonospace, 12), Brushes.White, new PointF(20, pictureBoxOriginal.Height / 2 - 20));
                        g.Dispose();
                        pictureBoxOriginal.Image = new Bitmap(bitmap, pictureBoxOriginal.Size);
                        bitmap.Dispose();
                    }
                }
                OnMainThread = false;
            }
        }
Ejemplo n.º 12
0
        protected override void WriteDataXML(XElement ele, ElderScrollsPlugin master)
        {
            XElement subEle;

            ele.TryPathTo("Type", true, out subEle);
            subEle.Value = Type.ToString();

            ele.TryPathTo("Threshold", true, out subEle);
            subEle.Value = Threshold.ToString();

            ele.TryPathTo("Flags", true, out subEle);
            subEle.Value = Flags.ToString();

            ele.TryPathTo("Interval", true, out subEle);
            subEle.Value = Interval.ToString();

            switch (Type)
            {
            case ChallengeType.KillFromAFormList:
                ele.TryPathTo("BodyPart", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("WeaponActorValue", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.KillASpecificFormID:
                ele.TryPathTo("BodyPart", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("WeaponActorValue", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.KillAnyInACategory:
                ele.TryPathTo("BodyPart", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("CreatureType", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.HitAnEnemy:
                ele.TryPathTo("BodyPart", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("TypeOfHit", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.DiscoverAMapMarker:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.UseAnItem:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.AcquireAnItem:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.UseASkill:
                ele.TryPathTo("Result", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("Difficulty", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.DoDamage:
                ele.TryPathTo("BodyPart", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("WeaponActorValue", true, out subEle);
                subEle.Value = Value2.ToString();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.UseAnItemFromAList:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.AcquireAnItemFromAList:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.MiscellaneousStat:
                ele.TryPathTo("MiscStat", true, out subEle);
                subEle.Value = Value1.ToString();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("WeaponCategory", true, out subEle);
                subEle.Value = Value3.ToString();
                break;

            case ChallengeType.CraftUsingAnItem:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;

            case ChallengeType.ScriptedChallenge:
                ele.TryPathTo("Unused1", true, out subEle);
                subEle.Value = (Value1 as byte[]).ToBase64();

                ele.TryPathTo("Unused2", true, out subEle);
                subEle.Value = (Value2 as byte[]).ToBase64();

                ele.TryPathTo("Unused3", true, out subEle);
                subEle.Value = (Value3 as byte[]).ToBase64();
                break;
            }
        }
Ejemplo n.º 13
0
        public void Should_Consolidate_Multiple_References_To_The_Same_codepoint_from_multiple_files()
        {
            var c1 = new NCoverNode(1, 0, 1, 1, "doc", 0, false, "m", 0, "k", new Regex(".*"));
            var c2 = new NCoverNode(1, 0, 1, 1, "doc", 1, false, "m", 0, "k", new Regex(".*"));

            Threshold threshold = new Threshold(
                new NCoverResults(new INCoverNode[] {c1, c2}),
                new NCoverResults(new INCoverNode[] {c2}),
                0.0);

            Assert.AreEqual(
                "NCoverCopTask: PASSED: -- There is no newly uncovered code. \r\n\tSequence Points Summary: 1 not excluded, 1 hit\r\n\tPercentage Summary: 100.00% [Minimum Required: 100.00%]\r\n",
                threshold.Message);
        }
Ejemplo n.º 14
0
 public ConsoleLogger(Threshold threshold = Threshold.Info)
 {
     this.threshold = threshold;
 }
Ejemplo n.º 15
0
        public Bitmap Apply(Bitmap originalImage)
        {
            //reduce image size so that less, bicubic resizes with less breakage
            ResizeBicubic resizeObject       = new ResizeBicubic(200, 200);
            Bitmap        smallOriginalImage = resizeObject.Apply(originalImage);
            Bitmap        copiedImage        = (Bitmap)smallOriginalImage.Clone();

            // to get the colour of the pixel passed as parameter
            for (int x = 0; x < smallOriginalImage.Width; x++)
            {
                for (int y = 0; y < smallOriginalImage.Height; y++)
                {
                    if (!isSkin(copiedImage.GetPixel(x, y)))
                    {
                        copiedImage.SetPixel(x, y, Color.Black);
                    }
                }
            }
            copiedImage = Grayscale.CommonAlgorithms.BT709.Apply(copiedImage);
            Threshold bwObj = new Threshold(50);

            copiedImage = bwObj.Apply(copiedImage);


            //applying closing to remove small black spots(closing holes in the image) i.e dilusion followed by erosion
            AForge.Imaging.Filters.Closing filter = new Closing();
            copiedImage = filter.Apply(copiedImage);
            //pictureBox2.Image = copiedImage;

            //extracting the biggest blob or a blob to get only the palms, here we get the bounding box
            //bounding box is the smallest box having the image, hence we see only the palms
            ExtractBiggestBlob biggestblobObject = new ExtractBiggestBlob();

            copiedImage = biggestblobObject.Apply(copiedImage);



            //we need to get the coordinates of the bounding box
            IntPoint point = biggestblobObject.BlobPosition;

            //create a rectangle to pass to the crop class, it takes x,y,height,width
            Rectangle rect = new Rectangle(point.X, point.Y, copiedImage.Width, copiedImage.Height);

            Crop cropObject = new Crop(rect);

            //we pass the original image because that cohtains noise, we remove the background and have only palms
            Bitmap croppedImage = cropObject.Apply(smallOriginalImage);


            //we still have a lot of background which need to be removed as the background between the fingers have background
            //hence we do a logical and between original image and the cropped image with pixels having white pixel
            //this operation is called as masking
            for (int x = 0; x < copiedImage.Width; x++)
            {
                for (int y = 0; y < copiedImage.Height; y++)
                {
                    Color c = copiedImage.GetPixel(x, y);
                    if (c.R == 0 && c.G == 0 && c.B == 0)
                    {
                        croppedImage.SetPixel(x, y, Color.Black);
                    }
                }
            }


            //it takes time because each pixel is checked and the image is huge,
            //so we need to resize, hence we do smallOriginalImage


            //we need to resize all objects to a standard size

            croppedImage = resizeObject.Apply(croppedImage);
            //pictureBox2.Image = croppedImage;

            croppedImage = Grayscale.CommonAlgorithms.BT709.Apply(croppedImage);
            CannyEdgeDetector cannyObj = new CannyEdgeDetector(0, 0, 1.4);

            croppedImage = cannyObj.Apply(croppedImage);
            Threshold thresObj = new Threshold(20);

            croppedImage = thresObj.Apply(croppedImage);



            return(croppedImage);
        }
Ejemplo n.º 16
0
        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            Invert inv = new Invert();

            inv.ApplyInPlace(image);

            UnmanagedImage ui = UnmanagedImage.FromManagedImage(image);

            pictureBox1.Image = image;


            if (controller.Tracker.TrackingObject == null)
            {
                return;
            }

            if (controller.Tracker.TrackingObject.IsEmpty)
            {
                return;
            }

            var  rect = controller.Tracker.TrackingObject.Rectangle;
            Crop crop = new Crop(rect);

            UnmanagedImage head = crop.Apply(ui);

            var points = new List <IntPoint>()
            {
                new IntPoint(head.Width / 2, head.Height / 2)
            };
            var pps = head.Collect16bppPixelValues(points);

            double mean = Accord.Statistics.Tools.Mean(pps);

            double    cutoff = mean + 15;
            Threshold t      = new Threshold((int)cutoff);
            var       mask   = t.Apply(ui);



            LevelsLinear16bpp levels = new LevelsLinear16bpp();

            levels.InGray  = new IntRange((int)cutoff, 65535);
            levels.OutGray = new IntRange(0, 65535);
            levels.ApplyInPlace(ui);


            var mask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(mask.ToManagedImage());



            BlobCounter bc = new BlobCounter();

            bc.ObjectsOrder = ObjectsOrder.Area;
            bc.ProcessImage(mask8bit);
            var blobs = bc.GetObjectsInformation();

            inv.ApplyInPlace(image);
            Intersect intersect = new Intersect();

            intersect.UnmanagedOverlayImage = mask;
            mask = intersect.Apply(ui);

            List <Rectangle> rects = new List <Rectangle>();

            // Extract the uppermost largest blobs.
            for (int i = 0; i < blobs.Length; i++)
            {
                double dx = (blobs[i].Rectangle.Top - controller.Tracker.TrackingObject.Center.Y);
                double d  = (dx * dx) / controller.Tracker.TrackingObject.Area;
                if (d < 2 && blobs[i].Area > 1000)
                {
                    rects.Add(blobs[i].Rectangle);
                }
            }

            rects.Sort(compare);

            if (rects.Count > 0)
            {
                captureHand(mask, rects[0], pbLeftArm, pbLeftHand);
            }
            if (rects.Count > 1)
            {
                captureHand(mask, rects[1], pbRightArm, pbRightHand);
            }

            RectanglesMarker marker = new RectanglesMarker(rects);

            marker.MarkerColor = Color.White;
            marker.ApplyInPlace(mask8bit);

            image = mask.ToManagedImage();
        }
Ejemplo n.º 17
0
        private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand)
        {
            Crop c = new Crop(rect);
            var handImage = c.Apply(mask);

            var ps = handImage.Collect16bppPixelValues(handImage.CollectActivePixels());

            if (ps.Length > 0)
            {
                ushort max = Matrix.Max(ps);

                LevelsLinear16bpp levels = new LevelsLinear16bpp();
                levels.InGray = new IntRange(0, max);
                levels.OutGray = new IntRange(0, 65535);
                levels.ApplyInPlace(handImage);


               // pbArm.Image = handImage.ToManagedImage();


                double cutoff = 30000;
                Threshold th = new Threshold((int)cutoff);
                var handMask = th.Apply(handImage);

                var handMask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(handMask.ToManagedImage());

                BlobCounter bch = new BlobCounter();
                bch.ObjectsOrder = ObjectsOrder.Area;
                bch.ProcessImage(handMask8bit);
                var blob = bch.GetObjectsInformation();

                if (blob.Length > 0)
                {
                    Intersect inters = new Intersect();
                    inters.UnmanagedOverlayImage = handMask;
                    inters.ApplyInPlace(handImage);

                    Crop ch = new Crop(blob[0].Rectangle);
                    handImage = ch.Apply(handImage);

                    ResizeNearestNeighbor res = new ResizeNearestNeighbor(25, 25);
                    handImage = res.Apply(handImage);

                    var leftHand = AForge.Imaging.Image.Convert16bppTo8bpp(handImage.ToManagedImage());

                    pbHand.Image = leftHand;
                }
            }
        }
Ejemplo n.º 18
0
        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            Invert inv = new Invert();
            inv.ApplyInPlace(image);

            UnmanagedImage ui = UnmanagedImage.FromManagedImage(image);

            pictureBox1.Image = image;


            if (controller.Tracker.TrackingObject == null)
                return;

            if (controller.Tracker.TrackingObject.IsEmpty)
                return;

            var rect = controller.Tracker.TrackingObject.Rectangle;
            Crop crop = new Crop(rect);

            UnmanagedImage head = crop.Apply(ui);

            var points = new List<IntPoint>() { new IntPoint(head.Width / 2, head.Height / 2) };
            var pps = head.Collect16bppPixelValues(points);

            double mean = Accord.Statistics.Tools.Mean(pps);

            double cutoff = mean + 15;
            Threshold t = new Threshold((int)cutoff);
            var mask = t.Apply(ui);



            LevelsLinear16bpp levels = new LevelsLinear16bpp();
            levels.InGray = new IntRange((int)cutoff, 65535);
            levels.OutGray = new IntRange(0, 65535);
            levels.ApplyInPlace(ui);


            var mask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(mask.ToManagedImage());



            BlobCounter bc = new BlobCounter();
            bc.ObjectsOrder = ObjectsOrder.Area;
            bc.ProcessImage(mask8bit);
            var blobs = bc.GetObjectsInformation();

            inv.ApplyInPlace(image);
            Intersect intersect = new Intersect();
            intersect.UnmanagedOverlayImage = mask;
            mask = intersect.Apply(ui);

            List<Rectangle> rects = new List<Rectangle>();

            // Extract the uppermost largest blobs.
            for (int i = 0; i < blobs.Length; i++)
            {
                double dx = (blobs[i].Rectangle.Top - controller.Tracker.TrackingObject.Center.Y);
                double d = (dx * dx) / controller.Tracker.TrackingObject.Area;
                if (d < 2 && blobs[i].Area > 1000)
                    rects.Add(blobs[i].Rectangle);
            }

            rects.Sort(compare);

            if (rects.Count > 0)
            {
                captureHand(mask, rects[0], pbLeftArm, pbLeftHand);
            }
            if (rects.Count > 1)
            {
                captureHand(mask, rects[1], pbRightArm, pbRightHand);

            }

            RectanglesMarker marker = new RectanglesMarker(rects);
            marker.MarkerColor = Color.White;
            marker.ApplyInPlace(mask8bit);

            image = mask.ToManagedImage();
        }
Ejemplo n.º 19
0
    public ChronoJumpWindow(string progVersion, string progName, string runningFileName)
    {
        this.progVersion = progVersion;
        this.progName = progName;
        this.runningFileName = runningFileName;

        Glade.XML gxml;
        gxml = Glade.XML.FromAssembly (Util.GetGladePath() + "app1.glade", "app1", "chronojump");
        gxml.Autoconnect(this);

        //put an icon to window
        UtilGtk.IconWindow(app1);

        //show chronojump logo on down-left area
        changeTestImage("", "", "LOGO");

        //white bg
        eventbox_image_test.ModifyBg(StateType.Normal, UtilGtk.WHITE);

        //start with the Mode selector
        notebook_start.CurrentPage = 0;

        //new DialogMessage(Constants.MessageTypes.INFO, UtilGtk.ScreenHeightFitted(false).ToString() );
        //UtilGtk.ResizeIfNeeded(stats_window);

        //app1.Maximize(); //this was for starting at fullscreen

        report = new Report(-1); //when a session is loaded or created, it will change the report.SessionID value
        //TODO: check what happens if a session it's deleted
        //i think report it's deactivated until a new session is created or loaded,
        //but check what happens if report window is opened

        //put videoOn as false before loading preferences to start always without the camera
        //this is good if camera produces crash
        SqlitePreferences.Update("videoOn", "False", false);

        //preferencesLoaded is a fix to a gtk#-net-windows-bug where radiobuttons raise signals
        //at initialization of chronojump and gives problems if this signals are raised while preferences are loading
        loadPreferences ();

        createTreeView_persons (treeview_persons);

        createTreeView_jumps (treeview_jumps);
        createTreeView_jumps_rj (treeview_jumps_rj);
        createTreeView_runs (treeview_runs);
        createTreeView_runs_interval (treeview_runs_interval);
        createTreeView_reaction_times (treeview_reaction_times);
        createTreeView_pulses (treeview_pulses);
        createTreeView_multi_chronopic (false, treeview_multi_chronopic);

        createComboSelectJumps(true);
        createComboSelectJumpsRj(true);
        createComboSelectRuns(true);
        createComboSelectRunsInterval(true);

        createComboResultJumps();
        createComboResultJumpsRj();
        createComboResultRuns();
        createComboResultRunsInterval();

        //reaction_times has no combo
        createComboPulses();
        //createComboMultiChronopic();
        createdStatsWin = false;

        repetitiveConditionsWin = RepetitiveConditionsWindow.Create();
        repetitiveConditionsWin.FakeButtonClose.Clicked += new EventHandler(on_repetitive_conditions_closed);

        //createChronopicWindow(false, "");
        //wizardPortContacts = "";
        //wizardPortEncoder = "";

        on_extra_window_multichronopic_test_changed(new object(), new EventArgs());
        on_extra_window_pulses_test_changed(new object(), new EventArgs());
        on_extra_window_reaction_times_test_changed(new object(), new EventArgs());
        on_extra_window_runs_interval_test_changed(new object(), new EventArgs());
        on_extra_window_runs_test_changed(new object(), new EventArgs());
        on_extra_window_jumps_rj_test_changed(new object(), new EventArgs());
        on_extra_window_jumps_test_changed(new object(), new EventArgs());
        //changeTestImage("", "", "LOGO");

        //We have no session, mark some widgets as ".Sensitive = false"
        sensitiveGuiNoSession();
        definedSession = false;

        rand = new Random(40);

        formatModeMenu();
        putNonStandardIcons();
        eventExecutePutNonStandardIcons();
        //eventExecuteCreateComboGraphResultsSize();

        /*

        if(chronopicPort != Constants.ChronopicDefaultPortWindows &&
                (chronopicPort != Constants.ChronopicDefaultPortLinux && File.Exists(chronopicPort))
          ) {
            ConfirmWindow confirmWin = ConfirmWindow.Show(Catalog.GetString("Do you want to connect to Chronopic now?"), "", "");
            confirmWin.Button_accept.Clicked += new EventHandler(chronopicAtStart);
        }
        */

        stats_win_create();
        createdStatsWin = true;
        //stats_win_initializeSession();

        encoderInitializeStuff();

        //presentationInit();

        videoCaptureInitialize();

        //leave empty on new releases
        //string buildDate = " (2016-07-27)";
        string buildVersion = UtilAll.ReadVersionFromBuildInfo();
        label_version.Text = buildVersion;
        LogB.Information("Build version:" + buildVersion);

        LeastSquares ls = new LeastSquares();
        ls.Test();
        LogB.Information(string.Format("coef = {0} {1} {2}", ls.Coef[0], ls.Coef[1], ls.Coef[2]));

        //these are constructed only one time
        threshold = new Threshold();
        cp2016 = new Chronopic2016();

        restTime = new RestTime();
        updatingRestTimes = true;
        //GLib.Timeout.Add(5000, new GLib.TimeoutHandler(updateRestTimes)); //each 5s
        GLib.Timeout.Add(1000, new GLib.TimeoutHandler(updateRestTimes)); //each s, better for don't have problems sorting data on treeview

        /*
         * start a ping in other thread
         * http://www.mono-project.com/docs/gui/gtksharp/responsive-applications/
         * Gtk.Application.Invoke
         */
        pingThread = new Thread (new ThreadStart (pingAtStart));
        pingThread.Start();

        //moveStartTestInitial();
    }
Ejemplo n.º 20
0
 public void Message_Pass_WhenNewPercentageBeatsMinThresholdAndPreviousPercentage()
 {
     var threshold = new Threshold(_results50PercentOf4Lines, _results100Percent, 0.30);
     Assert.AreEqual("NCoverCopTask: PASSED: -- There is no newly uncovered code. \r\n\tSequence Points Summary: 3 not excluded, 3 hit\r\n\tPercentage Summary: 100.00% [Minimum Required: 50.00%]\r\n", threshold.Message);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Checks that (x-y) > threshold
        /// </summary>
        /// <remarks>Should be consistent with wilcox.test(x, y, mu=threshold, alternative="greater") from R</remarks>
        public MannWhitneyResult IsGreater(double[] x, double[] y, Threshold threshold = null)
        {
            threshold = threshold ?? RelativeThreshold.Default;
            double thresholdValue = threshold.GetValue(x);

            int n = x.Length, m = y.Length;

            if (Math.Min(n, m) < 3 || Math.Max(n, m) < 5)
            {
                return(null); // Test can't be applied
            }
            var xy = new double[n + m];

            for (int i = 0; i < n; i++)
            {
                xy[i] = x[i];
            }
            for (int i = 0; i < m; i++)
            {
                xy[n + i] = y[i] + thresholdValue;
            }
            var index = new int[n + m];

            for (int i = 0; i < n + m; i++)
            {
                index[i] = i;
            }
            Array.Sort(index, (i, j) => xy[i].CompareTo(xy[j]));

            var ranks = new double[n + m];

            for (int i = 0; i < n + m;)
            {
                int j = i;
                while (j + 1 < n + m && Math.Abs(xy[index[j + 1]] - xy[index[i]]) < 1e-9)
                {
                    j++;
                }
                double rank = (i + j + 2) / 2.0;
                for (int k = i; k <= j; k++)
                {
                    ranks[k] = rank;
                }
                i = j + 1;
            }

            double ux = 0;

            for (int i = 0; i < n + m; i++)
            {
                if (index[i] < n)
                {
                    ux += ranks[i];
                }
            }
            ux -= n * (n + 1) / 2.0;
            double uy = n * m - ux;

            if (n + m <= BinomialCoefficientHelper.MaxAcceptableN)
            {
                double pValue = 1 - PValueForSmallN(n, m, ux - 1);
                return(new MannWhitneyResult(ux, uy, pValue, threshold));
            }
            else
            {
                double mu     = n * m / 2.0;
                double su     = Math.Sqrt(n * m * (n + m + 1) / 12.0);
                double z      = (ux - mu) / su;
                double pValue = 1 - NormalDistribution.Gauss(z);
                return(new MannWhitneyResult(ux, uy, pValue, threshold));
            }
        }
Ejemplo n.º 22
0
        private void cBFilters_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bitmap pictureTransform = (Bitmap)pbChoose.Image;

            if ((string)cBFilters.SelectedItem == "HSL_Filter")
            {
                AForge.Imaging.Filters.SaturationCorrection filter = new SaturationCorrection(0.1);
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Mediana")
            {
                AForge.Imaging.Filters.Median filter = new Median();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            /*if ((string)cBFilters.SelectedItem == "Fourier_Transformation")
             * {
             * Complex[] dst = new Complex[n];
             *
             *  AForge.Math.FourierTransform filter = AForge.Math.FourierTransform.DFT();// .FromBitmap(pictureTransform);
             *  Bitmap newImage = filter.Apply();
             *  pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
             *  pBNew.Image = newImage;
             * }*/

            if ((string)cBFilters.SelectedItem == "Binarization")
            {
                pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                Threshold threshold = new Threshold(127);
                threshold.ApplyInPlace(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = pictureTransform;
            }

            if ((string)cBFilters.SelectedItem == "Grayscale")
            {
                AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "FillHoles")
            {
                pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                Threshold threshold = new Threshold(127);
                threshold.ApplyInPlace(pictureTransform);
                AForge.Imaging.Filters.FillHoles filter = new AForge.Imaging.Filters.FillHoles();
                filter.MaxHoleHeight        = 5;
                filter.MaxHoleWidth         = 15;
                filter.CoupledSizeFiltering = false;
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Opening")
            {
                AForge.Imaging.Filters.Opening filter = new AForge.Imaging.Filters.Opening();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Closing")
            {
                AForge.Imaging.Filters.Closing filter = new AForge.Imaging.Filters.Closing();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Erosion")
            {
                AForge.Imaging.Filters.Erosion filter = new AForge.Imaging.Filters.Erosion();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Dilatation")
            {
                AForge.Imaging.Filters.Dilatation filter = new AForge.Imaging.Filters.Dilatation();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }

            if ((string)cBFilters.SelectedItem == "Edges")
            {
                AForge.Imaging.Filters.Edges filter = new AForge.Imaging.Filters.Edges();
                Bitmap newImage = filter.Apply(pictureTransform);
                pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                pBNew.Image       = newImage;
            }
        }
Ejemplo n.º 23
0
        public string GetKpiData(BoundLevel pLevel, List <KPIFlatDataItem> pKpiDataInfo, string pKpiLabelPrefix, string pKpiLabelSuffix, DataValueFormat pDataValueFormat, string pStyleCode, string pStyleSubCode)
        {
            Color[] pFlatColors = GetRenderColors(pStyleCode, pStyleSubCode);
            pKpiDataInfo.Sort(KpiDataCompare);
            double dMinValue = 0;// Convert.ToDouble(pKpiDataInfo[0].KPIData);

            for (int i = 0; i < pKpiDataInfo.Count; i++)
            {
                if (pKpiDataInfo[i].KPIData != null)
                {
                    dMinValue = Convert.ToDouble(pKpiDataInfo[i].KPIData);
                    break;
                }
            }
            double dMaxValue = Convert.ToDouble(pKpiDataInfo[pKpiDataInfo.Count - 1].KPIData);

            List <Threshold> lstThreshold = new List <Threshold>();
            //分成5段
            double dInterval = (dMaxValue - dMinValue) / 5.0;

            if (dInterval < 0.01 && dInterval > 0)//最小间隔为0.1
            {
                dInterval = 0.01;
            }

            Threshold            threshold1       = new Threshold();
            List <ThresholdItem> lstThresholdItem = new List <ThresholdItem>();

            for (int i = 0; i < 5; i++)
            {
                double startValue;
                double endValue;
                if (i == 0)
                {//起始值使用最小值
                    startValue = dMinValue;
                }
                else
                {
                    startValue = dMinValue + dInterval * i;
                }
                if (i == 4)
                {//结束值使用最大值
                    endValue = dMaxValue;
                }
                else
                {
                    endValue = dMinValue + dInterval * (i + 1);
                }
                if (startValue == 0 && endValue == 0)//忽略无数据的KPI
                {
                    continue;
                }
                string startLabel = KPIBuilderUtils.GetFormatedValue(startValue.ToString(), pDataValueFormat);
                string endLabel   = KPIBuilderUtils.GetFormatedValue(endValue.ToString(), pDataValueFormat);
                //阀值处理
                ThresholdItem thresholdItem = new ThresholdItem();
                if (pFlatColors.Length > i)
                {
                    thresholdItem.color = System.Drawing.ColorTranslator.ToHtml(pFlatColors[i]).Replace("#", "0x");
                }
                else
                {
                    thresholdItem.color = "0xFF0000";
                }
                thresholdItem.start = startValue.ToString();
                thresholdItem.end   = endValue.ToString();
                if ((pDataValueFormat & DataValueFormat.Int) != 0)
                {
                    if (thresholdItem.start.IndexOf(".") > -1)
                    {
                        thresholdItem.start = thresholdItem.start.Substring(0, thresholdItem.start.IndexOf("."));
                    }
                    if (thresholdItem.end.IndexOf(".") > -1)
                    {
                        thresholdItem.end = thresholdItem.end.Substring(0, thresholdItem.end.IndexOf("."));
                    }
                }
                thresholdItem.startlabel = startLabel;
                thresholdItem.endlabel   = endLabel;
                thresholdItem.size       = (20 + i * 2).ToString();
                if (Convert.ToDouble(thresholdItem.start) >= dMaxValue && lstThresholdItem.Count > 0)
                {
                    continue;//由于误差原因,可能超过最大值。
                }
                lstThresholdItem.Add(thresholdItem);
            }
            //删除重复的分段阀值
            List <ThresholdItem> lstNewThresholdItem = new List <ThresholdItem>();

            lstNewThresholdItem.Add(lstThresholdItem[0]);
            for (int i = 1; i < lstThresholdItem.Count; i++)
            {
                if (lstThresholdItem[i - 1].start != lstThresholdItem[i].start || lstThresholdItem[i - 1].end != lstThresholdItem[i].end)
                {
                    lstNewThresholdItem.Add(lstThresholdItem[i]);
                }
            }
            threshold1.threshold = lstNewThresholdItem.ToArray();
            if (pStyleCode.ToUpper() == "SB")
            {
                threshold1.type = "3";
                //气泡渲染要添加透明效果
                foreach (var item in threshold1.threshold)
                {
                    item.alpha = "0.8";
                }

                threshold1.defaultalpha = "0.8";
            }
            else
            {
                threshold1.type = "1";
            }
            threshold1.level        = ((int)pLevel).ToString();
            threshold1.defaultcolor = "0xFFFFFF";
            threshold1.defaultimage = "";
            threshold1.defaultsize  = "20";
            threshold1.defaulttext  = "无数据";
            lstThreshold.Add(threshold1);

            //计算气泡大小
            var lstData = new List <KPIFlatData>();

            foreach (var kpiDataItem in pKpiDataInfo)
            {
                //过滤无效的数据
                if (string.IsNullOrWhiteSpace(kpiDataItem.KPIData) || kpiDataItem.Ignore)
                {
                    continue;
                }
                //lstThreshold
                double dValue = Convert.ToDouble(kpiDataItem.KPIData);
                //过滤太小的数值
                //if (dValue < 0.01)
                //    continue;
                //省市县KPI
                KPIFlatData kpiData = new KPIFlatData();
                if (!string.IsNullOrWhiteSpace(kpiDataItem.DataID))
                {
                    kpiData.id = kpiDataItem.DataID;
                }
                kpiData.kpi      = kpiDataItem.KPIData;
                kpiData.kpilabel = KPIBuilderUtils.GetFormatedValue(kpiData.kpi, pDataValueFormat);
                kpiData.kpimark  = kpiData.kpilabel;
                if (!string.IsNullOrWhiteSpace(pKpiLabelPrefix))
                {
                    kpiData.kpilabel = pKpiLabelPrefix + kpiData.kpilabel;
                }

                if (!string.IsNullOrWhiteSpace(pKpiLabelSuffix))
                {
                    kpiData.kpilabel = kpiData.kpilabel + pKpiLabelSuffix;
                }
                lstData.Add(kpiData);
            }
            KPIInformation jsonKpiData = new KPIInformation();

            jsonKpiData.Data       = lstData.ToArray();
            jsonKpiData.Thresholds = lstThreshold.ToArray();
            return(jsonKpiData.ToJSON());
        }
Ejemplo n.º 24
0
            public void ShouldReturnSingleValueWhenOnlyMimimumIsSet()
            {
                var point = new Threshold(1.2);

                Assert.Equal("1.2", point.ToString());
            }
Ejemplo n.º 25
0
    /* Find a path from the agent's starting location to the desired goal
     * location. This uses the HPA* algorithm.
     * Input: start location, goal location.
     * Output: the calculated path as a list of cells the agent must visit to
     * get to the goal.
     */
    private List <Cell> FindHPAPath(Vector3 start, Vector3 goal)
    {
        //setups
        hasFoundPath      = false;
        isCalculatingPath = true;
        List <Cell> finalPath = new List <Cell>();


        //check if the start is already in the same zone as the goal
        Cell startCell = map.CellFromWorldPos(start);
        Cell goalCell  = map.CellFromWorldPos(goal);

        if (map.GetZone(startCell.zoneId).zoneId == map.GetZone(goalCell.zoneId).zoneId)
        {
            //simply use the find cell path function to get to the goal
            List <Cell> tmp = FindCellPath(startCell, goalCell);
            finalPath.AddRange(tmp);
            pathToTake        = finalPath;
            hasFoundPath      = true;
            isCalculatingPath = false;
            return(finalPath);
        }

        //add the start position and the goal position to the threshold graph
        //by finding which threshold is close to the two positions.
        Threshold thresholdStart = FindNeartestThreshold(start, goal);
        Threshold thresholdGoal  = FindNeartestThreshold(goal, start);

        //find a path of thresholds starting from thresholdStart and to thresholdGoal.
        List <Threshold> thresholdPath = FindThresholdPath(thresholdStart, thresholdGoal);

        tpathToTake = thresholdPath;

        //using all these thresholds, find a path to the goal from the start with the help of astar.
        //path from start threshold to between threshold.
        Cell        nextGoal = map.CellFromThreshold(thresholdStart);
        List <Cell> temp     = FindCellPath(startCell, nextGoal);

        finalPath.AddRange(temp);

        //path between the thresholds.
        for (int i = 1; i < thresholdPath.Count; i++)
        {
            //get the last position from the final path, this will be the new "start."
            Cell newStart = map.CellFromThreshold(thresholdPath[i - 1]);

            //the threshold will be the new goal.
            Cell newGoal = map.CellFromThreshold(thresholdPath[i]);

            temp = FindCellPath(newStart, newGoal);

            //add this path to the finalpath.
            finalPath.AddRange(temp);
        }
        //path from final threshold to goal.
        nextGoal = map.CellFromThreshold(thresholdPath[thresholdPath.Count - 1]);
        temp     = FindCellPath(nextGoal, goalCell);
        finalPath.AddRange(temp);

        //done!
        pathToTake        = finalPath;
        hasFoundPath      = true;
        isCalculatingPath = false;
        return(finalPath);
    }
Ejemplo n.º 26
0
    /* Same as above, but for thresholds.
     */
    private float GetThresholdHeuristic(Threshold source, Threshold sink)
    {
        float h = Vector3.Distance(source.worldPosition, sink.worldPosition);

        return(h);
    }
Ejemplo n.º 27
0
 public TraceLogger(Threshold threshold = Threshold.Info)
 {
     this.threshold = threshold;
 }
Ejemplo n.º 28
0
    /* Give the cell at the current threshold position
     * Input: threshold
     * Output: cell at that threshold
     */
    public Cell CellFromThreshold(Threshold threshold)
    {
        float xpos = threshold.worldPosition.x;
        float zpos = threshold.worldPosition.z;

        int z = 0;
        int x = 0;

        //search for the cell with the same z position.
        int t = 0;
        int b = grid.GetLength(0) - 1;

        while (t <= b)
        {
            int m = (int)Mathf.Floor((t + b) / 2);


            //round up the z component of the world position so it matches with the Vector3

            if (Mathf.Approximately(grid[m, 0].worldPosition.z, zpos))
            {
                z = m;
                break;
            }

            if (grid[m, 0].worldPosition.z > zpos)
            {
                t = m + 1;
            }
            else
            {
                b = m - 1;
            }
        }

        //now, search for the cell with the same x position.
        int l = 0;
        int r = grid.GetLength(1) - 1;

        while (l <= r)
        {
            int m = (int)Mathf.Floor((l + r) / 2);


            if (Mathf.Approximately(grid[z, m].worldPosition.x, xpos))
            {
                x = m;
                break;
            }

            if (grid[z, m].worldPosition.x < xpos)
            {
                l = m + 1;
            }

            else
            {
                r = m - 1;
            }
        }

        Cell c = grid[z, x];

        return(c);
    }
Ejemplo n.º 29
0
        public static Threshold ThresholdCalc(Trend uNewTrend, double curMid, double curPercent, double curLowThreshold, double curHighThreshold)
        {
            Threshold retThreshold = new Threshold();

            if (NoTrendEvent(uNewTrend))
            {
                if (uNewTrend.newTrend == iTREND_UP)
                {
                    retThreshold.newHighThreshold = curHighThreshold;
                    retThreshold.newLowThreshold = Math.Max(curLowThreshold, curMid * (1 - curPercent));
                }
                else  // this is newtrend == trend_down
                {
                    retThreshold.newLowThreshold = curLowThreshold;
                    retThreshold.newHighThreshold = Math.Min(curHighThreshold, curMid * (1 + curPercent));
                }
            }
            else
            {
                retThreshold.newLowThreshold = curMid * (1 - curPercent);
                retThreshold.newHighThreshold = curMid * (1 + curPercent);
            }
            return retThreshold;
        }
Ejemplo n.º 30
0
        private static Node split(List <int> indices, int NCount, Hyperrectangle <float> bounds)
        {
            _depth++;
            int YCount = indices.Count;

            if (YCount <= MinY)
            {
                _depth--;
                return(new Node {
                    NodeType = NodeType.Leaf, Y = YCount, N = NCount, Bounds = bounds
                });
            }

            if (NCount < YCount)
            {
                NCount = YCount;
            }

            int length = _numFeatures;

            float min, max;

            Dictionary <Threshold, float> thresholds = new Dictionary <Threshold, float>();

            float[] values = new float[YCount];

            for (int i = 0; i < length; i++)
            {
                float[] featureValues = _featureValues[i];
                for (int j = 0; j < YCount; j++)
                {
                    values[j] = featureValues[indices[j]];
                }
                Array.Sort <float>(values);

                min = bounds.MinimumBound[i];
                max = bounds.MaximumBound[i];

                Threshold cut1 = findCut(new Region {
                    Min = min, Max = max, YCount = YCount, NCount = NCount
                }, values);

                if (cut1 == null)
                {
                    continue;
                }

                Region r0 = new Region {
                    Min = min, Max = cut1.Value, IncludeLeft = true, IncludeRight = cut1.IsInclusive
                };
                Region r1 = new Region {
                    Min = cut1.Value, Max = max, IncludeLeft = !cut1.IsInclusive, IncludeRight = true
                };
                r0.CalculateCounts(values, min, max, NCount);
                r1.CalculateCounts(values, min, max, NCount);

                Region  L       = r0.RelativeDensity < r1.RelativeDensity ? r0 : r1;
                float[] LValues = L.Limit(values);
                if (LValues.Length == 0)
                {
                    cut1.Dimension   = i;
                    cut1.Feature     = _buildFeatures[i];
                    thresholds[cut1] = L.RelativeDensity;
                    continue;
                }

                Threshold cut2 = findCut(L, LValues);

                if (cut2 == null)
                {
                    continue;
                }

                if (L == r0)
                {
                    r0 = new Region {
                        Min = r0.Min, Max = cut2.Value, IncludeLeft = true, IncludeRight = cut2.IsInclusive
                    };
                    r1 = new Region {
                        Min = cut2.Value, Max = cut1.Value, IncludeLeft = !cut2.IsInclusive, IncludeRight = cut1.IsInclusive
                    };
                    r0.CalculateCounts(values, min, max, NCount);
                    r1.CalculateCounts(values, min, max, NCount);
                    if (r1.RelativeDensity > r0.RelativeDensity)
                    {
                        cut2.Dimension   = i;
                        cut2.Feature     = _buildFeatures[i];
                        thresholds[cut2] = r0.RelativeDensity;
                        continue;
                    }
                }
                else
                {
                    r0 = new Region {
                        Min = cut1.Value, Max = cut2.Value, IncludeLeft = !cut1.IsInclusive, IncludeRight = cut2.IsInclusive
                    };
                    r1 = new Region {
                        Min = cut2.Value, Max = r1.Max, IncludeLeft = !cut2.IsInclusive, IncludeRight = true
                    };
                    r0.CalculateCounts(values, min, max, NCount);
                    r1.CalculateCounts(values, min, max, NCount);
                    if (r0.RelativeDensity > r1.RelativeDensity)
                    {
                        cut2.Dimension   = i;
                        cut2.Feature     = _buildFeatures[i];
                        thresholds[cut2] = r1.RelativeDensity;
                        continue;
                    }
                }

                L       = r0.RelativeDensity < r1.RelativeDensity ? r0 : r1;
                LValues = L.Limit(LValues);
                if (LValues.Length == 0)
                {
                    continue;
                }

                Threshold cut3 = findCut(L, LValues);

                if (cut3 == null)
                {
                    continue;
                }

                if (cut1.Value < cut3.Value)
                {
                    r0 = new Region {
                        Min = cut1.Value, Max = cut3.Value, IncludeLeft = !cut1.IsInclusive, IncludeRight = cut3.IsInclusive
                    }
                }
                ;
                else
                {
                    r0 = new Region {
                        Min = cut3.Value, Max = cut1.Value, IncludeLeft = !cut3.IsInclusive, IncludeRight = cut1.IsInclusive
                    }
                };
                if (cut2.Value < cut3.Value)
                {
                    r1 = new Region {
                        Min = cut2.Value, Max = cut3.Value, IncludeLeft = !cut2.IsInclusive, IncludeRight = cut3.IsInclusive
                    }
                }
                ;
                else
                {
                    r1 = new Region {
                        Min = cut3.Value, Max = cut2.Value, IncludeLeft = !cut3.IsInclusive, IncludeRight = cut2.IsInclusive
                    }
                };
                r0.CalculateCounts(values, min, max, NCount);
                r1.CalculateCounts(values, min, max, NCount);
                cut3.Feature     = _buildFeatures[i];
                cut3.Dimension   = i;
                thresholds[cut3] = Math.Min(r0.RelativeDensity, r1.RelativeDensity);
            }

            values = null;

            if (thresholds.Count() == 0)
            {
                _depth--;
                return(new Node {
                    NodeType = NodeType.Leaf, Y = YCount, N = NCount, Bounds = bounds
                });
            }

            Threshold best = thresholds.OrderBy(o => o.Value).First().Key;

            List <int> left  = new List <int>();
            List <int> right = new List <int>();

            values = _featureValues[best.Dimension];
            foreach (int index in indices)
            {
                float value = values[index];
                if (best.IsLeft(value))
                {
                    left.Add(index);
                }
                else
                {
                    right.Add(index);
                }
            }

            UpdateManager.WriteLine("Splitting at {0}: {1} {2}", best, left.Count, right.Count);

            min = bounds.MinimumBound[best.Dimension];
            max = bounds.MaximumBound[best.Dimension];
            Hyperrectangle <float> leftBounds  = (Hyperrectangle <float>)bounds.Clone();
            Hyperrectangle <float> rightBounds = (Hyperrectangle <float>)bounds.Clone();

            leftBounds.MaximumBound[best.Dimension]  = best.Value;
            rightBounds.MinimumBound[best.Dimension] = best.Value;
            int  leftNCount = (int)(((best.Value - min) * NCount) / (max - min));
            Node node       = new Node {
                Threshold = best, NodeType = NodeType.Branch, Y = YCount, N = NCount, Bounds = bounds
            };

            node.Left  = split(left, leftNCount, leftBounds);
            node.Right = split(right, NCount - leftNCount, rightBounds);
            _depth--;
            return(node);
        }
    }
}
Ejemplo n.º 31
0
        public static void AggregateHistoricalData(object unused)
        {
            DateTime currentTime = DateTime.UtcNow;

            // We'll check the hour aggregation, since the day aggregation can only be triggered when the hour one is also triggered
            if (s_lastHourAggregation < (currentTime.AddHours(-1)))
            {
                lock (s_lockObject)
                {
                    if (s_lastHourAggregation < (currentTime.AddHours(-1)))
                    {
                        DateTime hourFloorTime = RoundDownToHour(currentTime);

                        const string c_selectSensorData = "SELECT ComponentSensorID,Date,Value FROM SensorData WHERE Date < @minTime ORDER BY ComponentSensorID ASC, Date ASC";

                        using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlSelectCommand.CommandText = c_selectSensorData;
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@minTime", hourFloorTime.AddHours(-1)));

                            using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                            {
                                long currentComponentSensorId = -1;
                                DateTime currentHourCutoff = DateTime.MinValue;

                                DateTime currentHour = DateTime.MinValue;
                                double sum = 0;
                                double max = 0;
                                double min = 0;
                                double sumOfSquares = 0;
                                long count = 0;

                                while (reader.Read())
                                {
                                    long componentSensorId = Convert.ToInt64(reader["ComponentSensorID"]);
                                    DateTime measureTime = Convert.ToDateTime(reader["Date"]);
                                    double measure = Convert.ToDouble(reader["Value"]);

                                    if (currentComponentSensorId != componentSensorId ||
                                        measureTime > currentHourCutoff)
                                    {
                                        // We don't want to save anything back if we're setting up
                                        if (currentComponentSensorId != -1)
                                        {
                                            InsertHistoricalData(currentComponentSensorId,
                                                currentHour,
                                                DateRangeType.hour,
                                                count,
                                                sum,
                                                sumOfSquares,
                                                min,
                                                max);
                                        }

                                        // Reset our aggregation
                                        currentComponentSensorId = componentSensorId;
                                        currentHour = RoundDownToHour(measureTime);
                                        currentHourCutoff = currentHour.AddHours(1);
                                        max = measure;
                                        min = measure;
                                        count = 0;
                                        sum = 0;
                                        sumOfSquares = 0;
                                    }

                                    max = Math.Max(max, measure);
                                    min = Math.Min(min, measure);
                                    count++;
                                    sum += measure;
                                    sumOfSquares += (measure * measure);
                                }

                                // Save the last set of measures. We don't want to save anything back if we're setting up
                                if (currentComponentSensorId != -1)
                                {
                                    InsertHistoricalData(currentComponentSensorId,
                                        currentHour,
                                        DateRangeType.hour,
                                        count,
                                        sum,
                                        sumOfSquares,
                                        min,
                                        max);
                                }
                            }
                        }

                        const string c_deleteSensorData = "DELETE FROM SensorData WHERE Date < @minTime";
                        using (SQLiteCommand sqlDeleteCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlDeleteCommand.CommandText = c_deleteSensorData;

                            // Always make sure we have one full hour of full resolution
                            sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@minTime", hourFloorTime.AddHours(-1)));

                            sqlDeleteCommand.ExecuteNonQuery();
                        }

                        s_lastHourAggregation = hourFloorTime;
                    }

                    if (s_lastDayAggregation < (currentTime.AddDays(-1)))
                    {
                        DateTime dayFloorTime = RoundDownToDay(currentTime);

                        const string c_selecttHistoricalData = "SELECT ComponentSensorID,Date,Count,Sum,SumOfSquares,Min,Max FROM HistoricalAggregation WHERE Date < @date AND DateRange = @dateRange ORDER BY ComponentSensorID ASC, Date ASC";

                        // If the row already exists, we need to add the data together
                        using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlSelectCommand.CommandText = c_selecttHistoricalData;
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@date", dayFloorTime.AddDays(-1)));
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@dateRange", DateRangeType.hour));

                            using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                            {
                                long currentComponentSensorId = -1;
                                DateTime currentDayCutoff = DateTime.MinValue;

                                DateTime currentDay = DateTime.MinValue;
                                double sum = 0;
                                double max = 0;
                                double min = 0;
                                double sumOfSquares = 0;
                                long count = 0;

                                while (reader.Read())
                                {
                                    long componentSensorId = Convert.ToInt64(reader["ComponentSensorID"]);
                                    DateTime measureTime = Convert.ToDateTime(reader["Date"]);

                                    if (currentComponentSensorId != componentSensorId ||
                                        measureTime > currentDayCutoff)
                                    {
                                        // We don't want to save anything back if we're setting up
                                        if (currentComponentSensorId != -1)
                                        {
                                            InsertHistoricalData(currentComponentSensorId,
                                                currentDay,
                                                DateRangeType.day,
                                                count,
                                                sum,
                                                sumOfSquares,
                                                min,
                                                max);
                                        }

                                        // Reset our aggregation
                                        currentComponentSensorId = componentSensorId;
                                        currentDay = RoundDownToDay(measureTime);
                                        currentDayCutoff = currentDay.AddHours(1);
                                        max = Convert.ToDouble(reader["Max"]);
                                        min = Convert.ToDouble(reader["Min"]);
                                        count = 0;
                                        sum = 0;
                                        sumOfSquares = 0;
                                    }

                                    count += Convert.ToInt64(reader["Count"]);
                                    sum += Convert.ToDouble(reader["Sum"]);
                                    sumOfSquares += Convert.ToDouble(reader["SumOfSquares"]);
                                    double tempMin = Convert.ToDouble(reader["Min"]);
                                    min = Math.Min(min, tempMin);
                                    double tempMax = Convert.ToDouble(reader["Max"]);
                                    max = Math.Max(max, tempMax);
                                }

                                // Save the last set of measures. We don't want to save anything back if we're setting up
                                if (currentComponentSensorId != -1)
                                {
                                    InsertHistoricalData(currentComponentSensorId,
                                        currentDay,
                                        DateRangeType.day,
                                        count,
                                        sum,
                                        sumOfSquares,
                                        min,
                                        max);
                                }
                            }
                        }

                        List<AggregateContainer> dataToSendToServer = new List<AggregateContainer>();
                        DateTime lastWatermark = DateTime.MinValue;

                        // NOTE: SQL does not support "TOP 1", so we'll just read one
                        const string c_selecttWatermark = "SELECT Date FROM Watermarks WHERE WatermarkId = @watermarkId ORDER BY Date DESC";

                        // If the row already exists, we need to add the data together
                        using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlSelectCommand.CommandText = c_selecttWatermark;
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@watermarkId", "ServerWatermark"));

                            using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    lastWatermark = Convert.ToDateTime(reader["Date"]);

                                    // Go ahead and add one day so we don't resend data
                                    lastWatermark = lastWatermark.AddDays(1);
                                }
                            }
                        }

                        const string c_selecttHistoricalData1 =
                            @"SELECT ha.ComponentSensorId,Name,Type,SensorTypeId,Date,Count,Sum,SumOfSquares,Min,Max
                             FROM HistoricalAggregation ha
                             JOIN ComponentSensor cs
                             ON cs.ComponentSensorId = ha.ComponentSensorId
                             JOIN ComputerComponent cc
                             ON cs.ComputerComponentId = cc.ComputerComponentId
                             JOIN Component ct
                             ON ct.ComponentId = cc.ComponentId
                             WHERE Date <= @maxDate
                               AND DateRange = @dateRange
                             ORDER BY Date ASC";

                        Dictionary<long, SensorReading> readings = new Dictionary<long, SensorReading>();

                        // If the row already exists, we need to add the data together
                        using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlSelectCommand.CommandText = c_selecttHistoricalData1;
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@maxDate", dayFloorTime.AddDays(-1)));
                            sqlSelectCommand.Parameters.Add(new SQLiteParameter("@dateRange", DateRangeType.day));

                            using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    AggregateContainer container = new AggregateContainer();

                                    long componentSensorId = Convert.ToInt64(reader["ComponentSensorId"]);
                                    long sensorType = Convert.ToInt64(reader["SensorTypeId"]);
                                    container.SensorType = (SensorType)sensorType;
                                    container.Name = Convert.ToString(reader["Name"]);
                                    container.Type = Convert.ToString(reader["Type"]);
                                    container.CurrentDay = Convert.ToDateTime(reader["Date"]);
                                    container.Count = Convert.ToInt64(reader["Count"]);
                                    container.Sum = Convert.ToDouble(reader["Sum"]);
                                    container.SumOfSquares = Convert.ToDouble(reader["SumOfSquares"]);
                                    container.Min = Convert.ToDouble(reader["Min"]);
                                    container.Max = Convert.ToDouble(reader["Max"]);

                                    SensorReading sensorReading;
                                    if (!readings.TryGetValue(componentSensorId, out sensorReading))
                                    {
                                        sensorReading = new SensorReading();
                                        readings[componentSensorId] = sensorReading;
                                    }

                                    sensorReading.Count += container.Count;
                                    sensorReading.Sum += container.Sum;
                                    sensorReading.SumOfSquares += container.SumOfSquares;

                                    if (container.CurrentDay > lastWatermark)
                                    {
                                        dataToSendToServer.Add(container);
                                    }
                                }
                            }
                        }

                        Dictionary<long, Threshold> thresholds = new Dictionary<long, Threshold>();

                        foreach (long key in readings.Keys)
                        {
                            SensorReading reading = readings[key];
                            double average = (double)reading.Sum / reading.Count;
                            double stddev = Math.Sqrt((reading.SumOfSquares / reading.Count) - (average * average));
                            Threshold threshold = new Threshold();
                            threshold.LowerThreshold = ThresholdMultiplier*(average - stddev);
                            threshold.UpperThreshold = ThresholdMultiplier*(average + stddev);
                            thresholds[key] = threshold;
                        }

                        // Atomically replace
                        Thresholds = thresholds;

                        bool sendToServerSuccess = s_httpClient.SendToServer(dataToSendToServer);

                        if (sendToServerSuccess)
                        {
                            List<DataManager.ComponentSensorTypesContainer> componentSensorList = GetComponentSensorList();
                            AggregatedData = s_httpClient.GetAggregatedStats(componentSensorList);
                            if (lastWatermark > DateTime.MinValue)
                            {
                                const string c_insertNewWatermark = "UPDATE Watermarks SET Date = @date WHERE WatermarkId = @watermarkId";
                                using (SQLiteCommand command = new SQLiteCommand(s_dataManager._sqliteConnection))
                                {
                                    command.CommandText = c_insertNewWatermark;
                                    command.Parameters.Add(new SQLiteParameter("@watermarkId", "ServerWatermark"));
                                    command.Parameters.Add(new SQLiteParameter("@date", dayFloorTime.AddDays(-1)));
                                    command.ExecuteNonQuery();
                                }
                            }
                            else
                            {
                                const string c_insertNewWatermark = "INSERT INTO Watermarks (WatermarkId,Date) values (@watermarkId,@date)";
                                using (SQLiteCommand command = new SQLiteCommand(s_dataManager._sqliteConnection))
                                {
                                    command.CommandText = c_insertNewWatermark;
                                    command.Parameters.Add(new SQLiteParameter("@watermarkId", "ServerWatermark"));
                                    command.Parameters.Add(new SQLiteParameter("@date", dayFloorTime.AddDays(-1)));
                                    command.ExecuteNonQuery();
                                }
                            }
                        }

                        const string c_deleteSensorData = "DELETE FROM HistoricalAggregation WHERE Date < @date AND DateRange = @dateRange";
                        using (SQLiteCommand sqlDeleteCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                        {
                            sqlDeleteCommand.CommandText = c_deleteSensorData;

                            // Always make sure we have one full day of hour resolution
                            sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@date", dayFloorTime.AddDays(-1)));
                            sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@dateRange", DateRangeType.hour));

                            sqlDeleteCommand.ExecuteNonQuery();
                        }

                        s_lastDayAggregation = dayFloorTime;

                    }
                }
            }
        }
Ejemplo n.º 32
0
    /* Same as above, but for thresholds.
     */
    private float GetThresholdCost(Threshold source, Threshold sink)
    {
        float cost = Vector3.Distance(source.worldPosition, sink.worldPosition);

        return(cost);
    }
        //private Collection<DetectionPoint> loadMockedDetectionPoints() {
        private HashSet<DetectionPoint> loadMockedDetectionPoints() {
            //Collection<DetectionPoint> configuredDetectionPoints = new Collection<DetectionPoint>();
            HashSet<DetectionPoint> configuredDetectionPoints = new HashSet<DetectionPoint>();

            Interval minutes5 = new Interval(5, Interval.MINUTES);
            Interval minutes6 = new Interval(6, Interval.MINUTES);
            Interval minutes7 = new Interval(7, Interval.MINUTES);
            Interval minutes8 = new Interval(8, Interval.MINUTES);
            Interval minutes11 = new Interval(11, Interval.MINUTES);
            Interval minutes12 = new Interval(12, Interval.MINUTES);
            Interval minutes13 = new Interval(13, Interval.MINUTES);
            Interval minutes14 = new Interval(14, Interval.MINUTES);
            Interval minutes15 = new Interval(15, Interval.MINUTES);
            Interval minutes31 = new Interval(31, Interval.MINUTES);
            Interval minutes32 = new Interval(32, Interval.MINUTES);
            Interval minutes33 = new Interval(33, Interval.MINUTES);
            Interval minutes34 = new Interval(34, Interval.MINUTES);
            Interval minutes35 = new Interval(35, Interval.MINUTES);

            Threshold events3minutes5 = new Threshold(3, minutes5);
            Threshold events12minutes5 = new Threshold(12, minutes5);
            Threshold events13minutes6 = new Threshold(13, minutes6);
            Threshold events14minutes7 = new Threshold(14, minutes7);
            Threshold events15minutes8 = new Threshold(15, minutes8);

            Response log = new Response();
            log.setAction("log");

            Response logout = new Response();
            logout.setAction("logout");

            Response disableUser = new Response();
            disableUser.setAction("disableUser");

            Response disableComponentForSpecificUser31 = new Response();
            disableComponentForSpecificUser31.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser31.setInterval(minutes31);

            Response disableComponentForSpecificUser32 = new Response();
            disableComponentForSpecificUser32.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser32.setInterval(minutes32);

            Response disableComponentForSpecificUser33 = new Response();
            disableComponentForSpecificUser33.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser33.setInterval(minutes33);

            Response disableComponentForSpecificUser34 = new Response();
            disableComponentForSpecificUser34.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser34.setInterval(minutes34);

            Response disableComponentForSpecificUser35 = new Response();
            disableComponentForSpecificUser35.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser35.setInterval(minutes35);

            Response disableComponentForAllUsers11 = new Response();
            disableComponentForAllUsers11.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers11.setInterval(minutes11);

            Response disableComponentForAllUsers12 = new Response();
            disableComponentForAllUsers12.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers12.setInterval(minutes12);

            Response disableComponentForAllUsers13 = new Response();
            disableComponentForAllUsers13.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers13.setInterval(minutes13);

            Response disableComponentForAllUsers14 = new Response();
            disableComponentForAllUsers14.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers14.setInterval(minutes14);

            Response disableComponentForAllUsers15 = new Response();
            disableComponentForAllUsers15.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers15.setInterval(minutes15);

            Collection<Response> point1Responses = new Collection<Response>();
            point1Responses.Add(log);
            point1Responses.Add(logout);
            point1Responses.Add(disableUser);
            point1Responses.Add(disableComponentForSpecificUser31);
            point1Responses.Add(disableComponentForAllUsers11);

            DetectionPoint point1 = new DetectionPoint("IE1", events3minutes5, point1Responses);

            Collection<Response> point2Responses = new Collection<Response>();
            point2Responses.Add(log);
            point2Responses.Add(logout);
            point2Responses.Add(disableUser);
            point2Responses.Add(disableComponentForSpecificUser32);
            point2Responses.Add(disableComponentForAllUsers12);

            DetectionPoint point2 = new DetectionPoint("IE2", events12minutes5, point2Responses);

            Collection<Response> point3Responses = new Collection<Response>();
            point3Responses.Add(log);
            point3Responses.Add(logout);
            point3Responses.Add(disableUser);
            point3Responses.Add(disableComponentForSpecificUser33);
            point3Responses.Add(disableComponentForAllUsers13);

            DetectionPoint point3 = new DetectionPoint("IE3", events13minutes6, point3Responses);

            Collection<Response> point4Responses = new Collection<Response>();
            point4Responses.Add(log);
            point4Responses.Add(logout);
            point4Responses.Add(disableUser);
            point4Responses.Add(disableComponentForSpecificUser34);
            point4Responses.Add(disableComponentForAllUsers14);

            DetectionPoint point4 = new DetectionPoint("IE4", events14minutes7, point4Responses);

            Collection<Response> point5Responses = new Collection<Response>();
            point5Responses.Add(log);
            point5Responses.Add(logout);
            point5Responses.Add(disableUser);
            point5Responses.Add(disableComponentForSpecificUser35);
            point5Responses.Add(disableComponentForAllUsers15);

            DetectionPoint point5 = new DetectionPoint("IE5", events15minutes8, point5Responses);

            configuredDetectionPoints.Add(point1);
            configuredDetectionPoints.Add(point2);
            configuredDetectionPoints.Add(point3);
            configuredDetectionPoints.Add(point4);
            configuredDetectionPoints.Add(point5);

            return configuredDetectionPoints;
        }
Ejemplo n.º 34
0
            public void ShouldReturnFalseWhenInstanceIsNull()
            {
                var point = new Threshold(50.0);

                Assert.False(point.Equals(null));
            }
Ejemplo n.º 35
0
		public ConsoleLogger(Type typeToLog, Threshold threshold = Threshold.Info)
		{
			this.typeToLog = typeToLog;
			this.threshold = threshold;
		}
Ejemplo n.º 36
0
        public ScoresPage(Inspection inspection, Question initialQuestion)
        {
            this.inspection = inspection;
            ChecklistModel checklist = inspection.Checklist;

            scoresThreshold = new Threshold(checklist.ScoreThresholdCommendable, checklist.ScoreThresholdSatisfactory);
            Padding         = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);

            this.Title = "Scores";
            ScoresLayout layout = new ScoresLayout
            {
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center
            };
            Label label = new Label
            {
                Text = "Choose section and part to see scores"
            };
            //add all the other stuff.
            GenericPicker <SectionModel> sectionPicker = new GenericPicker <SectionModel>();

            foreach (SectionModel section in inspection.Checklist.Sections)
            {
                sectionPicker.AddItem(section);
            }
            partPicker = new GenericPicker <SectionPart>();
            foreach (SectionPart part in initialQuestion.section.SectionParts)
            {
                partPicker.AddItem(part);
            }
            Button backButton = new Button
            {
                Text = "Back"
            };

            sectionScoreLabel = new Label
            {
                Text      = "Section label",
                TextColor = Color.White
            };
            partScoreLabel = new Label
            {
                Text      = "Part label",
                TextColor = Color.White
            };
            backButton.Clicked += BackButtonClicked;
            layout.Children.Add(label);
            layout.Children.Add(sectionPicker);
            layout.Children.Add(sectionScoreLabel);
            layout.Children.Add(partPicker);
            layout.Children.Add(partScoreLabel);
            double cumulativeScore      = ScoringHelper.ScoreInspection(inspection).Item3;
            Label  cumulativeScoreLabel = new Label
            {
                Text      = "Cumulative Score: " + (cumulativeScore * 100).ToString("0.00") + "%",
                TextColor = Color.White
            };

            setScoresColor(cumulativeScore, cumulativeScoreLabel);
            layout.Children.Add(cumulativeScoreLabel);
            layout.Children.Add(backButton);

            this.Content = layout;

            sectionPicker.SelectedIndexChanged += ChangeSection;
            sectionPicker.SelectedIndex         = sectionPicker.TItems.IndexOf(initialQuestion.section);
            partPicker.SelectedIndexChanged    += ChangePart;
            if (initialQuestion.part != null)
            {
                partPicker.SelectedIndex = partPicker.TItems.IndexOf(initialQuestion.part);
            }
        }
Ejemplo n.º 37
0
        public Binarize(UISettings ui, FileData file) : base(ui, file)
        {
            try {
                Invert AFinvert = new Invert();
                switch (ui.ThresholdIndex)         // threshold method selection "Global mean" / "Local adaptive"
                {
                case 0:                            // Global
                    if (ui.ThreshGlobalIsAbsolute) // use absolute
                    {
                        Threshold AFglobalbinary = new Threshold(ui.ThreshGlobalAbsolute);
                        UnmanagedBlackWhite = AFglobalbinary.Apply(UnmanagedGray);
                    }
                    else                                 // use relative
                    {
                        ImageStatistics stats          = new ImageStatistics(UnmanagedGray, AFinvert.Apply(UnmanagedExclude));
                        Threshold       AFglobalbinary = new Threshold(stats.Gray.Center2QuantileValue(1.0d * ui.ThreshGlobalRelative / 255.0d));
                        UnmanagedBlackWhite = AFglobalbinary.Apply(UnmanagedGray);
                    }
                    break;

                case 1:                         // Local
                    BradleyLocalThresholdingX AFlocalbinary = new BradleyLocalThresholdingX()
                    {
                        PixelBrightnessDifferenceLimit = ui.ThreshLocalBrightnessDifference,
                        WindowSize = ui.ThreshLocalWindowSize, UpperLimit = 250
                    };
                    UnmanagedBlackWhite = AFlocalbinary.Apply(UnmanagedGray);
                    break;
                }
                if (ui.FillHoleAirspaceSwitch && ui.FillHoleAirspace != 0)                 // fill holes of airspaces
                {
                    FillHoles AFfillinair = new FillHoles()
                    {
                        CoupledSizeFiltering = true, MaxHoleHeight = ui.FillHoleAirspace, MaxHoleWidth = ui.FillHoleAirspace
                    };
                    //FillHolesArea AFfillinair=new FillHolesArea() { MaxHoleArea=ui.FillHoleAirspace };
                    AFfillinair.ApplyInPlace(UnmanagedBlackWhite);
                }
                UnmanagedBlackWhite = AFinvert.Apply(UnmanagedBlackWhite);
                if (ui.FillHoleTissueSwitch && ui.FillHoleTissue != 0)                 // fill holes of tissue
                {
                    FillHoles AFfillintissue = new FillHoles()
                    {
                        CoupledSizeFiltering = true, MaxHoleHeight = ui.FillHoleTissue, MaxHoleWidth = ui.FillHoleTissue
                    };
                    //FillHolesArea AFfillintissue=new FillHolesArea() { MaxHoleArea=ui.FillHoleTissue };
                    AFfillintissue.ApplyInPlace(UnmanagedBlackWhite);
                }
                if (ui.MorphoDilateSwitch && ui.MorphoDilate != 0)               // Morphological Dilate
                {
                    int n = (Math.Max(ui.MorphoDilate, 0) * 2 + 1); short[,] morphmatrix = new short[n, n];
                    for (int i = 0; i < n; i++)
                    {
                        for (int j = 0; j < n; j++)
                        {
                            morphmatrix[i, j] = 1;
                        }
                    }
                    Dilatation AFdilate = new Dilatation(morphmatrix);
                    AFdilate.ApplyInPlace(UnmanagedBlackWhite);
                }
                if (ui.MorphoErodeSwitch && ui.MorphoErode != 0)               // Morphological Erode

                {
                    int n = (Math.Max(ui.MorphoErode, 0) * 2 + 1); short[,] morphmatrix = new short[n, n];
                    for (int i = 0; i < n; i++)
                    {
                        for (int j = 0; j < n; j++)
                        {
                            morphmatrix[i, j] = 1;
                        }
                    }
                    Erosion AFerode = new Erosion(morphmatrix);
                    AFerode.ApplyInPlace(UnmanagedBlackWhite);
                }
                if (ui.ExcludeColorSwitch)
                {
                    NonParen_SumArea = ui.um2px2 * UnmanagedExclude.NonBlackArea();
                }
                if (ui.BlobMinSwitch)
                {
                    Low_Threshold = Math.Pow(10.0d, ui.BlobMin) - 1;
                }
                else
                {
                    Low_Threshold = 0.0d;
                }
                if (ui.BlobMaxSwitch)
                {
                    High_Threshold = Math.Pow(10.0d, ui.BlobMax) - 1;
                }
                else
                {
                    High_Threshold = int.MaxValue;
                }

                if (ui.BlobMinSwitch || ui.BlobMaxSwitch)
                {
                    Merge       AFmerge1  = new Merge(UnmanagedExclude);
                    ExcludeSize AFexcsize = new ExcludeSize()
                    {
                        Low = (int)Math.Round(Low_Threshold / ui.um2px2), High = (int)Math.Round(Math.Min(int.MaxValue, High_Threshold / ui.um2px2))
                    };
                    Merge AFmerge2 = new Merge(AFexcsize.Apply(AFinvert.Apply(AFmerge1.Apply(UnmanagedBlackWhite))));
                    AFmerge2.ApplyInPlace(UnmanagedExclude);
                    Low_SumArea  = ui.um2px2 * AFexcsize.LowCount;
                    High_SumArea = ui.um2px2 * AFexcsize.HighCount;
                }
            } catch { throw new Exception("Error Occured During Binarization"); }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Bitmap sourceImage = null;

            DA.GetData(0, ref sourceImage);
            string filter = "";

            DA.GetData(1, ref filter);


            sourceImage = ImageUtilities.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            IFilter myFilter;
            Bitmap  filteredImage = sourceImage;

            //Grayscale.CommonAlgorithms.Y.Apply
            switch (filter)
            {
            case "Greyscale":
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                filteredImage = sourceImage;
                break;

            case "Sepia":
                Console.Write("Applying: " + filter);
                myFilter      = new Sepia();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Invert":
                Console.Write("Applying: " + filter);
                sourceImage   = ImageUtilities.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new Invert();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "RotateChannel":
                Console.Write("Applying: " + filter);
                myFilter      = new RotateChannels();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Threshold":     //Need Extended Version
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new Threshold();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "FloydFilter":
                Console.Write("Applying: " + filter);
                //sourceImage = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                //myFilter = new FloydSteinbergColorDithering();
                FloydSteinbergColorDithering myReduction = new FloydSteinbergColorDithering();
                filteredImage = myReduction.Apply(sourceImage);
                //filteredImage = myFilter.Apply(sourceImage);
                break;

            case "OrderedDithering":
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new OrderedDithering();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Sharpen":
                Console.Write("Applying: " + filter);
                myFilter      = new Sharpen();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "DifferenceEdgeDetector":
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new DifferenceEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "HomogenityEdgeDetector":
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new HomogenityEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Sobel":
                Console.Write("Applying: " + filter);
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new SobelEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Jitter":
                Console.Write("Applying: " + filter);
                myFilter      = new Jitter(); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "OilPainting":
                Console.Write("Applying: " + filter);
                myFilter      = new OilPainting(); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "TextureFiltering":
                Console.Write("Applying: " + filter);
                sourceImage   = ImageUtilities.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new Texturer(new TextileTexture(), 1.0, 0.8); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Median":
                Console.Write("Applying: " + filter);
                myFilter      = new Median();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Mean":
                Console.Write("Applying: " + filter);
                myFilter      = new Mean();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            case "Blur":     //Need Extended Version
                Console.Write("Applying: " + filter);
                myFilter      = new GaussianBlur();
                filteredImage = myFilter.Apply(sourceImage);
                break;

            default:
                Console.Write("No Filter");
                break;
            }

            Console.Write(filteredImage.PixelFormat.ToString());
            Console.Write(sourceImage.PixelFormat.ToString());
            filteredImage = ImageUtilities.convert(filteredImage, System.Drawing.Imaging.PixelFormat.Format32bppArgb);



            DA.SetData(0, filteredImage);
        }
Ejemplo n.º 39
0
        private void video_NewFrame1(object sender, NewFrameEventArgs eventArgs)
        {
            videoCapture.Stop();
            pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
            pictureBox2.SizeMode = PictureBoxSizeMode.CenterImage;
            pictureBox1.Image    = (Bitmap)eventArgs.Frame.Clone();
            //pictureBox2.Image = (Bitmap)eventArgs.Frame.Clone();
            image          = (Bitmap)eventArgs.Frame.Clone();
            byte[,] matrix = new byte[4, 4]
            {
                { 95, 233, 127, 255 },
                { 159, 31, 191, 63 },
                { 111, 239, 79, 207 },
                { 175, 47, 143, 15 }
            };
            switch (choice)
            {
            case 0:
            {
            }
            break;

            //Threshold
            case 1:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                Threshold filter = new Threshold(100);
                applyfilter(filter);
            }
            break;

            //OrderedDithering
            case 2:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                OrderedDithering filter = new OrderedDithering(matrix);
                applyfilter(filter);
            }
            break;

            //BayerDithering
            case 3:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                BayerDithering filter = new BayerDithering();
                applyfilter(filter);
            }
            break;

            //floyd
            case 4:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                FloydSteinbergDithering filter = new FloydSteinbergDithering();
                applyfilter(filter);
            }
            break;

            //burkes
            case 5:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                BurkesDithering filter = new BurkesDithering();
                applyfilter(filter);
            }
            break;

            //jarvis
            case 6:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                JarvisJudiceNinkeDithering filter = new JarvisJudiceNinkeDithering();
                applyfilter(filter);
            }
            break;

            //sierra
            case 7:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                SierraDithering filter = new SierraDithering();
                applyfilter(filter);
            }
            break;

            //stucki
            case 8:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                StuckiDithering filter = new StuckiDithering();
                applyfilter(filter);
            }
            break;

            //Homogenity
            case 9:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                HomogenityEdgeDetector filter = new HomogenityEdgeDetector();
                applyfilter(filter);
            }
            break;

            //rotate
            case 10:
            {
                applyfilter(new RotateChannels());
            } break;

            //sobel
            case 11:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                SobelEdgeDetector filter = new SobelEdgeDetector();
                applyfilter(filter);
            }
            break;

            //canny
            case 12:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                CannyEdgeDetector filter = new CannyEdgeDetector();
                applyfilter(filter);
            }
            break;

            case 13:
            {
                applyfilter(new YCbCrFiltering());
            } break;

            case 14:
            {
                applyfilter(new HueModifier(180));
            } break;

            //SIS Threshold
            case 15:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                SISThreshold filter = new SISThreshold();
                applyfilter(filter);
            } break;

            //Difference
            case 16:
            {
                Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
                image = g.Apply(image);
                DifferenceEdgeDetector filter = new DifferenceEdgeDetector();
                applyfilter(filter);
            } break;

            //mirror
            case 17:
            {
                applyfilter(new Mirror(false, true));
            } break;

            //flip
            case 18:
            {
                applyfilter(new RotateBilinear(180, true));
            } break;

            //Erosion
            case 19:
            {
                applyfilter1(new Erosion());
            } break;

            //Dilatation
            case 20:
            {
                applyfilter1(new Dilatation());
            } break;

            //Opening
            case 21:
            {
                applyfilter1(new Opening());
            } break;

            //closing
            case 22:
            {
                applyfilter1(new Closing());
            } break;

            //jitter
            case 23:
            {
                applyfilter(new Jitter(15));
            } break;

            //OilPainting
            case 24:
            {
                applyfilter(new OilPainting(10));
            } break;

            //pixellate
            case 25:
            {
                applyfilter(new Pixellate(10));
            } break;
            }
        }
Ejemplo n.º 40
0
        private void skinDetectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List <List <double> > Listofvectors = new List <List <double> >();

            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\gsrip\Documents\MyDocuments\Saarthi AI and IP\Segmented\segmented.txt", append: true);
            String alphabets            = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            for (int index = 1; index <= 26; index++)
            {
                //for each folder select all filenames
                filenames = Directory.GetFiles(dirnames[index - 1]);
                int n = 0;
                foreach (string filename in filenames)
                {
                    //load an image in a bitmap

                    Bitmap bmplocal = new Bitmap(filename);
                    int    height = 300, width = 300;
                    bmp = new Bitmap(bmplocal, width, height);
                    pictureBox1.Image    = new Bitmap(bmp);
                    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                    using (bmp)
                        using (skinBmp = new Bitmap(bmp.Width, bmp.Height))
                        {
                            //skin detection
                            for (int x = 0; x < bmp.Width; x++)
                            {
                                for (int y = 0; y < bmp.Height; y++)
                                {
                                    Color pixel = bmp.GetPixel(x, y);

                                    int red   = pixel.R;
                                    int blue  = pixel.B;
                                    int green = pixel.G;
                                    int max   = Math.Max(red, Math.Max(green, blue));
                                    int min   = Math.Min(red, Math.Min(green, blue));
                                    int rgdif = red - green;
                                    int abs   = Math.Abs(rgdif);
                                    if (red > 95 && green > 40 && blue > 20 && max - min > 15 && abs > 15 && red > green && red > blue)
                                    {
                                        skinBmp.SetPixel(x, y, pixel);
                                    }
                                }
                            }

                            pictureBox2.Image = new Bitmap(skinBmp);
                            //grayscale filter (BT709)
                            Grayscale filter1   = new Grayscale(0.2125, 0.7154, 0.0721);
                            Bitmap    newImage  = new Bitmap(bmp);
                            Bitmap    grayImage = filter1.Apply(newImage);

                            Threshold filter2 = new Threshold(100);
                            Bitmap    bwImage = filter2.Apply(grayImage);

                            Closing filter5 = new Closing();
                            filter5.ApplyInPlace(bwImage);

                            Opening filter3 = new Opening();
                            filter3.ApplyInPlace(bwImage);

                            ExtractBiggestBlob filter4           = new ExtractBiggestBlob();
                            Bitmap             biggestBlobsImage = filter4.Apply(bwImage);

                            ExtractBiggestBlob filter6            = new ExtractBiggestBlob();
                            Bitmap             biggestBlobsImage1 = filter6.Apply((Bitmap)pictureBox2.Image);

                            Bitmap orgimage  = new Bitmap(biggestBlobsImage1, 300, 300);
                            Bitmap blobimage = new Bitmap(biggestBlobsImage, 300, 300);

                            Bitmap newimage = new Bitmap(300, 300);

                            //anding the two images
                            for (int x = 0; x < 300; x++)
                            {
                                for (int y = 0; y < 300; y++)
                                {
                                    Color pixel1 = orgimage.GetPixel(x, y);
                                    Color pixel2 = blobimage.GetPixel(x, y);
                                    int   red1 = pixel1.R, red2 = pixel2.R;
                                    int   blue1 = pixel1.B, blue2 = pixel2.B;
                                    int   green1 = pixel1.G, green2 = pixel2.G;
                                    int   newred, newblue, newgreen;
                                    newred   = red1 & red2;
                                    newblue  = blue1 & blue2;
                                    newgreen = green1 & green2;
                                    Color newpixel = Color.FromArgb(newred, newgreen, newblue);

                                    newimage.SetPixel(x, y, newpixel);
                                }
                            }

                            CannyEdgeDetector filter7 = new CannyEdgeDetector();
                            Grayscale         filter  = new Grayscale(0.2125, 0.7154, 0.0721);
                            Bitmap            edges   = filter.Apply(newimage);
                            filter7.ApplyInPlace(edges);

                            pictureBox3.Image = new Bitmap(edges);
                            String location = "C:\\Users\\gsrip\\Documents\\MyDocuments\\Saarthi AI and IP\\Segmented\\";
                            location = location + alphabets[index].ToString() + "\\image";
                            newimage.Save(@location + (n++).ToString() + ".jpg");

                            List <int> featureVector = new List <int>();
                            for (int i = 0; i < 6; i++)
                            {
                                for (int j = 0; j < 6; j++)
                                {
                                    int count = 0;
                                    for (int x = i * 50; x < (i * 50) + 50; x++)
                                    {
                                        for (int y = j * 50; y < (j * 50) + 50; y++)
                                        {
                                            Color pixel = edges.GetPixel(x, y);
                                            if (pixel.R != 0 && pixel.G != 0 && pixel.B != 0)
                                            {
                                                count++;
                                            }
                                        }
                                    }
                                    featureVector.Add(count);
                                }
                            }

                            int           sumofvector       = featureVector.Sum();
                            List <double> featureVectorNorm = new List <double>();
                            foreach (var d in featureVector)
                            {
                                featureVectorNorm.Add((double)d / sumofvector);
                            }
                            Listofvectors.Add(featureVectorNorm);
                        }//end of using
                } // end of foreach filename
                foreach (var vector in Listofvectors)
                {
                    String line = index.ToString() + ": ";
                    //Console.WriteLine(value);
                    foreach (var obj in vector)
                    {
                        line = line + obj.ToString() + " ";
                        //Console.Write(value);
                    }
                    file.WriteLine(line);
                    //Console.WriteLine();
                }
            } //end of foreach index
            file.Close();
        }     //end of skindetect tool strip
Ejemplo n.º 41
0
        /// <summary>
        ///     Performs the analysis on the image
        /// </summary>
        public void Analyze(bool thorough = true)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("ImageProcessor");
            }

            if (IsScannable)
            {
                return;
            }

            LuminanceSource source    = new BitmapLuminanceSource(m_bitmap);
            var             binarizer = new HybridBinarizer(source);
            var             binBitmap = new BinaryBitmap(binarizer);

            // Try to extract the form data
            var barReader = new BarcodeReader();

            barReader.AutoRotate              = true;
            barReader.Options.TryHarder       = thorough;
            barReader.Options.PossibleFormats = new List <BarcodeFormat> {
                BarcodeFormat.CODE_128
            };

            m_barcodeResults = barReader.DecodeMultiple(source);

            // Look for barcode markers if possible
            if (m_barcodeResults != null)
            {
                MarkerCodes = m_barcodeResults.Where(o => o.Text.StartsWith("OMR:")).ToArray();
            }
            IsScannable = true;
            // Get the template data
            var markerCode = MarkerCodes == null
                ? null
                : MarkerCodes.FirstOrDefault(o => o.Text.StartsWith("OMR:TL") || o.Text.StartsWith("OMR:ID"));

            // Get the guiding points by circles
            var grayFilter      = new GrayscaleY();
            var thresholdFilter = new Threshold(127);
            var invertFilter    = new Invert();

            using (var searchImage = invertFilter.Apply(thresholdFilter.Apply(grayFilter.Apply(m_bitmap))))
            {
                // Blobs
                var blobCounter = new BlobCounter();
                blobCounter.FilterBlobs = true;
                blobCounter.MinHeight   = 30;
                blobCounter.MinWidth    = 30;

                // Check for circles
                blobCounter.ProcessImage(searchImage);
                var blobs         = blobCounter.GetObjectsInformation();
                var shapeChecker  = new SimpleShapeChecker();
                var controlPoints = new List <Point>();
                var currentCheck  = 45;
                while ((currentCheck-- > 20) && (controlPoints.Count != 4))
                {
                    controlPoints.Clear();
                    // Get the positions
                    foreach (var blob in blobs)
                    {
                        var   center = new Point();
                        float radius = 0;

                        if (shapeChecker.IsCircle(blobCounter.GetBlobsEdgePoints(blob), out center, out radius) &&
                            (radius > currentCheck))
                        {
                            controlPoints.Add(center);
                        }
                    }
                }

                // Control points
                IsScannable &= controlPoints.Count == 4;
                if (!IsScannable)
                {
                    return;
                }

                // Now set markers
                m_topLeft     = controlPoints[0]; //new AForge.Point(this.m_bitmap.Width + 10, this.m_bitmap.Height + 10);
                m_topRight    = controlPoints[1];
                m_bottomLeft  = controlPoints[2];
                m_bottomRight = controlPoints[3];

                // Find the right most bubble
                float rightMost = controlPoints.Select(o => o.X).Max(),
                      leftMost  = controlPoints.Select(o => o.X).Min();
                // Organize those that are left/right
                Point[] lefties = controlPoints.Where(o => o.X < leftMost + (rightMost - leftMost) / 2).ToArray(),
                righties = controlPoints.Where(o => o.X > leftMost + (rightMost - leftMost) / 2).ToArray();

                // HACK:
                if (lefties[0].Y < lefties[1].Y)
                {
                    m_topLeft    = lefties[0];
                    m_bottomLeft = lefties[1];
                }
                else
                {
                    m_topLeft    = lefties[1];
                    m_bottomLeft = lefties[0];
                }

                // HACK:
                if (righties[0].Y < righties[1].Y)
                {
                    m_topRight    = righties[0];
                    m_bottomRight = righties[1];
                }
                else
                {
                    m_topRight    = righties[1];
                    m_bottomRight = righties[0];
                }
            }

            if (!IsScannable)
            {
                return;
            }

            // Get the template data
            if ((MarkerCodes != null) && (markerCode != null))
            {
                var templateData = markerCode.Text.Split(':');
                if (templateData.Length > 2)
                {
                    TemplateName = templateData[2];
                    if (templateData.Length > 3)
                    {
                        Parameters = templateData.Skip(3).ToArray();
                    }
                }
            }
        }
        //private Collection<DetectionPoint> loadMockedDetectionPoints() {
        private HashSet <DetectionPoint> loadMockedDetectionPoints()
        {
            //Collection<DetectionPoint> configuredDetectionPoints = new Collection<DetectionPoint>();
            HashSet <DetectionPoint> configuredDetectionPoints = new HashSet <DetectionPoint>();

            Interval minutes5  = new Interval(5, Interval.MINUTES);
            Interval minutes6  = new Interval(6, Interval.MINUTES);
            Interval minutes7  = new Interval(7, Interval.MINUTES);
            Interval minutes8  = new Interval(8, Interval.MINUTES);
            Interval minutes11 = new Interval(11, Interval.MINUTES);
            Interval minutes12 = new Interval(12, Interval.MINUTES);
            Interval minutes13 = new Interval(13, Interval.MINUTES);
            Interval minutes14 = new Interval(14, Interval.MINUTES);
            Interval minutes15 = new Interval(15, Interval.MINUTES);
            Interval minutes31 = new Interval(31, Interval.MINUTES);
            Interval minutes32 = new Interval(32, Interval.MINUTES);
            Interval minutes33 = new Interval(33, Interval.MINUTES);
            Interval minutes34 = new Interval(34, Interval.MINUTES);
            Interval minutes35 = new Interval(35, Interval.MINUTES);

            Threshold events3minutes5  = new Threshold(3, minutes5);
            Threshold events12minutes5 = new Threshold(12, minutes5);
            Threshold events13minutes6 = new Threshold(13, minutes6);
            Threshold events14minutes7 = new Threshold(14, minutes7);
            Threshold events15minutes8 = new Threshold(15, minutes8);

            Response log = new Response();

            log.setAction("log");

            Response logout = new Response();

            logout.setAction("logout");

            Response disableUser = new Response();

            disableUser.setAction("disableUser");

            Response disableComponentForSpecificUser31 = new Response();

            disableComponentForSpecificUser31.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser31.setInterval(minutes31);

            Response disableComponentForSpecificUser32 = new Response();

            disableComponentForSpecificUser32.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser32.setInterval(minutes32);

            Response disableComponentForSpecificUser33 = new Response();

            disableComponentForSpecificUser33.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser33.setInterval(minutes33);

            Response disableComponentForSpecificUser34 = new Response();

            disableComponentForSpecificUser34.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser34.setInterval(minutes34);

            Response disableComponentForSpecificUser35 = new Response();

            disableComponentForSpecificUser35.setAction("disableComponentForSpecificUser");
            disableComponentForSpecificUser35.setInterval(minutes35);

            Response disableComponentForAllUsers11 = new Response();

            disableComponentForAllUsers11.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers11.setInterval(minutes11);

            Response disableComponentForAllUsers12 = new Response();

            disableComponentForAllUsers12.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers12.setInterval(minutes12);

            Response disableComponentForAllUsers13 = new Response();

            disableComponentForAllUsers13.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers13.setInterval(minutes13);

            Response disableComponentForAllUsers14 = new Response();

            disableComponentForAllUsers14.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers14.setInterval(minutes14);

            Response disableComponentForAllUsers15 = new Response();

            disableComponentForAllUsers15.setAction("disableComponentForAllUsers");
            disableComponentForAllUsers15.setInterval(minutes15);

            Collection <Response> point1Responses = new Collection <Response>();

            point1Responses.Add(log);
            point1Responses.Add(logout);
            point1Responses.Add(disableUser);
            point1Responses.Add(disableComponentForSpecificUser31);
            point1Responses.Add(disableComponentForAllUsers11);

            DetectionPoint point1 = new DetectionPoint("IE1", events3minutes5, point1Responses);

            Collection <Response> point2Responses = new Collection <Response>();

            point2Responses.Add(log);
            point2Responses.Add(logout);
            point2Responses.Add(disableUser);
            point2Responses.Add(disableComponentForSpecificUser32);
            point2Responses.Add(disableComponentForAllUsers12);

            DetectionPoint point2 = new DetectionPoint("IE2", events12minutes5, point2Responses);

            Collection <Response> point3Responses = new Collection <Response>();

            point3Responses.Add(log);
            point3Responses.Add(logout);
            point3Responses.Add(disableUser);
            point3Responses.Add(disableComponentForSpecificUser33);
            point3Responses.Add(disableComponentForAllUsers13);

            DetectionPoint point3 = new DetectionPoint("IE3", events13minutes6, point3Responses);

            Collection <Response> point4Responses = new Collection <Response>();

            point4Responses.Add(log);
            point4Responses.Add(logout);
            point4Responses.Add(disableUser);
            point4Responses.Add(disableComponentForSpecificUser34);
            point4Responses.Add(disableComponentForAllUsers14);

            DetectionPoint point4 = new DetectionPoint("IE4", events14minutes7, point4Responses);

            Collection <Response> point5Responses = new Collection <Response>();

            point5Responses.Add(log);
            point5Responses.Add(logout);
            point5Responses.Add(disableUser);
            point5Responses.Add(disableComponentForSpecificUser35);
            point5Responses.Add(disableComponentForAllUsers15);

            DetectionPoint point5 = new DetectionPoint("IE5", events15minutes8, point5Responses);

            configuredDetectionPoints.Add(point1);
            configuredDetectionPoints.Add(point2);
            configuredDetectionPoints.Add(point3);
            configuredDetectionPoints.Add(point4);
            configuredDetectionPoints.Add(point5);

            return(configuredDetectionPoints);
        }
Ejemplo n.º 43
0
    //TEMP FOR NOW. FIX UP LATER
    //NEW VERSTION OF HPA BELOW
    private List <Cell> NewFindHPAPath(Vector3 startPosition, Vector3 goalPosition)
    {
        //setups
        hasFoundPath      = false;
        isCalculatingPath = true;
        List <Cell> finalPath = new List <Cell>();

        //get cell versions of the start and goal position
        Cell startCell = map.CellFromWorldPos(startPosition);
        Cell goalCell  = map.CellFromWorldPos(goalPosition);

        //error checking
        if (!startCell.isWalkable)
        {
            startCell = map.CellFromWorldPosSearch(startPosition);
        }
        if (!goalCell.isWalkable)
        {
            goalCell = map.CellFromWorldPosSearch(goalPosition);
        }


        //check if the goalCell is the same as the startCell
        if (startCell.worldPosition == goalCell.worldPosition)
        {
            //we don't need to find a path
            return(null);
        }

        //check if the goalCell is in the same zone has the startCell
        //use this path as the final path
        if (map.GetZone(startCell.zoneId).zoneId == map.GetZone(goalCell.zoneId).zoneId)
        {
            //simply use the find cell path function to get to the goal
            List <Cell> path = FindCellPath(startCell, goalCell);

            //error checking
            if (path != null)
            {
                finalPath.AddRange(path);
            }

            pathToTake        = finalPath;
            hasFoundPath      = true;
            isCalculatingPath = false;
            return(finalPath);
        }

        //add the startCell and the goalCell to the agentThreshold graph
        Threshold startThresold = AddStartThreshold(startCell);
        Threshold goalThreshold = AddGoalThreshold(goalCell);

        //Debug.Log("start and goal thresholds have been created.");
        //Debug.Log("these thresholds are at:" + startThresold.worldPosition + " and at:" + goalThreshold.worldPosition);

        //find the threshold path using these new thresholds
        List <Threshold> thresholdPath = FindThresholdPath(startThresold, goalThreshold);

        if (thresholdPath == null)
        {
            //Debug.Log("Big f*****g yike");
            return(null);
        }


        tpathToTake = thresholdPath;

        //using the threshold path, find the lower level cell path
        if (thresholdPath.Count >= 2)
        {
            for (int i = 1; i < thresholdPath.Count; i++)
            {
                //Get the position of the previous threshold. This will be our new "start"
                Cell newStart = map.CellFromThreshold(thresholdPath[i - 1]);

                //Get the position of the current threshold. This will be our new "goal"
                Cell newGoal = map.CellFromThreshold(thresholdPath[i]);

                //find the cell path
                List <Cell> path = FindCellPath(newStart, newGoal);
                if (path != null)
                {
                    finalPath.AddRange(path);
                }
            }
        }

        //done!
        Debug.Log("path found");
        DeleteGoalThreshold(goalThreshold);
        pathToTake        = finalPath;
        hasFoundPath      = true;
        isCalculatingPath = false;
        return(finalPath);
    }
Ejemplo n.º 44
0
        public static Bitmap FilterImage(Bitmap img, int filter)
        {
            Bitmap sourceImage = img;

            sourceImage = ImageUtil.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            IFilter myFilter;
            Bitmap  filteredImage = sourceImage;

            if (filter == Filters.filters["Greyscale"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                filteredImage = sourceImage;
            }
            else if (filter == Filters.filters["Sepia"])
            {
                myFilter      = new Sepia();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Invert"])
            {
                sourceImage   = ImageUtil.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new Invert();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["RotateChannel"])
            {
                myFilter      = new RotateChannels();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Threshold"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new Threshold();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["FloydFilter"])
            {
                FloydSteinbergColorDithering myReduction = new FloydSteinbergColorDithering();
                filteredImage = myReduction.Apply(sourceImage);
            }
            else if (filter == Filters.filters["OrderedDithering"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new OrderedDithering();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Sharpen"])
            {
                myFilter      = new Sharpen();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["DifferenceEdgeDetector"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new DifferenceEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["HomogenityEdgeDetector"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new HomogenityEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Sobel"])
            {
                sourceImage   = Grayscale.CommonAlgorithms.RMY.Apply(sourceImage);
                myFilter      = new SobelEdgeDetector();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Jitter"])
            {
                myFilter      = new Jitter(); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["OilPainting"])
            {
                sourceImage   = ImageUtil.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new OilPainting(); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["TextureFiltering"])
            {
                sourceImage   = ImageUtil.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new Texturer(new TextileTexture(), 1.0, 0.8); //Needs Expand
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Median"])
            {
                sourceImage   = ImageUtil.convert(sourceImage, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                myFilter      = new Median();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Mean"])
            {
                myFilter      = new Mean();
                filteredImage = myFilter.Apply(sourceImage);
            }
            else if (filter == Filters.filters["Blur"])
            {
                myFilter      = new GaussianBlur();
                filteredImage = myFilter.Apply(sourceImage);
            }

            //Console.Write(filteredImage.PixelFormat.ToString());
            //Console.Write(sourceImage.PixelFormat.ToString());
            filteredImage = ImageUtil.convert(filteredImage, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            return(filteredImage);
        }
Ejemplo n.º 45
0
    /* Similar to the above method, but for thresholds rather than cells.
     */
    private List <Threshold> FindThresholdPath(Threshold startThreshold, Threshold goalThreshold)
    {
        PriorityQueue <Threshold> frontier = new PriorityQueue <Threshold>();
        List <Threshold>          path     = null;

        tcameFrom  = new Dictionary <Threshold, Threshold>();
        tcostSoFar = new Dictionary <Threshold, float>();

        frontier.Enqueue(startThreshold, 0);
        tcameFrom[startThreshold]  = startThreshold;
        tcostSoFar[startThreshold] = 0;


        while (frontier.Count() > 0)
        {
            //Check if the agent is able to calculate their path.
            if (hasHaltedCalculating)
            {
                StartCoroutine(WaitUntilCanCalculate());
            }

            //else, continue to calculate the path.
            Threshold current = frontier.Deqeueue();

            //check if the agent can calculate on this threshold
            if (current.belongsTo != null)
            {
                if (!current.belongsTo.Equals(gameObject.name))
                {
                    continue;
                }
            }

            if (current.Equals(goalThreshold))
            {
                path = RetraceThresholdPath(startThreshold, goalThreshold);
                break;
            }

            foreach (ThresholdEdge e in current.tedgesToNeighbors)
            {
                Threshold neighbor = e.incident;

                //check if the agent can calculate on this threshold
                if (neighbor.belongsTo != null)
                {
                    if (!neighbor.belongsTo.Equals(gameObject.name))
                    {
                        continue;
                    }
                }


                //CHANGED!!
                //float newCost = tcostSoFar[current] + GetThresholdCost(current, neighbor);
                float newCost = tcostSoFar[current] + e.weight;

                if (!tcostSoFar.ContainsKey(neighbor) || newCost < tcostSoFar[neighbor])
                {
                    tcostSoFar[neighbor] = newCost;
                    float priority = newCost + GetThresholdHeuristic(neighbor, goalThreshold) + GetICostFromThreshold(neighbor);
                    frontier.Enqueue(neighbor, priority);
                    tcameFrom[neighbor] = current;
                }
            }
        }

        return(path);
    }
Ejemplo n.º 46
0
        // Process image
        private void ProcessImage(Bitmap bitmap)
        {
            //QuantizeImage(bitmap);

            Grayscale grayscaleFilter = new Grayscale(0.33, 0.33, 0.34);
            // apply the filter
            Bitmap grayImage = grayscaleFilter.Apply(bitmap);

            // create filter
            SobelEdgeDetector sobelFilter = new SobelEdgeDetector();

            // apply the filter
            sobelFilter.ApplyInPlace(grayImage);
            Threshold filter = new Threshold(243);

            // apply the filter
            filter.ApplyInPlace(grayImage);

            int[,,] intersectPoint = new int[2, 19, 19];
            GetIntersect(grayImage, bitmap, intersectPoint);

            Graphics g = Graphics.FromImage(bitmap);

            //Sorting

            /*int[,] top19 = new int[19, 2];
             * int[,] left19 = new int[19, 2];
             * int[,] bot19 = new int[19, 2];
             * int[,] right19 = new int[19, 2];
             * int lowest = 9999999;
             * int lowX = 0;
             * int lowY = 0;
             * for (int i = 0; i < 19; i++) {
             *  for (int j = 0; j < 19; j++) {
             *      if (intersectPoint[0, i, j] + intersectPoint[1, i, j] < lowest) {
             *          lowest = intersectPoint[0, i, j] + intersectPoint[1, i, j];
             *          lowX = Math.Abs(intersectPoint[0, i, j]);
             *          lowY = Math.Abs(intersectPoint[1, i, j]);
             *      }
             *  }
             * }
             */

            for (int i = 0; i < 19; i++)
            {
                for (int j = 0; j < 19; j++)
                {
                    for (int k = 0; k < 19 - 1; k++)
                    {
                        if (Math.Abs(intersectPoint[1, i, k]) > Math.Abs(intersectPoint[1, i, k + 1]))
                        {
                            int tempX = Math.Abs(intersectPoint[0, i, k]);
                            int tempY = Math.Abs(intersectPoint[1, i, k]);
                            intersectPoint[0, i, k]     = Math.Abs(intersectPoint[0, i, k + 1]);
                            intersectPoint[1, i, k]     = Math.Abs(intersectPoint[1, i, k + 1]);
                            intersectPoint[0, i, k + 1] = tempX;
                            intersectPoint[1, i, k + 1] = tempY;
                            //MessageBox.Show(i + " " + k +" " +tempX + " " + tempY + " " + intersectPoint[0, i, k] + " " + intersectPoint[1, i, k] ,"ok", MessageBoxButtons.OK);
                        }
                    }
                }
            }

            for (int i = 0; i < 19; i++)
            {
                for (int j = 0; j < 19; j++)
                {
                    for (int k = 0; k < 19 - 1; k++)
                    {
                        if (Math.Abs(intersectPoint[0, k, i]) > Math.Abs(intersectPoint[0, k + 1, i]))
                        {
                            int tempX = Math.Abs(intersectPoint[0, k, i]);
                            int tempY = Math.Abs(intersectPoint[1, k, i]);
                            intersectPoint[0, k, i]     = intersectPoint[0, k + 1, i];
                            intersectPoint[1, k, i]     = intersectPoint[1, k + 1, i];
                            intersectPoint[0, k + 1, i] = tempX;
                            intersectPoint[1, k + 1, i] = tempY;
                        }
                    }
                }
            }

            Pen redPen = new Pen(Color.Red, 4);

            for (int i = 0; i < 19; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    g.DrawEllipse(redPen, Math.Abs(intersectPoint[0, i, j]) - 2, Math.Abs(intersectPoint[1, i, j]) - 2, (int)5, (int)5);
                    //g.DrawEllipse(redPen, 0, 0, (int)5, (int)5);
                }
            }
            Pen greenPen = new Pen(Color.Green, 4);

            greenPen.Dispose();
            redPen.Dispose();
            g.Dispose();


            /*HoughLineTransformation lineTransform = new HoughLineTransformation();
             * lineTransform.ProcessImage(grayImage);
             * Bitmap houghLineImage = lineTransform.ToBitmap();
             * // get lines using relative intensity
             * HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5);
             *
             * BitmapData bitmapData = bitmap.LockBits(
             * new Rectangle(0, 0, bitmap.Width, bitmap.Height),
             * ImageLockMode.ReadWrite, bitmap.PixelFormat);
             * BitmapData grayImageData = grayImage.LockBits(
             * new Rectangle(0, 0, grayImage.Width, grayImage.Height),
             * ImageLockMode.ReadWrite, grayImage.PixelFormat);
             * UnmanagedImage unmanagedImage = new UnmanagedImage(bitmapData);
             *
             * int w2 = 0, h2 = 0;
             * Color color = Color.Black;
             *
             * foreach (HoughLine line in lines)
             * {
             *
             *  String temp = line.Theta.ToString();
             *  //MessageBox.Show(temp, "ok", MessageBoxButtons.OK);
             *  // get line's radius and theta values
             *  int r = line.Radius;
             *  double t = line.Theta;
             *
             *  // check if line is in lower part of the image
             *  if (r < 0)
             *  {
             *      t += 180;
             *      r = -r;
             *  }
             *
             *  // convert degrees to radians
             *  t = (t / 180) * Math.PI;
             *
             *  // get image centers (all coordinate are measured relative
             *  // to center)
             *  w2 = grayImage.Width / 2;
             *  h2 = grayImage.Height / 2;
             *
             *  double x0 = 0, x1 = 0, y0 = 0, y1 = 0;
             *
             *  if (line.Theta != 0)
             *  {
             *      // horizontal
             *      // none-vertical line
             *
             *      if (line.Theta > 0 && line.Theta < 10 || line.Theta > 170)
             *      {
             *          x0 = -w2; // most left point
             *          x1 = w2;  // most right point
             *
             *          y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t);
             *          y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t);
             *
             *          color = Color.Red;
             *
             *          Drawing.Line(bitmapData,
             *          new IntPoint((int)x0 + w2, h2 - (int)y0),
             *          new IntPoint((int)x1 + w2, h2 - (int)y1),
             *          color);
             *          Drawing.Line(grayImageData,
             *          new IntPoint((int)x0 + w2, h2 - (int)y0),
             *          new IntPoint((int)x1 + w2, h2 - (int)y1),
             *          color);
             *      }
             *
             *      if (line.Theta > 80 && line.Theta < 100)
             *      {
             *          x0 = -w2; // most left point
             *          x1 = w2;  // most right point
             *
             *          y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t);
             *          y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t);
             *
             *          Drawing.Line(bitmapData,
             *          new IntPoint((int)x0 + w2, h2 - (int)y0),
             *          new IntPoint((int)x1 + w2, h2 - (int)y1),
             *          Color.Blue);
             *          Drawing.Line(grayImageData,
             *           new IntPoint((int)x0 + w2, h2 - (int)y0),
             *           new IntPoint((int)x1 + w2, h2 - (int)y1),
             *           Color.Blue);
             *      }
             *  }
             *  else
             *  {
             *      // vertical line
             *      x0 = line.Radius;
             *      x1 = line.Radius;
             *      y0 = h2;
             *      y1 = -h2;
             *
             *      color = Color.Red;
             *
             *      Drawing.Line(bitmapData,
             *      new IntPoint((int)x0 + w2, h2 - (int)y0),
             *      new IntPoint((int)x1 + w2, h2 - (int)y1),
             *      color);
             *      Drawing.Line(grayImageData,
             *       new IntPoint((int)x0 + w2, h2 - (int)y0),
             *       new IntPoint((int)x1 + w2, h2 - (int)y1),
             *       color);
             *  }
             * }
             * bitmap.UnlockBits(bitmapData);
             * grayImage.UnlockBits(grayImageData);
             * MessageBox.Show(lines.Length+"", "ok", MessageBoxButtons.OK);
             */
            Clipboard.SetDataObject(bitmap);
            // and to picture box
            pictureBox.Image = bitmap;
            UpdatePictureBoxPosition();
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Threshold algorithm. Here we create a new window from where we implement the algorithm.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void threshold_Click(object sender, RoutedEventArgs e) {
            if (m_data.M_inputFilename == string.Empty || m_data.M_bitmap == null) {
                MessageBox.Show("Open image first!", "ArgumentsNull", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try {
                Threshold thresholdWindow = new Threshold(m_data, m_vm);
                thresholdWindow.Owner = this;
                thresholdWindow.Show();
            } catch (FileNotFoundException ex) {
                MessageBox.Show(ex.Message, "FileNotFoundException", MessageBoxButton.OK, MessageBoxImage.Error);
            } catch (ArgumentException ex) {
                MessageBox.Show(ex.Message, "ArgumentException", MessageBoxButton.OK, MessageBoxImage.Error);
            } catch (InvalidOperationException ex) {
                MessageBox.Show(ex.Message, "InvalidOperationException", MessageBoxButton.OK, MessageBoxImage.Error);
            } catch (IndexOutOfRangeException ex) {
                MessageBox.Show(ex.Message, "IndexOutOfRangeException", MessageBoxButton.OK, MessageBoxImage.Error);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            disp1.SizeMode = PictureBoxSizeMode.StretchImage;
            disp2.SizeMode = PictureBoxSizeMode.StretchImage;
            disp3.SizeMode = PictureBoxSizeMode.StretchImage;
            System.Drawing.Image refimg  = System.Drawing.Image.FromFile("C:\\Users\\MohammadAlCheikhSale\\Desktop\\Final Hackathon\\RefImg.jpg");
            System.Drawing.Image caseimg = System.Drawing.Image.FromFile("C:\\Users\\MohammadAlCheikhSale\\Desktop\\Final Hackathon\\CaseImg.jpg");
            // create filter
            Difference filter = new Difference((Bitmap)refimg);
            // apply the filter
            Bitmap resultImage = filter.Apply((Bitmap)caseimg);

            disp1.Image = refimg;
            //ResultImage.Image = resultImage;
            disp2.Image = caseimg;
            show_result(resultImage);
            System.Threading.Thread.Sleep(5000);

            Grayscale gsfilter = new Grayscale(0.2125, 0.7154, 0.0721);
            Bitmap    gsImage  = gsfilter.Apply((Bitmap)caseimg);

            //ResultImage.Image = gsImage;

            System.Threading.Thread.Sleep(5000);

            Threshold bnFilter = new Threshold(100);
            Bitmap    bnImage  = bnFilter.Apply((Bitmap)gsImage);

            disp3.Image = bnImage;

            System.Threading.Thread.Sleep(5000);

            MaskedFilter mask     = new MaskedFilter(new Sepia(), bnImage);
            Bitmap       MasImage = mask.Apply((Bitmap)caseimg);

            disp3.Image = MasImage;

            /*HSLFiltering filter = new HSLFiltering(
             *  new IntRange(330, 30),    // hue range
             *  new Range(0, 1),    // saturation range
             *  new Range(0, 1));    // luminance range
             *
             * filter.UpdateLuminance = false;
             * filter.UpdateHue = false;
             * // apply the filter
             * filter.ApplyInPlace((Bitmap)proimg);*/

            /*Median filter = new Median();
             * // apply the filter
             * filter.ApplyInPlace((Bitmap)proimg);*/

            /*/ create grayscale filter (BT709)
             * Grayscale filter1 = new Grayscale(0.2125, 0.7154, 0.0721);
             * // apply the filter
             * Bitmap grayImage = filter1.Apply((Bitmap)proimg);
             *
             * // create filter
             * BlobsFiltering filter = new BlobsFiltering();
             * // configure filter
             * filter.CoupledSizeFiltering = true;
             * filter.MinWidth = 70;
             * filter.MinHeight = 70;
             * // apply the filter
             * filter.ApplyInPlace(grayImage);
             *
             * // create filter
             * Difference filter2 = new Difference(overlayImage);
             * // apply the filter
             * Bitmap resultImage = filter2.Apply(sourceImage);
             * procImage.Image = grayImage;*/



            /* BlobCounter bc = new BlobCounter();
             * bc.ProcessImage((Bitmap)resultImage);
             * Blob[] blobs = bc.GetObjectsInformation();
             */
        }
Ejemplo n.º 49
0
        public TiffDirectory()
        {
            td_subfiletype = 0;
            td_compression = 0;
            td_photometric = 0;
            td_planarconfig = 0;

            td_fillorder = FillOrder.MSB2LSB;
            td_bitspersample = 1;
            td_threshholding = Threshold.BILEVEL;
            td_orientation = Orientation.TOPLEFT;
            td_samplesperpixel = 1;
            td_rowsperstrip = -1;
            td_tiledepth = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit = ResUnit.INCH;
            td_sampleformat = SampleFormat.UINT;
            td_imagedepth = 1;
            td_ycbcrsubsampling[0] = 2;
            td_ycbcrsubsampling[1] = 2;
            td_ycbcrpositioning = YCbCrPosition.CENTERED;
        }
Ejemplo n.º 50
0
            public void ShouldReturnValueWithMinimumAndMaximum()
            {
                var point = new Threshold(1.2, 3.4);

                Assert.Equal("1.2-3.4", point.ToString());
            }
Ejemplo n.º 51
0
 public LinkParamGenDataRateEventWatcher(Threshold th)
 {
     this.th = th;
     subscribeEvent(th);
 }
Ejemplo n.º 52
0
        public TiffDirectory()
        {
            td_subfiletype = 0;
            td_compression = 0;
            td_photometric = 0;
            td_planarconfig = 0;

            td_fillorder = BitOrder.BigEndian;
            td_bitspersample = 1;
            td_threshholding = Threshold.BILevel;
            td_orientation = Orientation.TopLeft;
            td_samplesperpixel = 1;
            td_rowsperstrip = -1;
            td_tiledepth = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit = ResolutionUnit.Inch;
            td_sampleformat = SampleFormat.UInt;
            td_imagedepth = 1;
            td_ycbcrsubsampling[0] = 2;
            td_ycbcrsubsampling[1] = 2;
            td_ycbcrpositioning = YCbCrPosition.Centered;
        }
Ejemplo n.º 53
0
            public override void consumeMessage(IMessage message, int msgID)
            {
                VisionMessage vm = message as VisionMessage;
                // Bitmap bitmap = ByteTools.BytesToBmp(vm.Bitmap, vm.BmpWidth, vm.BmpHeight, ByteTools.bppToPixelFormat(vm.BytePerPixel));
                Bitmap bitmap = vm.Bitmap;
                Bitmap rgb = bitmap;

                bitmap = new ColorRemapping(redMap, greenMap, blueMap).Apply(bitmap);
                bitmap = new GrayscaleBT709().Apply(bitmap);
                bitmap = new Threshold(32).Apply(bitmap);

                //rgb = new GrayscaleToRGB().Apply(bitmap);

                Graphics g = Graphics.FromImage(rgb);

                if (g == null)
                {
                    Console.WriteLine("Null Graphics!");
                    return;
                }

                if (!threadRunning)
                {
                    threadRunning = true;
                    for (int i = 0; i < 3; i++)
                    {
                        if (g != null && currentStateProbs[i] > double.MinValue)
                        {
                            drawLine(g, new HoughLine((double)currentThetaStates[i], (short)currentRStates[i], 0, 0d),
                               new Rectangle(0, heightRes[0], bitmap.Width, (heightRes[heightRes.Length - 1] - heightRes[0]) * 2));
                        }
                    }
                    ThreadStart starter = delegate { findLines(bitmap); };
                    Thread innerThread = new Thread(starter);
                    innerThread.Start();
                }

                vm = new VisionMessage(rgb.Height, rgb.Width, ByteTools.pixelFormatToBPP(rgb.PixelFormat), rgb);
                msgService.sendMsg(vm);
            }