Inheritance: MonoBehaviour
Exemplo n.º 1
0
 public CannyEdgeDetector()
 {
     this.grayscaleFilter = new GrayscaleBT709();
     this.gaussianFilter = new GaussianBlur();
     this.lowThreshold = 20;
     this.highThreshold = 100;
 }
Exemplo n.º 2
0
        public void FindPeaksTest()
        {
            Bitmap hand = Properties.Resources.rhand;

            GaussianBlur median = new GaussianBlur(1.1);
            median.ApplyInPlace(hand);

            // Extract contour
            BorderFollowing bf = new BorderFollowing(1);
            List<IntPoint> contour = bf.FindContour(hand);

            hand = hand.Clone(new Rectangle(0, 0, hand.Width, hand.Height), PixelFormat.Format24bppRgb);

            // Find peaks
            KCurvature kcurv = new KCurvature(30, new DoubleRange(0, 45));
            // kcurv.Suppression = 30;
            var peaks = kcurv.FindPeaks(contour);

            List<IntPoint> supports = new List<IntPoint>();
            for (int i = 0; i < peaks.Count; i++)
            {
                int j = contour.IndexOf(peaks[i]);
                supports.Add(contour[(j + kcurv.K) % contour.Count]);
                supports.Add(contour[Accord.Math.Tools.Mod(j - kcurv.K, contour.Count)]);
            }

            // show(hand, contour, peaks, supports);

            Assert.AreEqual(2, peaks.Count);
            Assert.AreEqual(46, peaks[0].X);
            Assert.AreEqual(0, peaks[0].Y);
            Assert.AreEqual(2, peaks[1].X);
            Assert.AreEqual(11, peaks[1].Y);
        }
		protected override void AddCardImage()
		{
			var cardFile = Path.Combine(BarImageDir, Card.Id + ".png");
			if(!File.Exists(cardFile))
				return;
			var img = new GaussianBlur((Bitmap)Image.FromFile(cardFile)).Process(2);
			DrawingGroup.Children.Add(new ImageDrawing(img.ToImageSource(), FrameRect));
		}
Exemplo n.º 4
0
 public override BitmapBase Apply(Tank tank, BitmapBase layer)
 {
     if (_blur == null || _blur.Radius != Radius)
         lock (this)
             if (_blur == null || _blur.Radius != Radius)
                 _blur = new GaussianBlur(Radius);
     layer.Blur(_blur, Edge);
     return layer;
 }
Exemplo n.º 5
0
 public CannyEdgeDetector(byte lowThreshold, byte highThreshold, double sigma)
 {
     this.grayscaleFilter = new GrayscaleBT709();
     this.gaussianFilter = new GaussianBlur();
     this.lowThreshold = 20;
     this.highThreshold = 100;
     this.lowThreshold = lowThreshold;
     this.highThreshold = highThreshold;
     this.gaussianFilter.Sigma = sigma;
 }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Please provide an image file name as an argument");
                return;
            }

            var fileName = args[0];
            if (!File.Exists(fileName))
            {
                Console.WriteLine($"File {fileName} does not exist");
                return;
            }

            var image = Image.FromFile(fileName);
            var blur = new GaussianBlur(image as Bitmap);

            var sw = Stopwatch.StartNew();
            var result = blur.Process(10);
            Console.WriteLine($"Finished in: {sw.ElapsedMilliseconds}ms");
            result.Save("blur.jpg", ImageFormat.Jpeg);
        }
Exemplo n.º 7
0
        public static Bitmap Blur(this Bitmap bitmap, int radial)
        {
            var blur = new GaussianBlur(bitmap);

            return(blur.Process(radial));
        }
Exemplo n.º 8
0
 protected override void LoadContent()
 {
     gaussianBlur = new GaussianBlur(Game);
     bloom        = new Bloom(Game, gaussianBlur);
     motionBlur   = new MotionBlur(Game);
 }
Exemplo n.º 9
0
 public LinearScaleSpace(double sigma = Preferences.LSS_SIGMA)
 {
     Filter1 = new GaussianBlur(sigma / 4);
     Filter2 = new GaussianBlur(sigma / 2);
     Filter3 = new GaussianBlur(sigma);
 }
Exemplo n.º 10
0
        /// <summary> Blob Detection
        /// This method for color object detection by Blob counter algorithm.
        /// If you using this method, then you can detecting as follows:
        ///             red circle, rectangle, triangle
        ///             blue circle, rectangle, triangle
        ///             green circle, rectangle, triangle
        /// the process of this method as follow:
        ///     1. color filtering by Euclidean filtering(R, G, B).
        ///     2. the grayscale filtering based on color filtered image.
        ///     3. In this step, you can choose the blur option. Applied blur option(or not),
        ///        this method donging Sobel edge filtering based on grayscale(or grayscale + blur) image.
        ///     4. the binary filtering based on edge filter image.
        ///     5. Finally, detecting object, distance from the camera and degree are expreed on picturebox 1.
        /// </summary>

        private Bitmap BlobDetection(Bitmap _bitmapSourceImage)
        {
            #region Color filtering by Euclidean filtering
            switch (iColorMode)
            {
            case 1:
                //_colorFilter.CenterColor = new RGB(230, 30, 30);
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 2:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 3:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;
            }
            #endregion

            Grayscale _grayscale = new Grayscale(0.2125, 0.7154, 0.0721);
            _bitmapGreyImage = _grayscale.Apply(_colorFilterImage);

            #region blur option with Edge filter
            //create a edge detector instance
            if (_blurFlag == true)
            {
                //Blur _blurfilter = new Blur();
                GaussianBlur _blurfilter = new GaussianBlur(1.5);
                _bitmapBlurImage = _blurfilter.Apply(_bitmapGreyImage);
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapBlurImage);
            }
            else if (_blurFlag == false)
            {
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapGreyImage);
            }
            #endregion

            Threshold _threshold = new Threshold(iThreshold);
            _bitmapBinaryImage = _threshold.Apply(_bitmapEdgeImage);

            ///
            /// blob counter algorithm initailze.
            /// BlobCounter.MinWidth and MinHeight -> for the defined minimum region
            ///
            BlobCounter _blobCounter = new BlobCounter();
            //Configure Filter
            _blobCounter.MinWidth    = 70;
            _blobCounter.MinHeight   = 70;
            _blobCounter.FilterBlobs = true;
            _blobCounter.ProcessImage(_bitmapBinaryImage);

            Blob[]             _blobPoints   = _blobCounter.GetObjectsInformation();
            Graphics           _g            = Graphics.FromImage(_bitmapSourceImage);
            SimpleShapeChecker _shapeChecker = new SimpleShapeChecker();

            for (int i = 0; i < _blobPoints.Length; i++)
            {
                List <IntPoint> _edgePoint = _blobCounter.GetBlobsEdgePoints(_blobPoints[i]);
                List <IntPoint> _corners   = null;
                AForge.Point    _center;
                float           _radius;
                //#region detecting Rectangle
                /////
                ///// _corners: the corner of Quadrilateral
                /////
                //if (_shapeChecker.IsQuadrilateral(_edgePoint, out _corners))
                //{
                //    //Drawing the reference point of the picturebox
                //    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                //                                   (float)(pictureBox1.Size.Height),
                //                                   (float)10, (float)10);

                //    // Drawing setting for outline of detected object
                //    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();
                //    System.Drawing.Point[] _coordinates = ToPointsArray(_corners);
                //    Pen _pen = new Pen(Color.Blue, ipenWidth);
                //    int _x = _coordinates[0].X;
                //    int _y = _coordinates[0].Y;

                //    // Drawing setting for centroid of detected object
                //    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                //    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;

                //    //Drawing the centroid point of object
                //    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                //    //Degree calculation
                //    int _deg_x = (int)_centroid_X - pictureBox1.Size.Width;
                //    int _deg_y = pictureBox1.Size.Height - (int)_centroid_Y;
                //    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");

                //    ///
                //    /// Drawing outline of detected object
                //    ///
                //    if (_coordinates.Length == 4)
                //    {
                //        string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                //        _g.DrawString(_shapeString, _font, _brush, _x, _y);
                //        _g.DrawPolygon(_pen, ToPointsArray(_corners));
                //    }

                //    //size of rectange
                //    foreach (Rectangle rc in _rects)
                //    {
                //        ///for debug
                //        //System.Diagnostics.Debug.WriteLine(
                //        //    string.Format("Rect size: ({0}, {1})", rc.Width, rc.Height));

                //        iFeatureWidth = rc.Width;
                //        //check the FindDistance method.
                //        double dis = FindDistance(iFeatureWidth);
                //        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                //    }
                //}
                //#endregion

                #region detecting Circle
                ///
                /// _center: the center of circle
                /// _radius: the radius of circle
                ///
                if (_shapeChecker.IsCircle(_edgePoint, out _center, out _radius))
                {
                    //Drawing the reference point
                    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                                   (float)(pictureBox1.Size.Height),
                                   (float)10, (float)10);

                    // Drawing setting for outline of detected object
                    Rectangle[] _rects       = _blobCounter.GetObjectsRectangles();
                    Pen         _pen         = new Pen(Color.Red, ipenWidth);
                    string      _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    int         _x           = (int)_center.X;
                    int         _y           = (int)_center.Y;
                    ///
                    /// Drawing outline of detected object
                    ///
                    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                    _g.DrawEllipse(_pen, (float)(_center.X - _radius),
                                   (float)(_center.Y - _radius),
                                   (float)(_radius * 2),
                                   (float)(_radius * 2));

                    //Drawing the centroid point of object
                    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;
                    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                    //Degree calculation
                    //int _deg_x = _centroid_X - pictureBox1.Size.Width;
                    //int _deg_y = pictureBox1.Size.Height - _centroid_Y;

                    float _deg_x = _center.X * 100 / pictureBox1.Image.Width;
                    float _deg_y = _center.Y * 100 / pictureBox1.Image.Height;
                    textBox2.Text = _deg_x + "";
                    textBox3.Text = _deg_y + "";
                    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");

                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        ///for debug
                        //System.Diagnostics.Debug.WriteLine(
                        //    string.Format("Circle size: ({0}, {1})", rc.Width, rc.Height));
                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                    }
                }
                #endregion

                //#region detecting Triangle
                /////
                ///// _corners: the corner of Triangle
                /////
                //if (_shapeChecker.IsTriangle(_edgePoint, out _corners))
                //{
                //    //Drawing the reference point
                //    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                //                                   (float)(pictureBox1.Size.Height),
                //                                   (float)10, (float)10);

                //    // Drawing setting for outline of detected object
                //    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();
                //    Pen _pen = new Pen(Color.Green, ipenWidth);
                //    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                //    int _x = (int)_center.X;
                //    int _y = (int)_center.Y;

                //    // Drawing setting for centroid of detected object
                //    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                //    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;
                //    ///
                //    /// Drawing outline of detected object
                //    ///
                //    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                //    _g.DrawPolygon(_pen, ToPointsArray(_corners));

                //    //Drawing the centroid point of object
                //    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                //    //Degree calculation
                //    int _deg_x = (int)_centroid_X - pictureBox1.Size.Width;
                //    int _deg_y = pictureBox1.Size.Height - (int)_centroid_Y;
                //    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");
                //    //size of rectange
                //    foreach (Rectangle rc in _rects)
                //    {
                //        ///for debug
                //        //System.Diagnostics.Debug.WriteLine(
                //        //    string.Format("Triangle Size: ({0}, {1})", rc.Width, rc.Height));

                //        iFeatureWidth = rc.Width;
                //        double dis = FindDistance(iFeatureWidth);
                //        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                //    }
                //}
                //#endregion
            }
            return(_bitmapSourceImage);
        }
Exemplo n.º 11
0
        public SolarSystemScene(GameWindow gw, PlanetParameters planetParams, ContentManager contentManager)
        {
            this.contentManager = contentManager;
            this.hoursPerSecond = 1;
            this.defaultShader  = contentManager.GetShader("default");
            this.sunShader      = contentManager.GetShader("sunShader");
            this.lineShader     = contentManager.GetShader("lineShader");
            this.earthShader    = contentManager.GetShader("earth");

            this.buffer = new Framebuffer(gw.Width, gw.Height);
            buffer.AttachColorBuffer(internalFormat: PixelInternalFormat.Rgba16f, type: PixelType.Float);
            buffer.AttachColorBuffer(internalFormat: PixelInternalFormat.Rgba16f, type: PixelType.Float);
            buffer.AttachDepthStencilBuffer();

            blur = new GaussianBlur((int)gw.Size.Width / 1, (int)gw.Size.Height / 1);

            frame = FrameRenderer.Instance;

            finalShader            = contentManager.LoadShader("final");
            finalShader.Initialize = () =>
            {
                finalShader.Bind();
                finalShader.SetUniform("frame", 0);
                finalShader.SetUniform("bloom", 1);
            };
            finalShader.Init();

            cam            = new Camera(60);
            cam.MaxDepth   = 600;
            cam.LightPos   = new Vector3(0, 0, 0);
            cam.Projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(70), gw.Width / (float)gw.Height, .1f, 100000f);

            this.loadContent(planetParams, contentManager);

            cam.SetFocus(earth);

            #region Gui
            guiManager = new GuiManager(gw);
            panel      = new Panel()
            {
                Size            = new System.Drawing.Size(200, gw.Height),
                BackgroundColor = new Vector4(36f / 255, 36f / 255, 36f / 255, 1),
                BorderColor     = new Vector4(1, 1, 1, 1),
                Location        = new System.Drawing.Point(-201, 0),
            };

            var titleLabel = new Label()
            {
                Size      = new System.Drawing.Size(200, 50),
                Location  = new System.Drawing.Point(0, 10),
                Font      = new System.Drawing.Font("Arial", 20, System.Drawing.FontStyle.Underline),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Options"
            };

            int y     = 70;
            var label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Axial Tilt"
            };
            var @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.setAxialTiltDraw(((Switch)o).On);
            };
            panel.Controls.Add(titleLabel, label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Orbits"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.setOrbitDraw(((Switch)o).On);
            };
            panel.Controls.Add(label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Bloom Buffer"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y)
            };
            @switch.OnToggle += (o, e) =>
            {
                this.showBloomBuffer = ((Switch)o).On;
            };
            panel.Controls.Add(label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Bloom"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.bloom = ((Switch)o).On;
            };
            panel.Controls.Add(label, @switch);

            guiManager.Controls.Add(panel);
            #endregion
        }
Exemplo n.º 12
0
        public override BitmapBase Apply(Tank tank, BitmapBase layer)
        {
            if (_blur == null || _blur.Radius != Radius)
                lock (this)
                    if (_blur == null || _blur.Radius != Radius)
                        _blur = new GaussianBlur(Radius);

            BitmapBase shadow = layer.ToBitmapRam();
            var color = Color.GetColorWpf(tank);
            shadow.ReplaceColor(color);
            shadow.Blur(_blur, BlurEdgeMode.Transparent);
            shadow.ScaleOpacity(Spread, OpacityStyle.Additive);
            shadow.Transparentize(color.A);
            layer.DrawImage(shadow, below: true);
            return layer;
        }
Exemplo n.º 13
0
        //Blob Detection
        private Bitmap BlobDetection(Bitmap _bitmapSourceImage)
        {
            switch (iColorMode)
            {
            case 1:
                //_colorFilter.CenterColor = new RGB(230, 30, 30);
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 2:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 3:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;
            }

            Grayscale _grayscale = new Grayscale(0.2125, 0.7154, 0.0721);

            _bitmapGreyImage = _grayscale.Apply(_colorFilterImage);

            //create a edge detector instance
            if (_blurFlag == true)
            {
                //Blur _blurfilter = new Blur();
                GaussianBlur _blurfilter = new GaussianBlur();
                _bitmapBlurImage = _blurfilter.Apply(_bitmapGreyImage);
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapBlurImage);
            }
            else if (_blurFlag == false)
            {
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapGreyImage);
            }

            Threshold _threshold = new Threshold(iThreshold);

            _bitmapBinaryImage = _threshold.Apply(_bitmapEdgeImage);

            //Create a instance of blob counter algorithm
            BlobCounter _blobCounter = new BlobCounter();

            //Configure Filter
            _blobCounter.MinWidth    = 70;
            _blobCounter.MinHeight   = 70;
            _blobCounter.FilterBlobs = true;

            _blobCounter.ProcessImage(_bitmapBinaryImage);
            Blob[] _blobPoints = _blobCounter.GetObjectsInformation();

            Graphics _g = Graphics.FromImage(_bitmapSourceImage);

            SimpleShapeChecker _shapeChecker = new SimpleShapeChecker();

            for (int i = 0; i < _blobPoints.Length; i++)
            {
                List <IntPoint> _edgePoint = _blobCounter.GetBlobsEdgePoints(_blobPoints[i]);
                List <IntPoint> _corners   = null;
                AForge.Point    _center;
                float           _radius;

                if (_shapeChecker.IsQuadrilateral(_edgePoint, out _corners))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    System.Drawing.Point[] _coordinates = ToPointsArray(_corners);
                    int _x   = _coordinates[0].X;
                    int _y   = _coordinates[0].Y;
                    Pen _pen = new Pen(Color.Blue, ipenWidth);

                    if (_coordinates.Length == 4)
                    {
                        string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                        _g.DrawString(_shapeString, _font, _brush, _x, _y);
                        _g.DrawPolygon(_pen, ToPointsArray(_corners));
                    }
                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        ///for debug
                        //System.Diagnostics.Debug.WriteLine(
                        //    string.Format("Rect size: ({0}, {1})", rc.Width, rc.Height));

                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
                if (_shapeChecker.IsCircle(_edgePoint, out _center, out _radius))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    Pen    _pen         = new Pen(Color.Red, ipenWidth);
                    int    _x           = (int)_center.X;
                    int    _y           = (int)_center.Y;
                    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                    _g.DrawEllipse(_pen, (float)(_center.X - _radius),
                                   (float)(_center.Y - _radius),
                                   (float)(_radius * 2),
                                   (float)(_radius * 2));

                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        ///for debug
                        //System.Diagnostics.Debug.WriteLine(
                        //    string.Format("Circle size: ({0}, {1})", rc.Width, rc.Height));

                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        //textBox1.Text = dis.ToString("N2");
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
                if (_shapeChecker.IsTriangle(_edgePoint, out _corners))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    Pen    _pen         = new Pen(Color.Green, ipenWidth);
                    int    _x           = (int)_center.X;
                    int    _y           = (int)_center.Y;
                    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                    _g.DrawPolygon(_pen, ToPointsArray(_corners));

                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        ///for debug
                        //System.Diagnostics.Debug.WriteLine(
                        //    string.Format("Triangle Size: ({0}, {1})", rc.Width, rc.Height));

                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        //textBox1.Text = dis.ToString("N2");
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
            }
            return(_bitmapSourceImage);
        }
Exemplo n.º 14
0
        public BreezeInstance(ContentManager contentManager, SpriteBatch spriteBatch, Game game)
        {
            ScreenManager = new ScreenManager();
            SpriteBatch   = new SmartSpriteBatch(spriteBatch.GraphicsDevice);
            AssetLibrary  = new AssetLibrary(SpriteBatch);
            GaussianBlur  = new Breeze.Helpers.GaussianBlur(game);
            InputService  = new InputService();



#if WINDOWS_UAP
            StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            ContentPath         = folder.Path + "\\";
            ContentPathRelative = "\\";
#elif ANDROID
            Solids.ContentPath         = "Content\\";
            Solids.ContentPathRelative = "Content\\";
#else
            Solids.ContentPath         = "\\Ezmuze.Content\\";
            Solids.ContentPathRelative = "\\Ezmuze.Content\\";
#endif

#if WINDOWS_UAP
            //string pakPath = ContentPathRelative.GetFilePath("Content.pak");
            Debug.WriteLine(FileLocation.InstalledLocation);

            if (Storage.FileSystemStorage.FileExists(ContentPath.GetFilePath("Content.pak")))
            {
                string cpath = ContentPathRelative.GetFilePath("Content.pak");
                Debug.WriteLine("content pak path: " + cpath);
                StorageFile packBuffer = Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(cpath).GetAwaiter().GetResult();

                Stream stream       = packBuffer.OpenStreamForReadAsync().Result;
                int    streamLength = (int)stream.Length;
                byte[] tmp          = new byte[streamLength];
                stream.Read(tmp, 0, tmp.Length);

                string tocPath = ContentPathRelative.GetFilePath("Content.toc");

                Debug.WriteLine("Toc path: " + tocPath);
                var tocBuffer = Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(tocPath).GetAwaiter().GetResult();

                string json = FileIO.ReadTextAsync(tocBuffer).GetAwaiter().GetResult();



                Storage.DatfileStorage.TabletOfContents = JsonConvert.DeserializeObject <List <FileEntry> >(json);
                Storage.DatfileStorage.DataStorage      = tmp;
            }

            Debug.WriteLine("test!");
            //Solids.Breeze.Storage.Init(Solids.ContentPathRelative,tmp).ConfigureAwait(false).GetAwaiter().GetResult();
#elif ANDROID
            string pakPath = ("Content.pak");
            string tocPath = ("Content.toc");

            Stream tocBuffer = tocPath.FromAsset();
            var    sr        = new StreamReader(tocBuffer);
            string json      = sr.ReadToEnd();

            Solids.DatfileStorage.TabletOfContents = JsonConvert.DeserializeObject <List <Storage.FileEntry> >(json);

            var pakBuffer = pakPath.ToStream().Result;

            int length = Solids.DatfileStorage.TabletOfContents.Last().Start + Solids.DatfileStorage.TabletOfContents.Last().Length;

            byte[] data = new byte[length];
            pakBuffer.Read(data, 0, (int)length);
            Solids.DatfileStorage.DataStorage = data;
#endif
            Solids.Instance = this;



            //todo - this needs to be hella more dynamic
            Fonts = new Font
            {
                EuroStile  = new FontFamily("EuroStile", "eurostile"),
                Consolas   = new FontFamily("Consolas", "consolas"),
                MDL2       = new FontFamily("MDL2", "mdl"),
                Segoe      = new FontFamily("SegoeUI", "SegoeUI"),
                SegoeLight = new FontFamily("SegoeUILight", "SegoeUILight")
            };

            Fonts.Fonts.Add("EuroStile", Fonts.EuroStile);
            Fonts.Fonts.Add("Consolas", Fonts.Consolas);
            Fonts.Fonts.Add("MDL2", Fonts.MDL2);
            Fonts.Fonts.Add("Segoe", Fonts.Segoe);
            Fonts.Fonts.Add("SegoeLight", Fonts.SegoeLight);
        }
Exemplo n.º 15
0
        public static Image ApplyImageProperties(byte[] blobContent, ImageProperties properties)
        {
            Bitmap image = null;

            try {
                using (var ms = new MemoryStream(blobContent)) {
                    image = (Bitmap)System.Drawing.Image.FromStream(ms, false, false);
                    image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                    if (properties.Crop != null)
                    {
                        AForge.Imaging.Filters.Crop filter = new AForge.Imaging.Filters.Crop(new Rectangle(properties.Crop.XOffset, properties.Crop.YOffset, properties.Crop.CropWidth, properties.Crop.CropHeight));
                        image = filter.Apply(image);
                    }
                    if (properties.ImageWidth != properties.OriginalWidth || properties.ImageHeight != properties.OriginalHeight)
                    {
                        var filter = new ResizeBicubic(properties.ImageWidth, properties.ImageHeight);
                        image = filter.Apply(image);
                    }
                    if (properties.Colors != null)
                    {
                        if (properties.Colors.TransparentColor != null)
                        {
                            image.MakeTransparent(ColorTranslator.FromHtml("#" + properties.Colors.TransparentColor));
                        }
                        var brightness = properties.Colors.Brightness;
                        var bfilter    = new BrightnessCorrection(brightness);
                        bfilter.ApplyInPlace(image);
                        var contrast = properties.Colors.Contrast;
                        var cfilter  = new ContrastCorrection(contrast);
                        cfilter.ApplyInPlace(image);
                        if (properties.Colors.Hue != 0)
                        {
                            var         hue    = properties.Colors.Hue;
                            HueModifier filter = new HueModifier(hue);
                            filter.ApplyInPlace(image);
                        }
                        var saturation = properties.Colors.Saturation;
                        var sfilter    = new SaturationCorrection(saturation * 0.01f);
                        sfilter.ApplyInPlace(image);
                    }
                    # region Effects
                    if (!String.IsNullOrEmpty(properties.Effects))
                    {
                        var effects = properties.Effects.Split(';');
                        foreach (var item in effects)
                        {
                            switch (item)
                            {
                            case "Grayscale":
                                var g = new Grayscale(0.2125, 0.7154, 0.0721);
                                image = g.Apply(image);
                                break;

                            case "Sepia":
                                var s = new Sepia();
                                image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                                s.ApplyInPlace(image);
                                break;

                            case "Rotate Channels":
                                image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                                var r = new RotateChannels();
                                r.ApplyInPlace(image);
                                break;

                            case "Invert":
                                var i = new Invert();
                                i.ApplyInPlace(image);
                                break;

                            case "Blur":
                                var b = new Blur();
                                b.ApplyInPlace(image);
                                break;

                            case "Gaussian Blur":
                                var gb = new GaussianBlur(4, 11);
                                gb.ApplyInPlace(image);
                                break;

                            case "Convolution":
                                int[,] kernel = { { -2, -1, 0 }, { -1, 1, 1 }, { 0, 1, 2 } };
                                var c = new Convolution(kernel);
                                c.ApplyInPlace(image);
                                break;

                            case "Edges":
                                var e = new Edges();
                                e.ApplyInPlace(image);
                                break;
                            }
                        }
                    }
                    # endregion
                }
            } catch (Exception) {
Exemplo n.º 16
0
        private static void FinalizeFrame(Tomogram tom, Random rand, MRCFile file,
                                          string serializedSamplerPath)
        {
            float minValue = file.MinPixelValue;
            float maxValue = file.MaxPixelValue;

            tom.MRCScaler            = 255.0f / (maxValue - minValue);
            tom.MinimumTomogramValue = minValue;

            int[] classes = tom.DataClasses.Where(n => n != -1).Distinct().ToArray();

            Dictionary <int, float> classValues = new Dictionary <int, float>();

            for (int c = 0; c < classes.Length; c++)
            {
                MRCFrame frame = file.Frames[145];// rand.Next(0, file.Frames.Count - 1)];

                int   randomX     = rand.Next(511, 611);
                int   randomY     = rand.Next(292, 392);
                int   randomIndex = randomY * frame.Width + randomX;
                float value       = frame.Data[randomIndex];
                classValues.Add(classes[c], value);
            }

            for (int y = 0, i = 0; y < tom.Height; y++)
            {
                for (int x = 0; x < tom.Width; x++, i++)
                {
                    int classNumber = tom.DataClasses[i];
                    if (classNumber >= 0)
                    {
                        tom.Data[i] = classValues[classNumber];
                    }
                }
            }


            List <float>    distribution = null;
            BinaryFormatter bf           = new BinaryFormatter();

            using (FileStream fin = File.OpenRead(serializedSamplerPath))
            {
                distribution = bf.Deserialize(fin) as List <float>;
            }

            int[] mask = new int[tom.Width * tom.Height];

            for (int y = 0, i = 0; y < tom.Height; y++)
            {
                for (int x = 0; x < tom.Width; x++, i++)
                {
                    int classNumber = tom.DataClasses[i];
                    if (classNumber == -1)
                    {
                        tom.Data[i] = distribution[rand.Next(0, distribution.Count - 1)];
                        mask[i]     = 0;
                    }
                    else
                    {
                        mask[i] = 1;
                    }
                }
            }
            //            tom.Data = blur.BlurData(tom.Data, tom.Width, tom.Height);

            GaussianBlur blur = GaussianBlur.BuildBlur(.65f, tom.BlurRadius);

            tom.Data = blur.SelectivelyBlurData(tom.Data, mask, tom.Width, tom.Height, 1f, rand);

            float[] finalData        = new float[tom.FinalHeight * tom.FinalWidth];
            int[]   finalDataClasses = new int[tom.FinalHeight * tom.FinalWidth];

            for (int y = 0, dstIndex = 0; y < tom.FinalHeight; y++)
            {
                for (int x = 0; x < tom.FinalHeight; x++, dstIndex++)
                {
                    int srcIndex = (y + tom.BlurRadius) * tom.Width + (x + tom.BlurRadius);
                    finalData[dstIndex]        = tom.Data[srcIndex];
                    finalDataClasses[dstIndex] = tom.DataClasses[srcIndex];
                }
            }

            // hack. clean this up.
            tom.Data        = finalData;
            tom.DataClasses = finalDataClasses;
            tom.Width       = tom.FinalWidth;
            tom.Height      = tom.FinalHeight;
        }
        private async Task CalibThread(FrameReadyEventArgs e)
        {
            Debug.WriteLine("Calibrating " + _calibrationStep + " ");
            e.Frame.Bitmap.Save(@"C:\temp\daforge\src\img" + (_calibrationStep < 10?"0":"") + _calibrationStep + "-" + _errors + ".jpg", ImageFormat.Jpeg);
            if (_errors > 100)
            {
                //calibration not possible
                return;
            }
            if (_calibrationStep > CalibrationFrames)
            {
                // A concurrency problem, do nothing
            }
            if (_calibrationStep == CalibrationFrames)
            {
                _cc.FrameReady -= BaseCalibration;
                _calibrationStep++;
                //Grid.Calculate();
                _vs.Close();
                CalibrationCompleted(this, new EventArgs());
            }
            else
            {
                if (_calibrationStep > 2)
                {
                    // analyse diffimage
                    _vs.Clear();
                    var img = diffFilter.Apply(e.Frame.Bitmap);
                    var mf  = new GaussianBlur(0.6, 5);
                    var gf  = Grayscale.CommonAlgorithms.BT709;
#if DEBUG
                    actImg = (Bitmap)img.Clone();
#endif
                    img = gf.Apply(img);
                    var stats = new ImageStatistics(img);
                    mf.ApplyInPlace(img);
                    mf = new GaussianBlur(0.7, 7);
                    mf.ApplyInPlace(img);
                    var tf = new Threshold((int)(stats.GrayWithoutBlack.Mean + stats.GrayWithoutBlack.StdDev * 2.0));
                    tf.ApplyInPlace(img);
                    img.Save(@"C:\temp\daforge\diff\img" + _calibrationStep + "-" + _errors + ".jpg", ImageFormat.MemoryBmp);
                    var blobCounter = new BlobCounter
                    {
                        ObjectsOrder         = ObjectsOrder.YX,
                        MaxHeight            = 30,
                        MinHeight            = 10,
                        MaxWidth             = 30,
                        MinWidth             = 10,
                        FilterBlobs          = true,
                        CoupledSizeFiltering = false
                    };
                    blobCounter.ProcessImage(img);
                    if (ProcessBlobs(blobCounter))
                    {
                        _calibrationStep++;
                    }
                    else
                    {
                        _errors++;
                    }
#if DEBUG
                    actImg.Save(@"C:\temp\daforge\squares\img" + _calibrationStep + ".jpg", ImageFormat.Jpeg);
#endif
                    DrawMarkers();
                }
                else
                {
                    switch (_calibrationStep)
                    {
                    case 2:
                        var bm = UnmanagedImage.FromManagedImage(e.Frame.Bitmap);
                        //diffFilter.OverlayImage.Save(@"C:\temp\daforge\diff\src" + _errors + ".jpg", ImageFormat.Jpeg);
                        bm = diffFilter.Apply(bm);
                        var gf = new GaussianBlur(0.8, 5);
                        gf.ApplyInPlace(bm);
                        var cf = new ColorFiltering(new IntRange(10, 255), new IntRange(20, 255),
                                                    new IntRange(20, 255));
                        cf.ApplyInPlace(bm);
                        var blobCounter = new BlobCounter
                        {
                            ObjectsOrder = ObjectsOrder.Size,
                            MinHeight    = 200,
                            MinWidth     = 300,
                            //BackgroundThreshold = Color.FromArgb(255, 20, 20, 50),
                            //CoupledSizeFiltering = false,
                            FilterBlobs = true
                        };
                        blobCounter.ProcessImage(bm);
                        bm.ToManagedImage()
                        .Save(@"C:\temp\daforge\diff\img" + _calibrationStep + "-" + _errors + ".jpg",
                              ImageFormat.Jpeg);
                        var blobs = blobCounter.GetObjectsInformation();
                        if (blobs.Any())
                        {
                            int             i = 0;
                            List <IntPoint> corners;
                            do
                            {
                                corners =
                                    PointsCloud.FindQuadrilateralCorners(blobCounter.GetBlobsEdgePoints(blobs[i++]));
                            } while (corners.Count != 4);
                            RecursiveAForgeCalibrator.GridBlobs.InPlaceSort(corners);
                            Grid.TopLeft     = new Point(corners[0].X, corners[0].Y);
                            Grid.TopRight    = new Point(corners[1].X, corners[1].Y);
                            Grid.BottomLeft  = new Point(corners[2].X, corners[2].Y);
                            Grid.BottomRight = new Point(corners[3].X, corners[3].Y);
                            if (Grid.TopLeft.X > 10 && Grid.TopRight.X < _vs.Width - 5 && Grid.BottomLeft.X > 5 &&
                                Grid.BottomRight.X < _vs.Width - 5 && Grid.TopLeft.Y > 10 && Grid.TopRight.Y > 5 &&
                                Grid.BottomLeft.Y < _vs.Height - 5 && Grid.BottomRight.Y < _vs.Height - 5 &&
                                Grid.TopLeft.X < Grid.BottomRight.X &&
                                Grid.BottomLeft.X < Grid.TopRight.X && Grid.BottomLeft.X < Grid.BottomRight.X &&
                                Grid.TopLeft.Y < Grid.BottomLeft.Y && Grid.TopLeft.Y < Grid.BottomRight.Y &&
                                Grid.TopRight.Y < Grid.BottomLeft.Y && Grid.TopRight.Y < Grid.BottomRight.Y)
                            {
                                _calibrationStep++;
                                _vs.Clear();
                                Grid.AddPoint(new Point(), new Point(corners[0].X, corners[0].Y));
                                Grid.AddPoint(new Point(0, _vs.Height), new Point(corners[1].X, corners[1].Y));
                                Grid.AddPoint(new Point(_vs.Width, 0), new Point(corners[2].X, corners[2].Y));
                                Grid.AddPoint(new Point(_vs.Width, _vs.Height),
                                              new Point(corners[3].X, corners[3].Y));
                                DrawMarkers();
                            }
                            else
                            {
                                _calibrationStep = 0;
                                _errors++;
                            }
                        }
                        else
                        {
                            _calibrationStep = 0;
                            _errors++;
                        }
                        break;

                    case 1:
                        diffFilter.OverlayImage = e.Frame.Bitmap;
                        //diffFilter.OverlayImage.Save(@"C:\temp\daforge\diff\srcf" + _errors + ".jpg", ImageFormat.Jpeg);
                        //_vs.AddRect(0, 0, (int) _vs.Width, (int) _vs.Height, Color.FromArgb(255, 255, 255, 255));
                        _vs.Clear();
                        DrawInverted(0, 0, _vs.Width, _vs.Height);
                        _vs.Draw();
                        _calibrationStep++;
                        break;

                    case 0:
                        Grid            = new Grid(e.Frame.Bitmap.Width, e.Frame.Bitmap.Height);
                        Grid.ScreenSize = new Rectangle(0, 0, _vs.Width, _vs.Height);
                        var thread = new Thread(() =>
                        {
                            _vs.Show();
                        });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();
                        DrawBackground();
                        _vs.Draw();
                        _calibrationStep++;
                        break;
                    }
                }
            }
            Debug.WriteLine("Releasing");
            await Task.Delay(500);

            _sem.Release();
        }
Exemplo n.º 18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_Goo goo   = null;
            Image   image = new Image();

            if (!DA.GetData(0, ref goo))
            {
                return;
            }
            if (!goo.TryGetImage(ref image))
            {
                return;
            }

            int mode = 0;

            DA.GetData(1, ref mode);

            double numValA = 0;

            DA.GetData(2, ref numValA);

            double numValB = 0;

            DA.GetData(3, ref numValB);

            Filter filter = new Filter();

            switch ((FilterModes)mode)
            {
            case FilterModes.Additive:
                SetParameter(2);
                SetParameter(3);
                filter = new Additive();
                image.Filters.Add(new Additive());
                break;

            case FilterModes.Daube:
                SetParameter(2, "S", "Size", "[0-1] Unitized adjustment value");
                SetParameter(3);
                filter = new Daube(numValA);
                image.Filters.Add(new Daube(numValA));
                break;

            case FilterModes.SaltPepper:
                SetParameter(2, "N", "Noise", "[0-1] Unitized adjustment value");
                SetParameter(3);
                filter = new SaltPepper(numValA);
                image.Filters.Add(new SaltPepper(numValA));
                break;

            case FilterModes.Jitter:
                SetParameter(2, "R", "Radius", "[0-1] Unitized adjustment value");
                SetParameter(3);
                filter = new Jitter(numValA);
                image.Filters.Add(new Jitter(numValA));
                break;

            case FilterModes.Kuwahara:
                SetParameter(2, "S", "Size", "[0-1] Unitized adjustment value");
                SetParameter(3);
                filter = new Kuwahara(numValA);
                image.Filters.Add(new Kuwahara(numValA));
                break;

            case FilterModes.Posterize:
                SetParameter(2, "I", "Interval", "[0-1] Unitized adjustment value");
                SetParameter(3);
                filter = new Posterize(numValA);
                image.Filters.Add(new Posterize(numValA));
                break;

            case FilterModes.GaussianBlur:
                SetParameter(2, "X", "Sigma", "[0-1] Unitized adjustment value");
                SetParameter(3, "S", "Size", "[0-1] Unitized adjustment value");
                filter = new GaussianBlur(numValA, numValB);
                image.Filters.Add(new GaussianBlur(numValA, numValB));
                break;

            case FilterModes.Pixellate:
                SetParameter(2, "W", "Width", "[0-1] Unitized adjustment value");
                SetParameter(3, "H", "Height", "[0-1] Unitized adjustment value");
                filter = new Pixellate(numValA, numValB);
                image.Filters.Add(new Pixellate(numValA, numValB));
                break;

            case FilterModes.Blur:
                SetParameter(2, "D", "Divisor", "[0-1] Unitized adjustment value");
                SetParameter(3, "T", "Threshold", "[0-1] Unitized adjustment value");
                filter = new Blur(numValA, numValB);
                image.Filters.Add(new Blur(numValA, numValB));
                break;
            }

            message = ((FilterModes)mode).ToString();
            UpdateMessage();

            DA.SetData(0, image);
            DA.SetData(1, filter);
        }
Exemplo n.º 19
0
        static public void BoxShadow(Bitmap processBitmap, int shadowRadius, int[] cornersType, int[] cornersRadius)
        {
            int r         = shadowRadius;
            int sideWidth = shadowRadius;
            int offset    = 2;

            Graphics     g;
            Bitmap       bitmap;
            Rectangle    rc;
            Rectangle    rc1;
            Bitmap       effectBitmap;
            GraphicsPath path;
            GaussianBlur gs = new GaussianBlur(r);

            int      width  = processBitmap.Width;
            int      height = processBitmap.Height;
            Graphics baseg  = Graphics.FromImage(processBitmap);

            //
            int leftTopWidth  = sideWidth + r;
            int leftTopHeight = sideWidth + r;

            bitmap = new Bitmap(leftTopWidth, leftTopHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(sideWidth, sideWidth, r, r);

            if (cornersType[0] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, 0, new Rectangle(0, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path            = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, 0, new Rectangle(0, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, sideWidth, sideWidth, new Rectangle(sideWidth, sideWidth, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();


            ////
            int rightTopWidth  = sideWidth + r;
            int rightTopHeight = sideWidth + r;

            bitmap = new Bitmap(rightTopWidth, rightTopHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(0, sideWidth, r, r);

            if (cornersType[0] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, 0, new Rectangle(rightTopWidth - sideWidth, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path            = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, 0, new Rectangle(rightTopWidth - sideWidth, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, width - sideWidth - r, sideWidth, new Rectangle(0, sideWidth, r, r), GraphicsUnit.Pixel);
            }
            g.Dispose();
            bitmap.Dispose();

            ////
            int leftBottomWidth  = sideWidth + r;
            int leftBottomHeight = sideWidth + r;

            bitmap = new Bitmap(leftBottomWidth, leftBottomHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(sideWidth, 0, r, r);

            if (cornersType[2] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, height - sideWidth, new Rectangle(0, leftBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path            = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, height - sideWidth, new Rectangle(0, leftBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, sideWidth, height - sideWidth - r, new Rectangle(sideWidth, 0, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();

            ////
            int rightBottomWidth  = sideWidth + r;
            int rightBottomHeight = sideWidth + r;

            bitmap = new Bitmap(rightBottomWidth, rightBottomHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(0, 0, r, r);

            if (cornersType[3] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, height - sideWidth, new Rectangle(rightBottomHeight - sideWidth, rightBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path            = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, height - sideWidth, new Rectangle(rightBottomHeight - sideWidth, rightBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, width - sideWidth - r, height - sideWidth - r, new Rectangle(0, 0, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();


            ////
            int topWidth  = width;
            int topHeight = r + sideWidth;

            bitmap = new Bitmap(topWidth, topHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(sideWidth, sideWidth, width - sideWidth * 2, r);

            if (cornersType[0] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[1] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, sideWidth, 0, new Rectangle(sideWidth, 0, topWidth - sideWidth * 2, sideWidth), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int bottomWidth  = width;
            int bottomHeight = r + sideWidth;

            bitmap = new Bitmap(bottomWidth, bottomHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(sideWidth, 0, bottomWidth - 2 * sideWidth, r);

            if (cornersType[2] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[3] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, sideWidth, height - sideWidth, new Rectangle(sideWidth, bottomHeight - sideWidth, bottomWidth - sideWidth * 2, sideWidth), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int leftWidth  = sideWidth + r;
            int leftHeight = height;

            bitmap = new Bitmap(leftWidth, leftHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(sideWidth, sideWidth, r, leftHeight - sideWidth * 2);

            if (cornersType[0] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[2] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[2]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, 0, sideWidth, new Rectangle(0, sideWidth, sideWidth, leftHeight - sideWidth * 2), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int rightWidth  = sideWidth + r;
            int rightHeight = height;

            bitmap = new Bitmap(leftWidth, leftHeight);
            g      = Graphics.FromImage(bitmap);
            rc     = new Rectangle(0, sideWidth, r, rightHeight - sideWidth * 2);


            if (cornersType[1] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[3] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1             = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                path            = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[3]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, width - sideWidth, sideWidth, new Rectangle(leftWidth - sideWidth, sideWidth, sideWidth, leftHeight - sideWidth * 2), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            baseg.Dispose();
        }
Exemplo n.º 20
0
        private void generateHeightmap_Click(object sender, EventArgs e)
        {
            Heightmap heightmap = Heightmap.Instance;

            heightmap.SetDimensions((int)mapWidth.Value, (int)mapHeight.Value);
            int seed;

            if (this.enableSeed.Checked)
            {
                seed = (int)seedVal.Value;
            }
            else
            {
                seed          = (new Random()).Next();
                seedVal.Value = (Decimal)seed;
            }

            heightmap.DiffusionLimitedAgregation(seed, (float)(this.occupation.Value / this.occupation.Maximum),
                                                 (int)this.frequency.Value);

            // apply gaussian pass, multiple kernel sizes sum and normalize
            if (gaussianEnable.Checked)
            {
                List <Bitmap> dlaCopies     = new List <Bitmap>();
                Bitmap        dilatedBitmap = (Bitmap)heightmap.Texture.Clone();
                AForge.Imaging.Filters.GaussianBlur gaussian         = new AForge.Imaging.Filters.GaussianBlur(4.0, 21);
                AForge.Imaging.Filters.Dilatation   dilatationFilter = new AForge.Imaging.Filters.Dilatation();
                GaussianBlur gaus = new GaussianBlur(2);

                for (int i = 0; i < (int)copyCount.Value; i++)
                {
                    // apply filter, first increasinly dilate the picture
                    dilatedBitmap = dilatationFilter.Apply(dilatedBitmap);
                    // then apply gaussian blur with an increasing radius size
                    Bitmap blurredBitmap = (Bitmap)dilatedBitmap.Clone();

                    if (radialBlur.Checked)
                    {
                        for (int j = 0; j < (i * 3) + 1; j++)
                        {
                            blurredBitmap = gaussian.Apply(blurredBitmap);
                        }
                    }
                    else
                    {
                        gaus.Radius   = (int)Math.Pow(2, i + 1);
                        blurredBitmap = gaus.ProcessImage(blurredBitmap);
                    }

                    dlaCopies.Add(blurredBitmap);
                }

                // add noise to final texture collections
                if (noiseEnabled.Checked)
                {
                    dlaCopies.Add(NoiseTexture((int)perlinOctaves.Value, (double)perlinPersistence.Value,
                                               (double)perlinFreq.Value, (double)perlinAmplitude.Value));
                }

                // normalize all blurred heightmaps
                Bitmap     bmp       = (Bitmap)heightmap.Texture.Clone();
                BitmapData bmpData   = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
                byte[]     finalData = new byte[bmpData.Height * bmpData.Stride];

                // sum average between all blurred pictures
                for (int i = 0; i < dlaCopies.Count; i++)
                {
                    // AForge.Imaging.Filters addFilter = new AForge.Imaging.Filters.Add(blurredBitmap);
                    Bitmap     current     = dlaCopies[i];
                    BitmapData currentData = current.LockBits(new Rectangle(0, 0, current.Width, current.Height), ImageLockMode.ReadOnly,
                                                              current.PixelFormat);
                    byte[] currentRawData = new byte[currentData.Height * currentData.Stride];
                    Marshal.Copy(currentData.Scan0, currentRawData, 0, currentData.Height * currentData.Stride);
                    // lamba operation sums averages between blurred pictures
                    Parallel.For(0, currentRawData.Length, index =>
                    {
                        finalData[index] = (byte)(currentRawData[index] * 1.0f / (float)dlaCopies.Count + finalData[index]);
                    });
                }

                // save final raw pixel data
                Marshal.Copy(finalData, 0, bmpData.Scan0, finalData.Length);
                bmp.UnlockBits(bmpData);
                // store final values on heightmap
                heightmap.MapValues = finalData;
                heightmap.Texture   = bmp;
            }

            // show height map, set up new values
            this.heightmapPicture.Height = heightmap.Height;
            this.heightmapPicture.Width  = heightmap.Width;
            this.heightmapPicture.Image  = heightmap.Texture;
        }
Exemplo n.º 21
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="DifferenceOfGaussians"/> class.
        /// </summary>
        /// 
        public DifferenceOfGaussians()
        {
            formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
            formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed;
            formatTranslations[PixelFormat.Format16bppGrayScale] = PixelFormat.Format16bppGrayScale;
            formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb;
            formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format32bppRgb;
            formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb;
            formatTranslations[PixelFormat.Format48bppRgb] = PixelFormat.Format48bppRgb;
            formatTranslations[PixelFormat.Format64bppArgb] = PixelFormat.Format64bppArgb;

            this.first = new GaussianBlur()
            {
                Size = 3,
                Sigma = 0.4
            };

            this.second = new GaussianBlur()
            {
                Size = 5,
                Sigma = 0.4
            };

            this.subtract = new Subtract();
        }
Exemplo n.º 22
0
        public void GetImageProcess()//显示图片时读取
        {
            XmlNode node = xmlDoc.SelectSingleNode("PatientBackImage/Image[@Name='" + ImageName + "'] ");

            if (node != null)
            {
                if (node.HasChildNodes)
                {
                    XmlNodeList xmlNolist = node.ChildNodes;
                    foreach (XmlNode xn in xmlNolist)
                    {
                        XmlElement xmlE = (XmlElement)xn;
                        switch (xmlE.Name)
                        {
                        case "DrawLine":
                            DrawLine dl = new DrawLine(Convert.ToInt32(xmlE.GetAttribute("StartPointX")), Convert.ToInt32(xmlE.GetAttribute("StartPointY")), Convert.ToInt32(xmlE.GetAttribute("EndPointX")), Convert.ToInt32(xmlE.GetAttribute("EndPointY")));
                            dl.ID = Convert.ToInt32(xmlE.GetAttribute("ID"));
                            frmImgProcess.imgProcess.drawArea.GraphicsList.UnselectAll();
                            frmImgProcess.imgProcess.drawArea.GraphicsList.Add(dl);
                            frmImgProcess.imgProcess.drawArea.Capture = true;
                            frmImgProcess.imgProcess.drawArea.Refresh();
                            break;

                        case "DrawRectangle":
                            DrawRectangle dr = new DrawRectangle(Convert.ToInt32(xmlE.GetAttribute("X")), Convert.ToInt32(xmlE.GetAttribute("Y")), Convert.ToInt32(xmlE.GetAttribute("Width")), Convert.ToInt32(xmlE.GetAttribute("Height")));
                            dr.ID = Convert.ToInt32(xmlE.GetAttribute("ID"));
                            frmImgProcess.imgProcess.drawArea.GraphicsList.UnselectAll();
                            frmImgProcess.imgProcess.drawArea.GraphicsList.Add(dr);
                            frmImgProcess.imgProcess.drawArea.Capture = true;
                            frmImgProcess.imgProcess.drawArea.Refresh();
                            break;

                        case "DrawEllipse":
                            DrawEllipse de = new DrawEllipse(Convert.ToInt32(xmlE.GetAttribute("X")), Convert.ToInt32(xmlE.GetAttribute("Y")), Convert.ToInt32(xmlE.GetAttribute("Width")), Convert.ToInt32(xmlE.GetAttribute("Height")));
                            de.ID = Convert.ToInt32(xmlE.GetAttribute("ID"));
                            frmImgProcess.imgProcess.drawArea.GraphicsList.UnselectAll();
                            frmImgProcess.imgProcess.drawArea.GraphicsList.Add(de);
                            frmImgProcess.imgProcess.drawArea.Capture = true;
                            frmImgProcess.imgProcess.drawArea.Refresh();
                            break;

                        case "DrawPoint":
                            DrawPoint dp = new DrawPoint(Convert.ToInt32(xmlE.GetAttribute("X")), Convert.ToInt32(xmlE.GetAttribute("Y")));
                            dp.ID = Convert.ToInt32(xmlE.GetAttribute("ID"));
                            frmImgProcess.imgProcess.drawArea.GraphicsList.UnselectAll();
                            frmImgProcess.imgProcess.drawArea.GraphicsList.Add(dp);
                            frmImgProcess.imgProcess.drawArea.Capture = true;
                            frmImgProcess.imgProcess.drawArea.Refresh();
                            break;

                        case "DrawPolygon":
                            DrawPolygon dpy      = new DrawPolygon();
                            string      pointStr = xmlE.GetAttribute("pointStr");
                            string[]    poList   = pointStr.Split('$');
                            string[]    p        = { };
                            for (int i = 0; i < poList.Length; i++)
                            {
                                if (poList[i].ToString() != "")
                                {
                                    p = poList[i].Split(',');
                                    Point point = new Point(Convert.ToInt32(p[0]), Convert.ToInt32(p[1]));
                                    dpy.pointArray.Add(point);
                                }
                            }
                            dpy.ID = Convert.ToInt32(xmlE.GetAttribute("ID"));
                            frmImgProcess.imgProcess.drawArea.GraphicsList.UnselectAll();
                            frmImgProcess.imgProcess.drawArea.GraphicsList.Add(dpy);
                            frmImgProcess.imgProcess.drawArea.Capture = true;
                            frmImgProcess.imgProcess.drawArea.Refresh();
                            break;

                        case "TextBox":
                            ToolText tx = new ToolText(frmImgProcess.imgProcess.drawArea);
                            tx.Location     = new Point(Convert.ToInt32(xmlE.GetAttribute("X")), Convert.ToInt32(xmlE.GetAttribute("Y")));
                            tx.Width        = Convert.ToInt32(xmlE.GetAttribute("Width"));
                            tx.Height       = Convert.ToInt32(xmlE.GetAttribute("Height"));
                            tx.Name         = xmlE.GetAttribute("ID");
                            tx.Min          = true;
                            tx.Max          = true;
                            tx.IsChangeSize = true;
                            tx.ReadOnly     = false;
                            tx.IsMove       = true;
                            tx.Text         = xmlE.GetAttribute("Content");
                            tx.ForeColor    = System.Drawing.Color.Red;
                            frmImgProcess.imgProcess.drawArea.Controls.Add(tx);
                            break;

                        case "Process":
                            XmlNode nodeProcess = xmlDoc.SelectSingleNode("PatientBackImage/Image[@Name='" + ImageName + "']/Process ");
                            if (nodeProcess != null)
                            {
                                if (nodeProcess.HasChildNodes)
                                {
                                    XmlNodeList xmlNodeProcesslist = nodeProcess.ChildNodes;
                                    foreach (XmlNode xn2 in xmlNodeProcesslist)
                                    {
                                        XmlElement xmlE2 = (XmlElement)xn2;

                                        switch (xmlE2.Name)
                                        {
                                        case "BrightnessCorrection":        //亮度
                                            BrightnessCorrection brightnesscorr = new BrightnessCorrection();
                                            brightnesscorr.AdjustValue = double.Parse(xmlE2.GetAttribute("Value"));
                                            frmImgProcess.imgProcess.ApplyFilter(brightnesscorr);
                                            break;

                                        case "ContrastCorrection":        //对比
                                            ContrastCorrection contrastCorr = new ContrastCorrection();
                                            contrastCorr.Factor = double.Parse(xmlE2.GetAttribute("Value"));
                                            frmImgProcess.imgProcess.ApplyFilter(contrastCorr);
                                            break;

                                        case "HueModifier":        //色相
                                            HueModifier huemodifier = new HueModifier();
                                            huemodifier.Hue = int.Parse(xmlE2.GetAttribute("Value"));
                                            frmImgProcess.imgProcess.ApplyFilter(huemodifier);
                                            break;

                                        case "Saturation":        //饱和度
                                            SaturationCorrection saturationcorr = new SaturationCorrection();
                                            saturationcorr.AdjustValue = double.Parse(xmlE2.GetAttribute("Value"));
                                            frmImgProcess.imgProcess.ApplyFilter(saturationcorr);
                                            break;

                                        case "GrayscaleBT709":        //灰度
                                            GrayscaleBT709 grayscalebt = new GrayscaleBT709();
                                            frmImgProcess.imgProcess.ApplyFilter(grayscalebt);
                                            break;

                                        case "Filter":        //过滤
                                            ColorFiltering colorfilter = new ColorFiltering();
                                            IntRange       red = new IntRange(0, 255);
                                            IntRange       green = new IntRange(0, 255);
                                            IntRange       blue = new IntRange(0, 255);
                                            byte           fillR = 0, fillG = 0, fillB = 0;
                                            string         fillType = "";
                                            red.Min               = int.Parse(xmlE2.GetAttribute("RedMin"));
                                            red.Max               = int.Parse(xmlE2.GetAttribute("RedMax"));
                                            green.Min             = int.Parse(xmlE2.GetAttribute("GreenMin"));
                                            green.Max             = int.Parse(xmlE2.GetAttribute("GreenMax"));
                                            blue.Min              = int.Parse(xmlE2.GetAttribute("BlueMin"));
                                            blue.Max              = int.Parse(xmlE2.GetAttribute("BlueMax"));
                                            fillR                 = byte.Parse(xmlE2.GetAttribute("FillRed"));
                                            fillG                 = byte.Parse(xmlE2.GetAttribute("FillGreen"));
                                            fillB                 = byte.Parse(xmlE2.GetAttribute("FillBlue"));
                                            fillType              = xmlE2.GetAttribute("FillType");
                                            colorfilter.Red       = red;
                                            colorfilter.Green     = green;
                                            colorfilter.Blue      = blue;
                                            colorfilter.FillColor = new RGB(fillR, fillG, fillB);
                                            if (fillType == "OutSide")
                                            {
                                                colorfilter.FillOutsideRange = true;
                                            }
                                            else
                                            {
                                                colorfilter.FillOutsideRange = false;
                                            }
                                            frmImgProcess.imgProcess.ApplyFilter(colorfilter);
                                            break;

                                        case "Gaussian":        //柔化
                                            GaussianBlur gaussianBlur = new GaussianBlur();
                                            gaussianBlur.Sigma = double.Parse(xmlE2.GetAttribute("Sigma"));
                                            gaussianBlur.Size  = int.Parse(xmlE2.GetAttribute("Size"));
                                            frmImgProcess.imgProcess.ApplyFilter(gaussianBlur);
                                            break;

                                        case "DifferenceEdgeDetector":        //边缘增强
                                            DifferenceEdgeDetector differenceEdgeD = new DifferenceEdgeDetector();
                                            frmImgProcess.imgProcess.ApplyFilter(differenceEdgeD);
                                            break;

                                        case "RotateFlip":        //镜像
                                            frmImgProcess.imgProcess.drawArea.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                                            frmImgProcess.imgProcess.drawArea.Refresh();
                                            break;

                                        case "PerlinNoise":        //去噪
                                            string value = "";
                                            value = xmlE2.GetAttribute("Value");

                                            float imageWidth  = 0;
                                            float imageHeight = 0;
                                            switch (value)
                                            {
                                            case "Marble":
                                                filter = new Texturer(new MarbleTexture(imageWidth / 96, imageHeight / 48), 0.7f, 0.3f);
                                                break;

                                            case "Wood":
                                                filter = new Texturer(new WoodTexture(), 0.7f, 0.3f);
                                                break;

                                            case "Clouds":
                                                filter = new Texturer(new CloudsTexture(), 0.7f, 0.3f);
                                                break;

                                            case "Labyrinth":
                                                filter = new Texturer(new LabyrinthTexture(), 0.7f, 0.3f);
                                                break;

                                            case "Textile":
                                                filter = new Texturer(new TextileTexture(), 0.7f, 0.3f);
                                                break;

                                            case "Dirty":
                                                TexturedFilter f = new TexturedFilter(new CloudsTexture(), new Sepia());
                                                f.PreserveLevel = 0.30f;
                                                f.FilterLevel   = 0.90f;
                                                filter          = f;
                                                break;

                                            case "Rusty":
                                                filter = new TexturedFilter(new CloudsTexture(), new Sepia(), new GrayscaleBT709());
                                                break;
                                            }
                                            frmImgProcess.imgProcess.ApplyFilter(filter);
                                            break;

                                        case "Sharpen":
                                            Sharpen sharpen = new Sharpen();
                                            frmImgProcess.imgProcess.ApplyFilter(sharpen);
                                            break;

                                        case "Mean":
                                            Mean mean = new Mean();
                                            frmImgProcess.imgProcess.ApplyFilter(mean);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Primary draw method.
        /// </summary>
        /// <param name="gameTime">Handeled by the framework, the passage of time is updated automagically.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            _skybox.Draw(_camera.View, _camera.Projection, _camera.Position);

            foreach (BasicModel model in _models)
            {
                if (_camera.BoundingVolumeIsInView(model.BoundingSphere))
                {
                    model.Draw(_camera.View, _camera.Projection, _camera.Position);
                }
            }

            _lineDrawer.Begin(_camera.View, _camera.Projection);

            _lineDrawer.DrawHexagonGrid(Vector2.One * -9930, (new Vector2(80, 40)), 200, Color.Red);
            _lineDrawer.DrawLine(_models[0].Position, new Vector3(_models[0].Position.X, 0, _models[0].Position.Z), Color.CornflowerBlue);

            ShipMovement.DrawHeading();
            ShipMovement.DrawMarker();

            _lineDrawer.End();

            _stars.Draw(_camera.View, _camera.Projection, _camera.Up, _camera.Right);

            // if rendered card buffer is null, initialize it here
            if (_renderedCardBuffer == null)
            {
                // Choosing a random card for testing...
                Random r = new Random();
                //Card c = _cards[r.Next(_cards.Count)];
                Card c = null;
                foreach (Card cx in _cards)
                {
                    if (cx.Title == "Patrol Drone")
                    //if (_rulesTextFont.MeasureString(WrapText(_rulesTextFont, cx.RulesText, _cardRulesWidth)).Y > _cardRulesHeight)
                    {
                        c = cx;
                        //Debug.WriteLine("{0}", _rulesTextFont.MeasureString(WrapText(_rulesTextFont, cx.RulesText, _cardRulesWidth)).Y - _cardRulesHeight);
                        break;
                    }
                }

                string someRandomText = c.RulesText;
                someRandomText = WrapText(_rulesTextFont, someRandomText, _cardRulesWidth);
                Vector2 textSize = _rulesTextFont.MeasureString(someRandomText);

                string  titleString = c.Title;
                Vector2 titleSize   = _titleFont.MeasureString(titleString);

                string typeString    = c.Supertype.ToString();
                string subtypeString = c.Subtype.ToString();
                if (subtypeString != "None")
                {
                    typeString = typeString + " - " + c.Subtype.ToString();
                }
                Vector2 typeSize = _typeFont.MeasureString(typeString);

                string  costString = (c.EnergyCostType == AmountType.Variable) ? Description.ToDescription(c.EnergyCostVar).Replace("+", string.Empty) : c.EnergyCost.ToString();
                Vector2 costSize   = _statFont.MeasureString(costString);

                Rectangle cardRect = new Rectangle(
                    0,
                    0,
                    _cardTexture.Width,
                    _cardTexture.Height);

                float titleScale = 1;
                if (titleSize.X > _cardTitleWidth)
                {
                    titleScale = _cardTitleWidth / titleSize.X;
                }

                float typeScale = 1;
                if (typeSize.X > _cardTypeWidth)
                {
                    typeScale = _cardTypeWidth / typeSize.X;
                }

                float costScale = 1;
                if (costSize.X > _cardCostWidth)
                {
                    costScale = _cardCostWidth / costSize.X;
                }

                // render the title text's shadow
                RenderTarget2D titleShadowTarget = new RenderTarget2D(GraphicsDevice, _cardTitleWidth, _cardTitleHeight, false,
                                                                      GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24);
                GraphicsDevice.SetRenderTarget(titleShadowTarget);
                GraphicsDevice.Clear(Color.Transparent);
                _spriteBatch.Begin();
                _spriteBatch.DrawString(_titleFont, titleString,
                                        new Vector2((int)((_cardTitleWidth - titleSize.X * titleScale) / 2), (int)((_cardTitleHeight - titleSize.Y * titleScale) / 2)),
                                        Color.White, 0, Vector2.Zero, titleScale, SpriteEffects.None, 0);
                _spriteBatch.End();

                // do blur
                GaussianBlur gaussianBlur = new GaussianBlur(this);
                gaussianBlur.ComputeKernel(4, 2);
                int            renderTargetWidth  = titleShadowTarget.Width / 2;
                int            renderTargetHeight = titleShadowTarget.Height / 2;
                RenderTarget2D rt1 = new RenderTarget2D(GraphicsDevice,
                                                        renderTargetWidth, renderTargetHeight, false,
                                                        GraphicsDevice.PresentationParameters.BackBufferFormat,
                                                        DepthFormat.None);
                RenderTarget2D rt2 = new RenderTarget2D(GraphicsDevice,
                                                        renderTargetWidth, renderTargetHeight, false,
                                                        GraphicsDevice.PresentationParameters.BackBufferFormat,
                                                        DepthFormat.None);
                gaussianBlur.ComputeOffsets(renderTargetWidth, renderTargetHeight);
                Texture2D titleShadowResult = gaussianBlur.PerformGaussianBlur(titleShadowTarget, rt1, rt2, _spriteBatch);

                // render the type text's shadow
                RenderTarget2D typeShadowTarget = new RenderTarget2D(GraphicsDevice, _cardTypeWidth, _cardTypeHeight, false,
                                                                     GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24);
                GraphicsDevice.SetRenderTarget(typeShadowTarget);
                GraphicsDevice.Clear(Color.Transparent);
                _spriteBatch.Begin();
                _spriteBatch.DrawString(_typeFont, typeString,
                                        new Vector2((int)((_cardTypeWidth - typeSize.X * typeScale) / 2), (int)((_cardTypeHeight - typeSize.Y * typeScale) / 2)),
                                        Color.White, 0, Vector2.Zero, typeScale, SpriteEffects.None, 0);
                _spriteBatch.End();

                // do blur
                renderTargetWidth  = typeShadowTarget.Width / 2;
                renderTargetHeight = typeShadowTarget.Height / 2;
                rt1 = new RenderTarget2D(GraphicsDevice,
                                         renderTargetWidth, renderTargetHeight, false,
                                         GraphicsDevice.PresentationParameters.BackBufferFormat,
                                         DepthFormat.None);
                rt2 = new RenderTarget2D(GraphicsDevice,
                                         renderTargetWidth, renderTargetHeight, false,
                                         GraphicsDevice.PresentationParameters.BackBufferFormat,
                                         DepthFormat.None);
                gaussianBlur.ComputeOffsets(renderTargetWidth, renderTargetHeight);
                Texture2D typeShadowResult = gaussianBlur.PerformGaussianBlur(typeShadowTarget, rt1, rt2, _spriteBatch);

                // render the card
                _renderedCardBuffer = new RenderTarget2D(GraphicsDevice, _cardTexture.Width, _cardTexture.Height, false,
                                                         GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24);
                GraphicsDevice.SetRenderTarget(_renderedCardBuffer);
                GraphicsDevice.Clear(Color.Transparent);

                _spriteBatch.Begin();
                _spriteBatch.Draw(_cardTexture, cardRect, Color.White);
                _spriteBatch.DrawString(_rulesTextFont, someRandomText,
                                        new Vector2(_cardRulesLeftX, (int)(_cardRulesTopY + (_cardRulesHeight - textSize.Y) / 2)),
                                        Color.Black, 0, Vector2.Zero, 1, SpriteEffects.None, 0);

                _spriteBatch.Draw(titleShadowResult,
                                  new Rectangle((int)(_cardTitleLeftX + (_cardTitleWidth - titleShadowResult.Width * 2) / 2), (int)(_cardTitleTopY + (_cardTitleHeight - titleShadowResult.Height * 2) / 2), titleShadowResult.Width * 2, titleShadowResult.Height * 2),
                                  new Rectangle(0, 0, titleShadowResult.Width, titleShadowResult.Height),
                                  Color.White);
                _spriteBatch.Draw(typeShadowResult,
                                  new Rectangle((int)(_cardTypeLeftX + (_cardTypeWidth - typeShadowResult.Width * 2) / 2), (int)(_cardTypeTopY + (_cardTypeHeight - typeShadowResult.Height * 2) / 2), typeShadowResult.Width * 2, typeShadowResult.Height * 2),
                                  new Rectangle(0, 0, typeShadowResult.Width, typeShadowResult.Height),
                                  Color.White);
                _spriteBatch.DrawString(_titleFont, titleString,
                                        new Vector2((int)(_cardTitleLeftX + (_cardTitleWidth - titleSize.X * titleScale) / 2), (int)(_cardTitleTopY + (_cardTitleHeight - titleSize.Y * titleScale) / 2)),
                                        Color.Black, 0, Vector2.Zero, titleScale, SpriteEffects.None, 0);
                _spriteBatch.DrawString(_typeFont, typeString,
                                        new Vector2((int)(_cardTypeLeftX + (_cardTypeWidth - typeSize.X * typeScale) / 2), (int)(_cardTypeTopY + (_cardTypeHeight - typeSize.Y * typeScale) / 2)),
                                        Color.Black, 0, Vector2.Zero, typeScale, SpriteEffects.None, 0);
                _spriteBatch.DrawString(_statFont, costString,
                                        new Vector2((int)(_cardCostLeftX + (_cardCostWidth - costSize.X * costScale) / 2), (int)(_cardCostTopY + (_cardCostHeight - costSize.Y * costScale) / 2)),
                                        Color.Black, 0, Vector2.Zero, costScale, SpriteEffects.None, 0);

                _spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);
            }

            // Draw cards *this should always appear at the end so its on top
            _spriteBatch.Begin();
            float scale = .4f;

            // Note: this is arbitrary rules text for testing...
            Rectangle retval = new Rectangle(
                0 + 10,
                GraphicsDevice.Viewport.Height - (int)(_cardTexture.Height * scale) - 10,
                (int)(_cardTexture.Width * scale),
                (int)(_cardTexture.Height * scale));

            _spriteBatch.Draw(_renderedCardBuffer, retval, Color.White);

            _spriteBatch.End();

            base.Draw(gameTime);
        }
Exemplo n.º 24
0
        protected override void LoadContent()
        {
            base.LoadContent();

            var Content = gameRef.Content;

            IOManager.Init();

            blackOverlay = new DrawableRectangle(GraphicsDevice,
                                                 new Vector2(MainGame.GAME_WIDTH, MainGame.GAME_HEIGHT), Color.White, true).Texture;

            blurOverlay = new GaussianBlur(gameRef);
            blurOverlay.ComputeKernel(7, 2.0f);


            titleImage = Content.Load <Texture2D>("Images\\title");

            title            = new Label();
            title.SpriteFont = Content.Load <SpriteFont>("Fonts\\title");
            title.Text       = "";
            title.Color      = Color.White;
            title.Position   = new Vector2(MainGame.GAME_WIDTH / 2 - title.Width / 2, 90);
            controls.Add(title);

            Texture2D[] images = new Texture2D[8];
            for (int i = 0; i < images.Length; i++)
            {
                images[i] = Content.Load <Texture2D>("Images\\waterfall\\water" + i.ToString());
            }

            anim = new Animation(images);

            #region Menu State
            menuControls = new ControlManager(gameRef, Content.Load <SpriteFont>("Fonts\\default"));

            var start = new LinkLabel(0)
            {
                Name = "lnklblStart", Text = "New Game"
            };
            var load = new LinkLabel(1)
            {
                Name = "lnklblLoad", Text = "Load Game"
            };
            var options = new LinkLabel(2)
            {
                Name = "lnklblOptions", Text = "Options"
            };
            var quit = new LinkLabel(3)
            {
                Name = "lnklblQuit", Text = "Quit Game"
            };

            menuControls.Add(start);
            menuControls.Add(load);
            menuControls.Add(options);
            menuControls.Add(quit);

            Vector2 startPos = new Vector2(MainGame.GAME_WIDTH / 2, MainGame.GAME_HEIGHT / 1.8f);
            foreach (Control c in menuControls)
            {
                if (c is LinkLabel)
                {
                    var l      = (LinkLabel)c;
                    var offset = new Vector2(c.Width / 2, 0);
                    c.Position  = startPos - offset;
                    c.Selected += new EventHandler(LinkLabel_Selected);
                    c.Effect    = ControlEffect.PULSE;
                    c.Color     = Color.Black;
                    ((LinkLabel)c).SelectedColor = Color.DarkBlue;

                    l.OnMouseIn += LinkLabel_OnMouseIn;

                    startPos.Y += c.Height + 10f;
                }
            }

            menuControls.SelectControl(0);
            #endregion

            #region New Game State
            newGameControls = new ControlManager(gameRef, Content.Load <SpriteFont>("Fonts\\default"));

            Label prompt = new Label();
            prompt.Text     = "Enter your name";
            prompt.Name     = "lblNamePrompt";
            prompt.Position = new Vector2(MainGame.GAME_WIDTH / 2 -
                                          prompt.SpriteFont.MeasureString(prompt.Text).X / 2, 200);
            newGameControls.Add(prompt);

            TextBox name = new TextBox(GraphicsDevice);
            name.Name      = "txtName";
            name.Position  = new Vector2(prompt.Position.X + 40, prompt.Position.Y + prompt.Height + 10);
            name.BackColor = Color.Transparent;
            name.ForeColor = Color.White;
            newGameControls.Add(name);

            LinkLabel startGame = new LinkLabel(2)
            {
                Name = "lnklblNewGame", Text = "Start"
            };
            startGame.Position   = new Vector2(prompt.Position.X, name.Position.Y + 44);
            startGame.OnMouseIn += LinkLabel_OnMouseIn;
            startGame.Selected  += (o, e) =>
            {
                Config.currentlyPlaying = newGameControls[1].Text;
                SwitchStateWithFade(new LoadingState(gameRef, StateManager, new GameplayState(gameRef, StateManager)));
            };
            startGame.Effect = ControlEffect.PULSE;

            LinkLabel cancel = new LinkLabel(3)
            {
                Name = "lnklblCancel", Text = "Cancel"
            };
            cancel.Position   = new Vector2(prompt.Position.X + prompt.Width - cancel.Width, startGame.Position.Y);
            cancel.OnMouseIn += LinkLabel_OnMouseIn;
            cancel.Selected  += (o, e) => { currentState = State.Menu; };
            cancel.Effect     = ControlEffect.PULSE;

            newGameControls.Add(startGame);
            newGameControls.Add(cancel);
            #endregion

            #region Load Game State
            loadGameControls = new ControlManager(gameRef, Content.Load <SpriteFont>("Fonts\\default"));

            List <EntityProperties> saves = new List <EntityProperties>();
            saves = IOManager.GetAllPlayerDatas();

            startPos = new Vector2(MainGame.GAME_WIDTH / 2, 0);
            int counter = 0;
            foreach (EntityProperties ep in saves)
            {
                var lnklblLoadSave = new LinkLabel(counter++);
                lnklblLoadSave.AutoSize   = true;
                lnklblLoadSave.Name       = "lnklblLoadSave";
                lnklblLoadSave.Text       = ep.Name + " | " + ep.TimeOfSave;
                lnklblLoadSave.OnMouseIn += LinkLabel_OnMouseIn;
                lnklblLoadSave.Selected  += (o, e) => { SwitchStateWithFade(new LoadingState(gameRef, StateManager, new GameplayState(gameRef, StateManager, ep))); };
                lnklblLoadSave.Effect     = ControlEffect.PULSE;

                var offset = new Vector2(lnklblLoadSave.Width / 2, 0);
                lnklblLoadSave.Position = startPos - offset;
                startPos.Y += lnklblLoadSave.Height + 10;
                loadGameControls.Add(lnklblLoadSave);
            }

            var goBack_Load = new LinkLabel(loadGameControls.Count);
            goBack_Load.Name       = "lnklblGoBackLoad";
            goBack_Load.Text       = "Go Back";
            goBack_Load.Effect     = ControlEffect.PULSE;
            goBack_Load.Position   = new Vector2(MainGame.GAME_WIDTH / 2 - goBack_Load.Width / 2, MainGame.GAME_HEIGHT - goBack_Load.Height - 100);
            goBack_Load.OnMouseIn += LinkLabel_OnMouseIn;
            goBack_Load.Selected  += (o, e) => { currentState = State.Menu; };
            loadGameControls.Add(goBack_Load);

            #endregion

            #region Options Game State

            #endregion

            #region Quit State
            quitControls = new ControlManager(gameRef, Content.Load <SpriteFont>("Fonts\\default"));

            Label areYouSure1 = new Label();
            areYouSure1.Name     = "lblAreYouSure?";
            areYouSure1.Text     = "Are you sure you want to quit?";
            areYouSure1.Position = new Vector2(MainGame.GAME_WIDTH / 2 - areYouSure1.SpriteFont.MeasureString(
                                                   areYouSure1.Text).X / 2, 140);
            quitControls.Add(areYouSure1);

            LinkLabel yes = new LinkLabel(1)
            {
                Name = "lnklblYes", Text = "Yes"
            };
            yes.Position   = new Vector2(areYouSure1.Position.X + 40, areYouSure1.Position.Y + areYouSure1.Height + 50);
            yes.OnMouseIn += LinkLabel_OnMouseIn;
            yes.Selected  += (o, e) => { gameRef.Exit(); };
            yes.Effect     = ControlEffect.PULSE;

            LinkLabel no = new LinkLabel(2)
            {
                Name = "lnklblNo", Text = "No"
            };
            no.Position   = new Vector2(areYouSure1.Position.X + areYouSure1.Width - no.Width - 40, yes.Position.Y);
            no.OnMouseIn += LinkLabel_OnMouseIn;
            no.Selected  += (o, e) => { currentState = State.Menu; };
            no.Effect     = ControlEffect.PULSE;

            quitControls.Add(yes);
            quitControls.Add(no);
            #endregion

            debugFont = Content.Load <SpriteFont>("Fonts\\version");
        }
Exemplo n.º 25
0
        public override void LargeLoadContent(object sender)
        {
            var Content = gameRef.Content;

            background = new DrawableRectangle(gameRef.GraphicsDevice, new Vector2(10, 10), Color.Black, true).Texture;

            levelManager = new LevelManager(gameRef);
            Camera.Initialize(Vector2.Zero, new Rectangle(0, 0, MainGame.GAME_WIDTH, MainGame.GAME_HEIGHT),
                              new Vector2(LevelManager.CurrentLevel.WidthInPixels, LevelManager.CurrentLevel.HeightInPixels));
            Camera.MaxClamp -= new Vector2(Camera.View.Width / 2, Camera.View.Height / 2);

            entityManager = new EntityManager(gameRef);


            if (!loadedGame)
            {
                EntityManager.Player.Name = Config.currentlyPlaying;

                if (LevelManager.CurrentLevel.PlayerSpawnPoint.X > -1 &&
                    LevelManager.CurrentLevel.PlayerSpawnPoint.Y > -1)
                {
                    EntityManager.Player.Position = new Vector2(LevelManager.CurrentLevel.PlayerSpawnPoint.X, LevelManager.CurrentLevel.PlayerSpawnPoint.Y) * Engine.TileWidth;
                }
            }
            else
            {
                Config.SetLastLogin(loadedProps.Name);
                Config.currentlyPlaying = loadedProps.Name;
                EntityManager.Player.LoadFromData(loadedProps);
            }

            new Pathfinder(LevelManager.CurrentLevel);

            #region Pause_Normal
            pauseControls_Normal = new ControlManager(gameRef, gameRef.Content.Load <SpriteFont>("Fonts\\default"));
            {
                Label lblPauseDisplay = new Label()
                {
                    Name  = "lblPauseDisplay",
                    Text  = "P A U S E D",
                    Color = Color.White
                };
                lblPauseDisplay.Position = new Vector2(MainGame.GAME_WIDTH / 2 - lblPauseDisplay.Width / 2,
                                                       MainGame.GAME_HEIGHT / 1.8f - lblPauseDisplay.Height - 10);

                var back = new LinkLabel(1)
                {
                    Name = "lnklblBack", Text = "Resume"
                };
                var save = new LinkLabel(2)
                {
                    Name = "lnklblSave", Text = "Save Game"
                };
                var quit = new LinkLabel(3)
                {
                    Name = "lnklblQuit", Text = "Quit to Menu"
                };

                pauseControls_Normal.Add(lblPauseDisplay);
                pauseControls_Normal.Add(back);
                pauseControls_Normal.Add(save);
                pauseControls_Normal.Add(quit);

                Vector2 startPos = new Vector2(MainGame.GAME_WIDTH / 2, MainGame.GAME_HEIGHT / 1.8f);
                foreach (Control c in pauseControls_Normal)
                {
                    if (c is LinkLabel)
                    {
                        var l      = (LinkLabel)c;
                        var offset = new Vector2(c.Width / 2, 0);
                        c.Position   = startPos - offset;
                        c.Selected  += new EventHandler(LinkLabel_Selected);
                        c.Effect     = ControlEffect.PULSE;
                        c.Color      = Color.Black;
                        l.OnMouseIn += LinkLabel_OnMouseIn;

                        startPos.Y += c.Height + 10f;
                    }
                }
            }
            #endregion

            #region Pause_Save
            pauseControls_Save = new ControlManager(gameRef, gameRef.Content.Load <SpriteFont>("Fonts\\default"));

            Label status = new Label();
            status.AutoSize = true;
            status.Text     = "Save game success!";
            status.Position = new Vector2(MainGame.GAME_WIDTH / 2 - status.Width / 2, MainGame.GAME_HEIGHT / 2 - status.Height);
            pauseControls_Save.Add(status);

            LinkLabel goBack_Save = new LinkLabel(0);
            goBack_Save.AutoSize   = true;
            goBack_Save.Text       = "Go Back";
            goBack_Save.Position   = new Vector2(MainGame.GAME_WIDTH / 2 - goBack_Save.Width / 2, status.Position.Y + status.Height + 10);
            goBack_Save.Selected  += (o, e) => { pauseState = State_Paused.Normal; };
            goBack_Save.OnMouseIn += LinkLabel_OnMouseIn;
            pauseControls_Save.Add(goBack_Save);
            #endregion

            #region Pause_Quit
            pauseControls_Quit = new ControlManager(gameRef, gameRef.Content.Load <SpriteFont>("Fonts\\default"));

            Label areYouSure1 = new Label();
            areYouSure1.Name     = "lblAreYouSure?";
            areYouSure1.Text     = "Are you sure you want to quit?";
            areYouSure1.Position = new Vector2(MainGame.GAME_WIDTH / 2 - areYouSure1.SpriteFont.MeasureString(
                                                   areYouSure1.Text).X / 2, 140);
            pauseControls_Quit.Add(areYouSure1);

            LinkLabel yes = new LinkLabel(1)
            {
                Name = "lnklblYes", Text = "Yes"
            };
            yes.Position   = new Vector2(areYouSure1.Position.X + 40, areYouSure1.Position.Y + areYouSure1.Height + 50);
            yes.OnMouseIn += LinkLabel_OnMouseIn;
            yes.Selected  += (o, e) => { SwitchStateWithFade(new MainMenuState(gameRef, StateManager)); };
            yes.Effect     = ControlEffect.PULSE;

            LinkLabel no = new LinkLabel(2)
            {
                Name = "lnklblNo", Text = "No"
            };
            no.Position   = new Vector2(areYouSure1.Position.X + areYouSure1.Width - no.Width - 40, yes.Position.Y);
            no.OnMouseIn += LinkLabel_OnMouseIn;
            no.Selected  += (o, e) => { pauseState = State_Paused.Normal; };
            no.Effect     = ControlEffect.PULSE;

            pauseControls_Quit.Add(yes);
            pauseControls_Quit.Add(no);
            #endregion

            blurOverlay        = new GaussianBlur(gameRef);
            renderTargetWidth  = MainGame.GAME_WIDTH;
            renderTargetHeight = MainGame.GAME_HEIGHT;
            blurOverlay.ComputeKernel(7, 2.0f);

            mainTarget = new RenderTarget2D(gameRef.GraphicsDevice, MainGame.GAME_WIDTH, MainGame.GAME_HEIGHT);
            target1    = new RenderTarget2D(gameRef.GraphicsDevice, renderTargetWidth, renderTargetHeight, false,
                                            gameRef.GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.None);
            target2 = new RenderTarget2D(gameRef.GraphicsDevice, renderTargetWidth, renderTargetHeight, false,
                                         gameRef.GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.None);

            blurOverlay.ComputeOffsets(renderTargetWidth, renderTargetHeight);

            quests = new QuestManager();

            Quest q = new Quest(0, (QuestGiver)EntityManager.Npcs[0], EntityManager.Player);
            q.CheckSuccess += (delegate()
            {
                return(EntityManager.Player.NoClip == true);
            });
            quests.AddQuest(q);

            ((QuestGiver)EntityManager.Npcs[0]).Quest             = q;
            ((QuestGiver)EntityManager.Npcs[0]).OnQuestCompleted += (delegate(object sender2, EventArgs args)
            {
                var questGiverSender = (QuestGiver)sender2;
                questGiverSender.Dialogues[0] = "Good job!";
            });

            base.LargeLoadContent(sender);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Permite dirigir el programa al filtro que el usuario quiere aplicar.
        /// </summary>
        private void filterTypeImage()
        {
            MessageBox.Show("    Aplicando filtro    ", "Notificación", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            Bitmap    imagePixels = new Bitmap(imageContainer.Image);
            Stopwatch watch       = new Stopwatch();
            bool      local       = simpleModeB.Checked;

            updateTime(0, " ");
            updateTime(1, " ");
            Image newImage;

            if (local)
            {
                Console.WriteLine(filterIndex);
                switch (filterIndex)
                {
                case 0:
                    watch.Start();
                    newImage = traditionalFilter.sepiaFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.sepiaFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 1:
                    watch.Start();
                    newImage = traditionalFilter.grayScaleFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.grayScaleFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 2:
                    try
                    {
                        watch.Start();
                        newImage = traditionalFilter.opacityFilter(imagePixels, Convert.ToDouble(filterPercentage.Text));
                        watch.Stop();
                        this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                        watch.Start();
                        optimizedFilter.opacityFilter(imagePixels, Convert.ToDouble(filterPercentage.Text));
                        watch.Stop();
                        this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                        this.imageContainer.Image = newImage;
                    }
                    catch
                    {
                        MessageBox.Show("Verifica el dato de entrada", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    break;

                case 3:
                    watch.Start();
                    newImage = traditionalFilter.invertColorsFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.invertColorsFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 4:
                    watch.Start();
                    newImage = traditionalFilter.GaussinBlurFilter(imagePixels, new Rectangle(0, 0, imagePixels.Width, imagePixels.Height), 4);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    GaussianBlur gaussian = new GaussianBlur(imagePixels);
                    gaussian.Process(3);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 5:
                    try
                    {
                        watch.Start();
                        newImage = traditionalFilter.brightFilter(imagePixels, Convert.ToDouble(filterPercentage.Text) / 100);
                        watch.Stop();
                        this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                        watch.Start();
                        optimizedFilter.brightFilter(imagePixels, Convert.ToDouble(filterPercentage.Text) / 100);
                        watch.Stop();
                        this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                        this.imageContainer.Image = newImage;
                    }
                    catch
                    {
                        MessageBox.Show("Verifica el dato de entrada", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    break;

                case 6:
                    watch.Start();
                    newImage = traditionalFilter.colorsBalance(imagePixels);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.colorsBalance(imagePixels);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 7:
                    watch.Start();
                    newImage = traditionalFilter.colorSubstitution(imagePixels, colorSubstitution);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    //esperar un segundo
                    Thread.Sleep(1000);
                    optimizedFilter.colorSubstitution(imagePixels, colorSubstitution);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 8:
                    try
                    {
                        watch.Start();
                        newImage = traditionalFilter.CrudeHighPass(imagePixels, Convert.ToInt32(filterPercentage.Text) / 100);
                        watch.Stop();
                        this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                        watch.Start();
                        optimizedFilter.CrudeHighPass(imagePixels, Convert.ToInt32(filterPercentage.Text) / 100);
                        watch.Stop();
                        this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                        this.imageContainer.Image = newImage;
                    }
                    catch
                    {
                        MessageBox.Show("Verifica el dato de entrada", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    break;

                case 9:
                    watch.Start();
                    newImage = traditionalFilter.EdgeFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.EdgeFilter(imagePixels);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 10:
                    watch.Start();
                    newImage = traditionalFilter.solariseFilter(imagePixels, 25, 40, 52);
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    watch.Start();
                    optimizedFilter.solariseFilter(imagePixels, 25, 40, 52);
                    watch.Stop();
                    this.updateTime(2, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                default:
                    break;
                }
            }
            else
            {
                switch (filterIndex)
                {
                case 0:
                    watch.Start();
                    ConnectionManager.FilterName = "Sepia";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 1:
                    watch.Start();
                    ConnectionManager.FilterName = "GrayScale";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 2:
                    double opacityValue = 0;
                    try
                    {
                        opacityValue = double.Parse(filterPercentage.Text);
                        if (opacityValue <= 0 || opacityValue > 255)
                        {
                            MessageBox.Show("Error: el numero debe ser un entero de 0 a 255", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error: el numero debe ser un entero de 0 a 255", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    watch.Start();
                    ConnectionManager.ParamValue = opacityValue;
                    ConnectionManager.FilterName = "Opacity";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 3:
                    watch.Start();
                    ConnectionManager.FilterName = "InvertColors";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 4:
                    watch.Start();
                    ConnectionManager.FilterName = "GaussianBlur";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 5:
                    watch.Start();

                    double BrightValue = 0;
                    try
                    {
                        BrightValue = double.Parse(filterPercentage.Text);
                        if (BrightValue < 0 || BrightValue > 255)
                        {
                            MessageBox.Show("Error: Debe ser un numero entero", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error: el numero debe ser un entero", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    ConnectionManager.ParamValue = BrightValue;
                    ConnectionManager.FilterName = "Bright";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 6:
                    watch.Start();
                    ConnectionManager.FilterName = "ColorsBalance";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    this.updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 7:
                    Color sourceColor    = colorSubstitution.getSourceColor();
                    Color newColor       = colorSubstitution.getNewColor();
                    int   colorThreshold = colorSubstitution.getThreshold();

                    watch.Start();
                    ConnectionManager.FilterName = "ColorSubstitution";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.Colors.Clear();
                    ConnectionManager.Colors.Add(sourceColor);
                    ConnectionManager.Colors.Add(newColor);
                    ConnectionManager.ParamValue = colorThreshold;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 8:
                    watch.Start();
                    ConnectionManager.FilterName = "SolariseFilter";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 9:
                    watch.Start();
                    ConnectionManager.FilterName = "EdgeDetection";
                    ConnectionManager.Bitmap     = imagePixels;
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                case 10:
                    ConnectionManager.FilterName = "CrudeHighPass";
                    double darknessValue = 0;
                    Console.WriteLine(darknessValue);
                    try
                    {
                        darknessValue = double.Parse(filterPercentage.Text);
                        if (darknessValue <= 0 || darknessValue > 255)
                        {
                            MessageBox.Show("Error: el numero debe ser un entero de 0 a 255", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error: el numero debe ser un entero de 0 a 255", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    ConnectionManager.ParamValue = darknessValue;
                    ConnectionManager.Bitmap     = imagePixels;
                    watch.Start();
                    ConnectionManager.AddConnections(servers);
                    newImage = ConnectionManager.ApplyFilter();
                    watch.Stop();
                    updateTime(1, watch.Elapsed.TotalSeconds.ToString() + " s");
                    this.imageContainer.Image = newImage;
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 27
0
        private async Task CalibThread(FrameReadyEventArgs e)
        {
            Debug.WriteLine("Calibrating " + _calibrationStep + " " + _drawing);
            e.Frame.Bitmap.Save(@"C:\temp\daforge\src\img" + (_calibrationStep < 10?"0":"") + _calibrationStep + "-" + (_drawing?"1":"0") + "-" + _errors + ".jpg", ImageFormat.Jpeg);
            if (_errors > 100)
            {
                //calibration not possible
                return;
            }
            if (_calibrationStep == CalibrationFrames && !_drawing)
            {
                _cc.FrameReady -= BaseCalibration; // TODO
                //Grid.Calculate();
                _vs.Close();
                CalibrationCompleted(this, new EventArgs());
            }
            else
            {
                if (_calibrationStep > 2)
                {
                    if (_drawing)
                    {
                        // draw diffimage
                        _drawing = false;
                        _vs.Clear();
                        FillRects();
                        diffFilter.OverlayImage = e.Frame.Bitmap;
                    }
                    else
                    {
                        // analyse diffimage
                        _calibrationStep++;
                        _drawing = true;
                        _vs.Clear();
                        FillRects();
                        _calibrationStep--;
                        var gbm = diffFilter.Apply(e.Frame.Bitmap);
                        gbm.Save(@"C:\temp\daforge\diff\img" + _calibrationStep + ".jpg", ImageFormat.Jpeg);
#if DEBUG
                        actImg = (Bitmap)gbm.Clone();
#endif
                        var d     = UnmanagedImage.FromManagedImage(gbm);
                        var stats = new ImageStatistics(d);
                        var gcf   = new ColorFiltering(new IntRange(0, 255),
                                                       new IntRange((int)(stats.GreenWithoutBlack.Mean + stats.GreenWithoutBlack.StdDev + 5), 255),
                                                       new IntRange(0, 255));
                        var bcf = new ColorFiltering(new IntRange(0, 255),
                                                     new IntRange(0, 255),
                                                     new IntRange((int)(stats.BlueWithoutBlack.Mean + stats.BlueWithoutBlack.StdDev), 255));
                        //Debug.WriteLine("Green: " + stats.GreenWithoutBlack.Median + " Blue: " + stats.BlueWithoutBlack.Median);
                        //Debug.WriteLine("Green: " + stats.GreenWithoutBlack.Mean + " Blue: " + stats.BlueWithoutBlack.Mean);
                        var bf = new Difference(gcf.Apply(d));
                        bcf.ApplyInPlace(d);
                        bf.ApplyInPlace(d);
                        d.ToManagedImage().Save(@"C:\temp\daforge\diff\img" + _calibrationStep + ".jpg", ImageFormat.Jpeg);
                        stats = new ImageStatistics(d);
                        gcf   = new ColorFiltering(new IntRange(0, 255),
                                                   new IntRange((int)stats.GreenWithoutBlack.Mean, 255),
                                                   new IntRange(0, 255));
                        bcf = new ColorFiltering(new IntRange(0, 255),
                                                 new IntRange(0, 255),
                                                 new IntRange((int)stats.BlueWithoutBlack.Mean, 255));
                        // split channels
                        var bbm = bcf.Apply(d);
                        bbm.ToManagedImage().Save(@"C:\temp\daforge\bimg\img" + _calibrationStep + ".jpg", ImageFormat.Bmp);
                        gcf.ApplyInPlace(d);
                        d.ToManagedImage().Save(@"C:\temp\daforge\gimg\img" + _calibrationStep + ".jpg", ImageFormat.Bmp);
                        var gblobCounter = new BlobCounter
                        {
                            ObjectsOrder         = ObjectsOrder.YX,
                            MaxHeight            = 60,
                            MinHeight            = 15,
                            MaxWidth             = 60,
                            MinWidth             = 15,
                            FilterBlobs          = true,
                            CoupledSizeFiltering = false
                        };
                        gblobCounter.ProcessImage(d);
                        var bblobCounter = new BlobCounter
                        {
                            ObjectsOrder         = ObjectsOrder.YX,
                            MaxHeight            = 60,
                            MinHeight            = 15,
                            MaxWidth             = 60,
                            MinWidth             = 15,
                            FilterBlobs          = true,
                            CoupledSizeFiltering = false
                        };
                        bblobCounter.ProcessImage(bbm);
                        ProcessBlobs(gblobCounter, 0);
                        ProcessBlobs(bblobCounter, 1);
#if DEBUG
                        actImg.Save(@"C:\temp\daforge\squares\img" + _calibrationStep + ".jpg", ImageFormat.Jpeg);
#endif
                        _calibrationStep++;
                    }
                }
                else
                {
                    switch (_calibrationStep)
                    {
                    case 2:
                        var bm = UnmanagedImage.FromManagedImage(e.Frame.Bitmap);
                        //diffFilter.OverlayImage.Save(@"C:\temp\daforge\diff\src" + _errors + ".jpg", ImageFormat.Jpeg);
                        bm = diffFilter.Apply(bm);
                        var gf = new GaussianBlur(9.0, 3);
                        gf.ApplyInPlace(bm);
                        var cf = new ColorFiltering(new IntRange(10, 255), new IntRange(20, 255),
                                                    new IntRange(20, 255));
                        cf.ApplyInPlace(bm);
                        var blobCounter = new BlobCounter {
                            ObjectsOrder = ObjectsOrder.Size, BackgroundThreshold = Color.FromArgb(255, 15, 20, 20), FilterBlobs = true
                        };
                        blobCounter.ProcessImage(bm);
                        bm.ToManagedImage().Save(@"C:\temp\daforge\diff\img" + _calibrationStep + "-" + _errors + ".jpg", ImageFormat.Jpeg);
                        var blobs = blobCounter.GetObjectsInformation();
                        if (blobs.Any())
                        {
                            int             i = 0;
                            List <IntPoint> corners;
                            do
                            {
                                corners =
                                    PointsCloud.FindQuadrilateralCorners(blobCounter.GetBlobsEdgePoints(blobs[i++]));
                            } while (corners.Count != 4);
                            RecursiveAForgeCalibrator.GridBlobs.InPlaceSort(corners);
                            Grid.TopLeft     = new Point(corners[0].X, corners[0].Y);
                            Grid.TopRight    = new Point(corners[1].X, corners[1].Y);
                            Grid.BottomLeft  = new Point(corners[2].X, corners[2].Y);
                            Grid.BottomRight = new Point(corners[3].X, corners[3].Y);
                            if (Grid.TopLeft.X > 10 && Grid.TopRight.X < _vs.Width - 5 && Grid.BottomLeft.X > 5 &&
                                Grid.BottomRight.X < _vs.Width - 5 && Grid.TopLeft.Y > 10 && Grid.TopRight.Y > 5 &&
                                Grid.BottomLeft.Y < _vs.Height - 5 && Grid.BottomRight.Y < _vs.Height - 5 &&
                                Grid.TopLeft.X < Grid.BottomRight.X && blobs[i - 1].Area > 60000 &&
                                Grid.BottomLeft.X < Grid.TopRight.X && Grid.BottomLeft.X < Grid.BottomRight.X &&
                                Grid.TopLeft.Y < Grid.BottomLeft.Y && Grid.TopLeft.Y < Grid.BottomRight.Y &&
                                Grid.TopRight.Y < Grid.BottomLeft.Y && Grid.TopRight.Y < Grid.BottomRight.Y)
                            {
                                _calibrationStep++;
                                _drawing = true;
                                _vs.Clear();
                                FillRects();
                                Grid.AddPoint(new Point(), new Point(corners[0].X, corners[0].Y));
                                Grid.AddPoint(new Point(0, _vs.Height), new Point(corners[1].X, corners[1].Y));
                                Grid.AddPoint(new Point(_vs.Width, 0), new Point(corners[2].X, corners[2].Y));
                                Grid.AddPoint(new Point(_vs.Width, _vs.Height),
                                              new Point(corners[3].X, corners[3].Y));
                            }
                            else
                            {
                                _calibrationStep = 0;
                                _errors++;
                            }
                        }
                        else
                        {
                            _calibrationStep = 0;
                            _errors++;
                            _vs.Draw();
                        }
                        break;

                    case 1:
                        diffFilter.OverlayImage = e.Frame.Bitmap;
                        //diffFilter.OverlayImage.Save(@"C:\temp\daforge\diff\srcf" + _errors + ".jpg", ImageFormat.Jpeg);
                        //_vs.AddRect(0, 0, (int) _vs.Width, (int) _vs.Height, Color.FromArgb(255, 255, 255, 255));
                        _vs.Clear();
                        for (int y = 0; y < Columncount; y++)
                        {
                            for (int x = 0; x < Rowcount; x++)
                            {
                                if (!(y % 2 == 0 && x % 2 == 0 || y % 2 == 1 && x % 2 == 1))
                                {
                                    _vs.AddRect((int)(x * _sqrwidth), (int)(y * _sqrheight),
                                                (int)_sqrwidth, (int)_sqrheight,
                                                Color.FromArgb(255, 255, 255, 255));
                                }
                            }
                        }
                        _vs.Draw();
                        _calibrationStep++;
                        break;

                    case 0:
                        Grid            = new Grid(e.Frame.Bitmap.Width, e.Frame.Bitmap.Height);
                        Grid.ScreenSize = new Rectangle(0, 0, _vs.Width, _vs.Height);
                        var thread = new Thread(() =>
                        {
                            _vs.Show();
                            _vs.AddRect(0, 0, _vs.Width, _vs.Height, Color.FromArgb(255, 0, 0, 0));
                        });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();
                        for (int y = 0; y < Columncount; y++)
                        {
                            for (int x = 0; x < Rowcount; x++)
                            {
                                if (y % 2 == 0 && x % 2 == 0 || y % 2 == 1 && x % 2 == 1)
                                {
                                    _vs.AddRect((int)(x * _sqrwidth), (int)(y * _sqrheight),
                                                (int)_sqrwidth, (int)_sqrheight,
                                                Color.FromArgb(255, 255, 255, 255));
                                }
                            }
                        }
                        _vs.Draw();
                        _calibrationStep++;
                        break;
                    }
                }
            }
            Debug.WriteLine("Releasing");
            await Task.Delay(500);

            _sem.Release();
        }
Exemplo n.º 28
0
        public new void BeforeRender(Scene scene)
        {
            string path     = Path.Combine("Maps", SaveData.Instance?.LastArea.GetSID() ?? "").Replace('\\', '/');
            string SIDToUse = SaveData.Instance?.LastArea.GetSID() ?? "";
            bool   fadingIn = true;

            // Check if we're changing mountain models or textures
            // If so, we want to fade out and then back in
            if (!(SaveData.Instance?.LastArea.GetSID() ?? "").Equals(PreviousSID))
            {
                string oldModelDir = "", oldTextureDir = "", newModelDir = "", newTextureDir = "";
                if (SaveData.Instance != null && Everest.Content.TryGet(path, out ModAsset asset1))
                {
                    MapMeta meta;
                    if (asset1 != null && (meta = asset1.GetMeta <MapMeta>()) != null && meta.Mountain != null)
                    {
                        newModelDir   = meta.Mountain.MountainModelDirectory ?? "";
                        newTextureDir = meta.Mountain.MountainTextureDirectory ?? "";
                    }
                }
                string oldPath = Path.Combine("Maps", PreviousSID ?? "").Replace('\\', '/');
                if (SaveData.Instance != null && Everest.Content.TryGet(oldPath, out asset1))
                {
                    MapMeta meta;
                    if (asset1 != null && (meta = asset1.GetMeta <MapMeta>()) != null && meta.Mountain != null)
                    {
                        oldModelDir   = meta.Mountain.MountainModelDirectory ?? "";
                        oldTextureDir = meta.Mountain.MountainTextureDirectory ?? "";
                    }
                }

                if (!oldModelDir.Equals(newModelDir) || !oldTextureDir.Equals(newTextureDir))
                {
                    if (fade != 1f)
                    {
                        SIDToUse = PreviousSID;
                        path     = oldPath;
                        fade     = Calc.Approach(fade, 1f, Engine.DeltaTime * 4f);
                        fadingIn = false;
                    }
                    else
                    {
                        // How long we want it to stay opaque before fading back in
                        fadeHoldCountdown = .3f;
                    }
                }
            }

            if (fadingIn && fade != 0f)
            {
                if (fadeHoldCountdown <= 0)
                {
                    fade = Calc.Approach(fade, 0f, Engine.DeltaTime * 4f);
                }
                else
                {
                    fadeHoldCountdown -= Engine.DeltaTime;
                }
            }

            if (SaveData.Instance != null && Everest.Content.TryGet(path, out ModAsset asset))
            {
                MapMeta meta;
                if (asset != null && (meta = asset.GetMeta <MapMeta>()) != null && meta.Mountain != null && !(string.IsNullOrEmpty(meta.Mountain.MountainModelDirectory) && string.IsNullOrEmpty(meta.Mountain.MountainTextureDirectory)))
                {
                    MountainResources resources = MTNExt.MountainMappings[path];

                    ResetRenderTargets();
                    Quaternion rotation = Camera.Rotation;
                    if (ignoreCameraRotation)
                    {
                        rotation = lastCameraRotation;
                    }
                    Matrix matrix  = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, (float)Engine.Width / (float)Engine.Height, 0.25f, 50f);
                    Matrix matrix2 = Matrix.CreateTranslation(-Camera.Position) * Matrix.CreateFromQuaternion(rotation);
                    Matrix matrix3 = matrix2 * matrix;
                    Forward = Vector3.Transform(Vector3.Forward, Camera.Rotation.Conjugated());
                    Engine.Graphics.GraphicsDevice.SetRenderTarget(buffer);

                    Matrix matrix4 = Matrix.CreateTranslation(0f, 5f - Camera.Position.Y * 1.1f, 0f) * Matrix.CreateFromQuaternion(rotation) * matrix;

                    if (currState == nextState)
                    {
                        (resources.MountainStates?[currState] ?? mountainStates[currState]).Skybox.Draw(matrix4, Color.White);
                    }
                    else
                    {
                        (resources.MountainStates?[currState] ?? mountainStates[currState]).Skybox.Draw(matrix4, Color.White);
                        (resources.MountainStates?[currState] ?? mountainStates[currState]).Skybox.Draw(matrix4, Color.White * easeState);
                    }
                    if (currState != nextState)
                    {
                        GFX.FxMountain.Parameters["ease"].SetValue(easeState);
                        GFX.FxMountain.CurrentTechnique = GFX.FxMountain.Techniques["Easing"];
                    }
                    else
                    {
                        GFX.FxMountain.CurrentTechnique = GFX.FxMountain.Techniques["Single"];
                    }
                    Engine.Graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
                    Engine.Graphics.GraphicsDevice.BlendState        = BlendState.AlphaBlend;
                    Engine.Graphics.GraphicsDevice.RasterizerState   = MountainRasterizer;
                    GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                    GFX.FxMountain.Parameters["fog"].SetValue(customFog.TopColor.ToVector3());
                    Engine.Graphics.GraphicsDevice.Textures[0]      = (resources.MountainStates?[currState] ?? mountainStates[currState]).TerrainTexture.Texture;
                    Engine.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
                    if (currState != nextState)
                    {
                        Engine.Graphics.GraphicsDevice.Textures[1]      = (resources.MountainStates?[nextState] ?? mountainStates[nextState]).TerrainTexture.Texture;
                        Engine.Graphics.GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
                    }
                    (resources.MountainTerrain ?? MTN.MountainTerrain).Draw(GFX.FxMountain);
                    GFX.FxMountain.Parameters["WorldViewProj"].SetValue(Matrix.CreateTranslation(CoreWallPosition) * matrix3);
                    (resources.MountainCoreWall ?? MTN.MountainCoreWall).Draw(GFX.FxMountain);
                    GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                    Engine.Graphics.GraphicsDevice.Textures[0]      = (resources.MountainStates?[currState] ?? mountainStates[currState]).BuildingsTexture.Texture;
                    Engine.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
                    if (currState != nextState)
                    {
                        Engine.Graphics.GraphicsDevice.Textures[1]      = (resources.MountainStates?[nextState] ?? mountainStates[nextState]).BuildingsTexture.Texture;
                        Engine.Graphics.GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
                    }
                    (resources.MountainBuildings ?? MTN.MountainBuildings).Draw(GFX.FxMountain);
                    customFog.Draw(matrix3);

                    DrawBillboards(matrix3, scene.Tracker.GetComponents <Billboard>());
                    customFog2.Draw(matrix3, CullCRasterizer);

                    if (DrawDebugPoints && DebugPoints.Count > 0)
                    {
                        GFX.FxDebug.World              = Matrix.Identity;
                        GFX.FxDebug.View               = matrix2;
                        GFX.FxDebug.Projection         = matrix;
                        GFX.FxDebug.TextureEnabled     = false;
                        GFX.FxDebug.VertexColorEnabled = true;
                        VertexPositionColor[] array = DebugPoints.ToArray();
                        foreach (EffectPass pass in GFX.FxDebug.CurrentTechnique.Passes)
                        {
                            pass.Apply();
                            Engine.Graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, array, 0, array.Length / 3);
                        }
                    }
                    GaussianBlur.Blur((RenderTarget2D)buffer, blurA, blurB, 0.75f, clear: true, samples: GaussianBlur.Samples.Five);

                    Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
                    Draw.Rect(-10f, -10f, 1940f, 1100f, Color.Black * fade);
                    Draw.SpriteBatch.End();

                    // Initialize new custom fog when we switch between maps
                    if (!(SIDToUse).Equals(PreviousSID) && resources.MountainFogTexture != null)
                    {
                        customFog  = new Ring(6f, -1f, 20f, 0f, 24, Color.White, resources.MountainFogTexture ?? MTN.MountainFogTexture);
                        customFog2 = new Ring(6f, -4f, 10f, 0f, 24, Color.White, resources.MountainFogTexture ?? MTN.MountainFogTexture);
                    }
                    PreviousSID = SIDToUse;
                    return;
                }
            }

            orig_BeforeRender(scene);

            Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
            Draw.Rect(-10f, -10f, 1940f, 1100f, Color.Black * fade);
            Draw.SpriteBatch.End();

            PreviousSID = SIDToUse;
        }
Exemplo n.º 29
0
        /// <summary>
        /// Blur image with Gauss
        /// </summary>
        /// <param name="image"></param>
        /// <param name="sigma">Gaussia sigma</param>
        /// <param name="kernelSize">Gaussia kermel</param>
        /// <returns></returns>
        public static Bitmap Gauss(this Image image, double sigma, int kernelSize)
        {
            GaussianBlur blur = new GaussianBlur(sigma, kernelSize);

            return(blur.Apply(new Bitmap(image)));
        }
Exemplo n.º 30
0
    public void Test32()
    {
        Texture2D tex32 = sp32.texture;

        byte[] data = tex32.GetRawTextureData();
        print(data.Length);
        print("width: " + tex32.width);
        print("height: " + tex32.height);

        byte[] result_32   = new byte[data.Length];
        byte[] result_32_4 = new byte[data.Length];
        byte[] result_32h  = new byte[data.Length];
        byte[] result_32v  = new byte[data.Length];

        byte[] result_32_repeat = new byte[data.Length];
        byte[] result_32_src    = null;
        byte[] result_32_dst    = null;
        byte[] result_32_tmp    = null;

        TimeSpan ts;
        DateTime dt = DateTime.Now;

        GaussianBlur.Blur32(data, tex32.width, tex32.height, 2, 4, result_32_4);
        ts = DateTime.Now - dt;
        print("blur32_4: " + ts);
        dt = DateTime.Now;
        GaussianBlur.Blur32(data, tex32.width, tex32.height, 2.0f, 3, result_32);
        ts = DateTime.Now - dt;
        print("blur32: " + ts);
        dt = DateTime.Now;
        //GaussianBlur.Blur32 (data, tex32.width, tex32.height, result_32);
        for (int i = 0; i < GaussianBlur.cDefaultRadius + GaussianBlur.cDefaultRadius + 1; i++)
        {
            GaussianBlur.Blur32Horizontal(data, tex32.width, tex32.height, i, result_32h);
        }
        ts = DateTime.Now - dt;
        print("blur32h: " + ts);
        dt = DateTime.Now;
        for (int i = 0; i < GaussianBlur.cDefaultRadius + GaussianBlur.cDefaultRadius + 1; i++)
        {
            GaussianBlur.Blur32Vertical(data, tex32.width, tex32.height, i, result_32v);
        }
        ts = DateTime.Now - dt;
        print("blur32v: " + ts);
        dt            = DateTime.Now;
        result_32_src = data;
        result_32_dst = result_32_repeat;
        float sd = 5.5f;
        int   r  = 3;

        float[] matrix = GaussianMatrixGen.GetGaussianMatrixIn2d(sd, r);
        for (int i = 0; i < r + r + 1; i++)
        {
            GaussianBlur.Blur32Horizontal(result_32_src, tex32.width, tex32.height, matrix, sd, r, i, result_32_dst);
        }
        result_32_src = result_32_repeat;
        result_32_dst = data;
        for (int i = 0; i < r + r + 1; i++)
        {
            GaussianBlur.Blur32Vertical(result_32_src, tex32.width, tex32.height, matrix, sd, r, i, result_32_dst);
        }
        result_32_src = data;
        result_32_dst = result_32_repeat;
        GaussianBlur.Blur32(result_32_src, tex32.width, tex32.height, 100.5f, 3, result_32_dst);
        ts = DateTime.Now - dt;
        print("blur32-hv: " + ts);
        dt = DateTime.Now;
        sd = 0.84089642f;
        r  = 3;
        ts = DateTime.Now - dt;
        print("blur32-repeat: " + ts);

        Texture2D t32 = new Texture2D(tex32.width, tex32.height, TextureFormat.RGBA32, false, true);

        t32.LoadRawTextureData(result_32);
        File.WriteAllBytes(Path.Combine(Application.dataPath, "test_gaussianblur32.png"), t32.EncodeToPNG());

        Texture2D t32_4 = new Texture2D(tex32.width, tex32.height, TextureFormat.RGBA32, false, true);

        t32_4.LoadRawTextureData(result_32_4);
        File.WriteAllBytes(Path.Combine(Application.dataPath, "test_gaussianblur32_4.png"), t32_4.EncodeToPNG());

        Texture2D t32h = new Texture2D(tex32.width, tex32.height, TextureFormat.RGBA32, false, true);

        t32h.LoadRawTextureData(result_32h);
        File.WriteAllBytes(Path.Combine(Application.dataPath, "test_gaussianblur32h.png"), t32h.EncodeToPNG());

        Texture2D t32v = new Texture2D(tex32.width, tex32.height, TextureFormat.RGBA32, false, true);

        t32v.LoadRawTextureData(result_32v);
        File.WriteAllBytes(Path.Combine(Application.dataPath, "test_gaussianblur32v.png"), t32v.EncodeToPNG());

        Texture2D t32repeat = new Texture2D(tex32.width, tex32.height, TextureFormat.RGBA32, false, true);

        t32repeat.LoadRawTextureData(result_32_dst);
        File.WriteAllBytes(Path.Combine(Application.dataPath, "test_gaussianblur32hv.png"), t32repeat.EncodeToPNG());
    }
        public List <IntPoint> ProcessImage(UnmanagedImage image)
        {
            // check image format
            if (
                (image.PixelFormat != PixelFormat.Format8bppIndexed) &&
                (image.PixelFormat != PixelFormat.Format24bppRgb) &&
                (image.PixelFormat != PixelFormat.Format32bppRgb) &&
                (image.PixelFormat != PixelFormat.Format32bppArgb)
                )
            {
                throw new UnsupportedImageFormatException("Unsupported pixel format of the source image.");
            }

            // make sure we have grayscale image
            UnmanagedImage grayImage = null;

            grayImage = image.PixelFormat == PixelFormat.Format8bppIndexed ? image : Grayscale.CommonAlgorithms.BT709.Apply(image);


            // get source image size
            int width  = grayImage.Width;
            int height = grayImage.Height;
            int stride = grayImage.Stride;
            int offset = stride - width;



            // 1. Calculate partial differences
            UnmanagedImage diffx  = UnmanagedImage.Create(width, height, PixelFormat.Format8bppIndexed);
            UnmanagedImage diffy  = UnmanagedImage.Create(width, height, PixelFormat.Format8bppIndexed);
            UnmanagedImage diffxy = UnmanagedImage.Create(width, height, PixelFormat.Format8bppIndexed);

            unsafe
            {
                // Compute dx and dy
                byte *src = (byte *)grayImage.ImageData.ToPointer();
                byte *dx  = (byte *)diffx.ImageData.ToPointer();
                byte *dy  = (byte *)diffy.ImageData.ToPointer();

                // for each line
                for (int y = 0; y < height; y++)
                {
                    // for each pixel
                    for (int x = 0; x < width; x++, src++, dx++, dy++)
                    {
                        // TODO: Place those verifications
                        // outside the innermost loop
                        if (x == 0 || x == width - 1 ||
                            y == 0 || y == height - 1)
                        {
                            *dx = *dy = 0; continue;
                        }

                        int h = -(src[-stride - 1] + src[-1] + src[stride - 1]) +
                                (src[-stride + 1] + src[+1] + src[stride + 1]);
                        *dx = (byte)(h > 255 ? 255 : h < 0 ? 0 : h);

                        int v = -(src[-stride - 1] + src[-stride] + src[-stride + 1]) +
                                (src[+stride - 1] + src[+stride] + src[+stride + 1]);
                        *dy = (byte)(v > 255 ? 255 : v < 0 ? 0 : v);
                    }
                    src += offset;
                    dx  += offset;
                    dy  += offset;
                }


                // Compute dxy
                dx = (byte *)diffx.ImageData.ToPointer();
                var dxy = (byte *)diffxy.ImageData.ToPointer();

                // for each line
                for (int y = 0; y < height; y++)
                {
                    // for each pixel
                    for (int x = 0; x < width; x++, dx++, dxy++)
                    {
                        if (x == 0 || x == width - 1 ||
                            y == 0 || y == height - 1)
                        {
                            *dxy = 0; continue;
                        }

                        int v = -(dx[-stride - 1] + dx[-stride] + dx[-stride + 1]) +
                                (dx[+stride - 1] + dx[+stride] + dx[+stride + 1]);
                        *dxy = (byte)(v > 255 ? 255 : v < 0 ? 0 : v);
                    }
                    dx  += offset;
                    dxy += offset;
                }
            }


            // 2. Smooth the diff images
            if (_sigma > 0.0)
            {
                GaussianBlur blur = new GaussianBlur(_sigma);
                blur.ApplyInPlace(diffx);
                blur.ApplyInPlace(diffy);
                blur.ApplyInPlace(diffxy);
            }


            // 3. Compute Harris Corner Response
            float[,] H = new float[height, width];

            unsafe
            {
                byte *ptrA = (byte *)diffx.ImageData.ToPointer();
                byte *ptrB = (byte *)diffy.ImageData.ToPointer();
                byte *ptrC = (byte *)diffxy.ImageData.ToPointer();
                float M, A, B, C;

                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        A = *(ptrA++);
                        B = *(ptrB++);
                        C = *(ptrC++);

                        // Harris corner measure
                        M = (A * B - C * C) - (_k * ((A + B) * (A + B)));

                        if (M > _threshold)
                        {
                            H[y, x] = M;
                        }
                        else
                        {
                            H[y, x] = 0;
                        }
                    }

                    ptrA += offset;
                    ptrB += offset;
                    ptrC += offset;
                }
            }


            // Free resources
            diffx.Dispose();
            diffy.Dispose();
            diffxy.Dispose();

            if (image.PixelFormat != PixelFormat.Format8bppIndexed)
            {
                grayImage.Dispose();
            }


            // 4. Suppress non-maximum points
            List <IntPoint> cornersList = new List <IntPoint>();

            // for each row
            for (int y = _r, maxY = height - _r; y < maxY; y++)
            {
                // for each pixel
                for (int x = _r, maxX = width - _r; x < maxX; x++)
                {
                    float currentValue = H[y, x];

                    // for each windows' row
                    for (int i = -_r; (currentValue != 0) && (i <= _r); i++)
                    {
                        // for each windows' pixel
                        for (int j = -_r; j <= _r; j++)
                        {
                            if (H[y + i, x + j] > currentValue)
                            {
                                currentValue = 0;
                                break;
                            }
                        }
                    }

                    // check if this point is really interesting
                    if (currentValue != 0)
                    {
                        cornersList.Add(new IntPoint(x, y));
                    }
                }
            }


            return(cornersList);
        }
Exemplo n.º 32
0
        /// <summary>
        ///     Method written for playlists
        /// </summary>
        /// <param name="backgroundRect"></param>
        /// <param name="musicLink"></param>
        /// <param name="songTitle"></param>
        /// <param name="songLabel"></param>
        /// <param name="youtubePlayer"></param>
        /// <param name="backgroundImageUrl"></param>
        /// <returns></returns>
        public static async Task <bool> PlaySpecifiedSong(Rectangle backgroundRect,
                                                          string musicLink, string songTitle, TextBlock songLabel, ChromiumWebBrowser youtubePlayer,
                                                          string backgroundImageUrl, Button playButton)
        {
            songLabel.Text = "Loading...";
            int maxTries = 4;
            int count    = 0;

            while (true)
            {
                try
                {
                    var songName = await GetMusicVideo(musicLink, youtubePlayer);

                    MusicPanel.IsPlaying = true;
                    songLabel.Text       = "Now Playing: " + songTitle;
                    var pauseUri   = new Uri("Icons/Stop.png", UriKind.Relative);
                    var streamInfo = Application.GetResourceStream(pauseUri);
                    var temp       = BitmapFrame.Create(streamInfo.Stream);
                    playButton.Background = new ImageBrush(temp);
                    //Set the background
                    var fileName = Music.GetSongThumb(
                        backgroundImageUrl,
                        RemoveIllegalPathCharacters(songName));
                    var    image        = Image.FromFile(fileName);
                    var    blur         = new GaussianBlur(image as Bitmap);
                    Bitmap blurredThumb = null;
                    try
                    {
                        blurredThumb = blur.Process(15);
                    }
                    catch
                    {
                        blurredThumb = blur.Process(15);
                    }
                    image.Dispose();
                    var hBitmap = blurredThumb.GetHbitmap();
                    var backgroundImageBrush = new ImageBrush();
                    backgroundImageBrush.ImageSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap,
                                                                                             IntPtr.Zero,
                                                                                             Int32Rect.Empty,
                                                                                             BitmapSizeOptions.FromEmptyOptions()
                                                                                             );
                    DeleteObject(hBitmap);
                    blurredThumb.Dispose();
                    backgroundImageBrush.Stretch = Stretch.UniformToFill;
                    backgroundRect.Fill          = backgroundImageBrush;
                    backgroundRect.Effect        = null;
                    streamInfo.Stream.Close();
                    streamInfo.Stream.Dispose();
                    return(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    count++;
                    if (count == maxTries)
                    {
                        return(false);
                    }
                }
            }
        }
Exemplo n.º 33
0
        public new void BeforeRender(Scene scene)
        {
            if (vanillaMoonParticles == null)
            {
                // back up the vanilla particles.
                vanillaMoonParticles = (Engine.Scene as Overworld)?.Entities.OfType <MoonParticle3D>().First();
            }

            string path;

            try {
                path = Path.Combine("Maps", SaveData.Instance?.LastArea.GetSID() ?? "").Replace('\\', '/');
            } catch (ArgumentException) {
                path = "Maps";
            }

            string SIDToUse = SaveData.Instance?.LastArea.GetSID() ?? "";
            bool   fadingIn = true;

            // Check if we're changing any mountain parameter
            // If so, we want to fade out and then back in
            if (PreviousSID != null && !(SaveData.Instance?.LastArea.GetSID() ?? "").Equals(PreviousSID))
            {
                MapMetaMountain oldMountain = null;
                MapMetaMountain newMountain = null;
                if (SaveData.Instance != null && Everest.Content.TryGet(path, out ModAsset asset1))
                {
                    MapMeta meta;
                    if (asset1 != null && (meta = asset1.GetMeta <MapMeta>()) != null && meta.Mountain != null)
                    {
                        newMountain = meta.Mountain;
                    }
                }
                string oldPath;
                try {
                    oldPath = Path.Combine("Maps", PreviousSID ?? "").Replace('\\', '/');
                } catch (ArgumentException) {
                    oldPath = "Maps";
                }
                if (SaveData.Instance != null && Everest.Content.TryGet(oldPath, out asset1))
                {
                    MapMeta meta;
                    if (asset1 != null && (meta = asset1.GetMeta <MapMeta>()) != null && meta.Mountain != null)
                    {
                        oldMountain = meta.Mountain;
                    }
                }

                if (oldMountain?.MountainModelDirectory != newMountain?.MountainModelDirectory ||
                    oldMountain?.MountainTextureDirectory != newMountain?.MountainTextureDirectory ||
                    (oldMountain?.FogColors == null) != (newMountain?.FogColors == null) || // only fade to black if one end has custom fog colors and the other doesn't.
                    oldMountain?.StarFogColor != newMountain?.StarFogColor ||
                    (oldMountain?.ShowSnow ?? true) != (newMountain?.ShowSnow ?? true) ||
                    !arrayEqual(oldMountain?.StarStreamColors, newMountain?.StarStreamColors) ||
                    !arrayEqual(oldMountain?.StarBeltColors1, newMountain?.StarBeltColors1) ||
                    !arrayEqual(oldMountain?.StarBeltColors2, newMountain?.StarBeltColors2))
                {
                    if (fade != 1f)
                    {
                        // fade out, and continue using the old mountain during the fadeout.
                        SIDToUse = PreviousSID;
                        path     = oldPath;
                        fade     = Calc.Approach(fade, 1f, Engine.DeltaTime * 4f);
                        fadingIn = false;
                    }
                    else
                    {
                        // start holding the black screen
                        fadeHoldCountdown = .3f;
                    }
                }
            }

            if (fadingIn && fade != 0f)
            {
                if (fadeHoldCountdown <= 0)
                {
                    // fade in
                    fade = Calc.Approach(fade, 0f, Engine.DeltaTime * 4f);
                }
                else
                {
                    // hold the black screen
                    fadeHoldCountdown -= Engine.DeltaTime;
                }
            }

            if (SaveData.Instance != null && Everest.Content.TryGet(path, out ModAsset asset))
            {
                MapMeta meta;
                if (asset != null && (meta = asset.GetMeta <MapMeta>()) != null && meta.Mountain != null && hasCustomSettings(meta))
                {
                    // there is a custom mountain! render it, similarly to vanilla.
                    MountainResources resources = MTNExt.MountainMappings[path];

                    ResetRenderTargets();
                    Quaternion rotation = Camera.Rotation;
                    if (ignoreCameraRotation)
                    {
                        rotation = lastCameraRotation;
                    }
                    Matrix matrix  = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, (float)Engine.Width / (float)Engine.Height, 0.25f, 50f);
                    Matrix matrix2 = Matrix.CreateTranslation(-Camera.Position) * Matrix.CreateFromQuaternion(rotation);
                    Matrix matrix3 = matrix2 * matrix;
                    Forward = Vector3.Transform(Vector3.Forward, Camera.Rotation.Conjugated());
                    Engine.Graphics.GraphicsDevice.SetRenderTarget(buffer);

                    if (StarEase < 1f)
                    {
                        Matrix matrix4 = Matrix.CreateTranslation(0f, 5f - Camera.Position.Y * 1.1f, 0f) * Matrix.CreateFromQuaternion(rotation) * matrix;

                        if (currState == nextState)
                        {
                            (resources.MountainStates?[currState] ?? mountainStates[currState]).Skybox.Draw(matrix4, Color.White);
                        }
                        else
                        {
                            (resources.MountainStates?[currState] ?? mountainStates[currState]).Skybox.Draw(matrix4, Color.White);
                            (resources.MountainStates?[nextState] ?? mountainStates[nextState]).Skybox.Draw(matrix4, Color.White * easeState);
                        }
                        if (currState != nextState)
                        {
                            GFX.FxMountain.Parameters["ease"].SetValue(easeState);
                            GFX.FxMountain.CurrentTechnique = GFX.FxMountain.Techniques["Easing"];
                        }
                        else
                        {
                            GFX.FxMountain.CurrentTechnique = GFX.FxMountain.Techniques["Single"];
                        }
                        Engine.Graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
                        Engine.Graphics.GraphicsDevice.BlendState        = BlendState.AlphaBlend;
                        Engine.Graphics.GraphicsDevice.RasterizerState   = MountainRasterizer;
                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                        GFX.FxMountain.Parameters["fog"].SetValue(customFog.TopColor.ToVector3());
                        Engine.Graphics.GraphicsDevice.Textures[0]      = (resources.MountainStates?[currState] ?? mountainStates[currState]).TerrainTexture.Texture;
                        Engine.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
                        if (currState != nextState)
                        {
                            Engine.Graphics.GraphicsDevice.Textures[1]      = (resources.MountainStates?[nextState] ?? mountainStates[nextState]).TerrainTexture.Texture;
                            Engine.Graphics.GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
                        }
                        (resources.MountainTerrain ?? MTN.MountainTerrain).Draw(GFX.FxMountain);
                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(Matrix.CreateTranslation(CoreWallPosition) * matrix3);
                        (resources.MountainCoreWall ?? MTN.MountainCoreWall).Draw(GFX.FxMountain);

                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                        for (int i = 0; i < resources.MountainExtraModels.Count; i++)
                        {
                            Engine.Graphics.GraphicsDevice.Textures[0]      = (resources.MountainExtraModelTextures[i][currState] ?? mountainStates[currState].TerrainTexture).Texture;
                            Engine.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
                            if (currState != nextState)
                            {
                                Engine.Graphics.GraphicsDevice.Textures[1]      = (resources.MountainExtraModelTextures[i][nextState] ?? mountainStates[nextState].TerrainTexture).Texture;
                                Engine.Graphics.GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
                            }
                            resources.MountainExtraModels[i].Draw(GFX.FxMountain);
                        }
                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                        Engine.Graphics.GraphicsDevice.Textures[0]      = (resources.MountainStates?[currState] ?? mountainStates[currState]).BuildingsTexture.Texture;
                        Engine.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
                        if (currState != nextState)
                        {
                            Engine.Graphics.GraphicsDevice.Textures[1]      = (resources.MountainStates?[nextState] ?? mountainStates[nextState]).BuildingsTexture.Texture;
                            Engine.Graphics.GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
                        }
                        (resources.MountainBuildings ?? MTN.MountainBuildings).Draw(GFX.FxMountain);
                        customFog.Draw(matrix3);
                    }

                    if (StarEase > 0f)
                    {
                        Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
                        Draw.Rect(0f, 0f, buffer.Width, buffer.Height, Color.Black * Ease.CubeInOut(Calc.ClampedMap(StarEase, 0f, 0.6f)));
                        Draw.SpriteBatch.End();
                        Matrix matrix5 = Matrix.CreateTranslation(starCenter - Camera.Position) * Matrix.CreateFromQuaternion(rotation) * matrix;
                        float  alpha   = Calc.ClampedMap(StarEase, 0.8f, 1f);
                        customStarsky.Draw(matrix5, CullCCRasterizer, alpha);
                        customStarfog.Draw(matrix5, CullCCRasterizer, alpha);
                        customStardots0.Draw(matrix5, CullCCRasterizer, alpha);
                        customStarstream0.Draw(matrix5, CullCCRasterizer, alpha);
                        customStarstream1.Draw(matrix5, CullCCRasterizer, alpha);
                        customStarstream2.Draw(matrix5, CullCCRasterizer, alpha);
                        Engine.Graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
                        Engine.Graphics.GraphicsDevice.BlendState        = BlendState.AlphaBlend;
                        Engine.Graphics.GraphicsDevice.RasterizerState   = CullCRasterizer;
                        Engine.Graphics.GraphicsDevice.Textures[0]       = (resources.MountainMoonTexture ?? MTN.MountainMoonTexture).Texture;
                        Engine.Graphics.GraphicsDevice.SamplerStates[0]  = SamplerState.LinearClamp;
                        GFX.FxMountain.CurrentTechnique = GFX.FxMountain.Techniques["Single"];
                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix3);
                        GFX.FxMountain.Parameters["fog"].SetValue(fog.TopColor.ToVector3());
                        (resources.MountainMoon ?? MTN.MountainMoon).Draw(GFX.FxMountain);
                        float  num     = birdTimer * 0.2f;
                        Matrix matrix6 = Matrix.CreateScale(0.25f) * Matrix.CreateRotationZ((float)Math.Cos(num * 2f) * 0.5f) * Matrix.CreateRotationX(0.4f + (float)Math.Sin(num) * 0.05f) * Matrix.CreateRotationY(0f - num - (float)Math.PI / 2f) * Matrix.CreateTranslation((float)Math.Cos(num) * 2.2f, 31f + (float)Math.Sin(num * 2f) * 0.8f, (float)Math.Sin(num) * 2.2f);
                        GFX.FxMountain.Parameters["WorldViewProj"].SetValue(matrix6 * matrix3);
                        GFX.FxMountain.Parameters["fog"].SetValue(fog.TopColor.ToVector3());
                        (resources.MountainBird ?? MTN.MountainBird).Draw(GFX.FxMountain);
                    }

                    DrawBillboards(matrix3, scene.Tracker.GetComponents <Billboard>());

                    if (StarEase < 1f)
                    {
                        customFog2.Draw(matrix3, CullCRasterizer);
                    }

                    if (DrawDebugPoints && DebugPoints.Count > 0)
                    {
                        GFX.FxDebug.World              = Matrix.Identity;
                        GFX.FxDebug.View               = matrix2;
                        GFX.FxDebug.Projection         = matrix;
                        GFX.FxDebug.TextureEnabled     = false;
                        GFX.FxDebug.VertexColorEnabled = true;
                        VertexPositionColor[] array = DebugPoints.ToArray();
                        foreach (EffectPass pass in GFX.FxDebug.CurrentTechnique.Passes)
                        {
                            pass.Apply();
                            Engine.Graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, array, 0, array.Length / 3);
                        }
                    }
                    GaussianBlur.Blur((RenderTarget2D)buffer, blurA, blurB, 0.75f, clear: true, samples: GaussianBlur.Samples.Five);

                    // render the fade to black.
                    Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
                    Draw.Rect(-10f, -10f, 1940f, 1100f, Color.Black * fade);
                    Draw.SpriteBatch.End();

                    // Initialize new custom fog and star belt when we switch between maps
                    if (!(SIDToUse).Equals(PreviousSID))
                    {
                        // save values to make transition smoother.
                        Color fogColorBeforeReload = customFog?.TopColor ?? Color.White;
                        float spinBeforeReload     = customFog.Verts[1].TextureCoordinate.X;

                        // build new objects with custom textures.
                        customFog         = new Ring(6f, -1f, 20f, 0f, 24, Color.White, resources.MountainFogTexture ?? MTN.MountainFogTexture);
                        customFog2        = new Ring(6f, -4f, 10f, 0f, 24, Color.White, resources.MountainFogTexture ?? MTN.MountainFogTexture);
                        customStarsky     = new Ring(18f, -18f, 20f, 0f, 24, Color.White, Color.Transparent, resources.MountainSpaceTexture ?? MTN.MountainStarSky);
                        customStarfog     = new Ring(10f, -18f, 19.5f, 0f, 24, resources.StarFogColor ?? Calc.HexToColor("020915"), Color.Transparent, resources.MountainFogTexture ?? MTN.MountainFogTexture);
                        customStardots0   = new Ring(16f, -18f, 19f, 0f, 24, Color.White, Color.Transparent, resources.MountainSpaceStarsTexture ?? MTN.MountainStars, 4f);
                        customStarstream0 = new Ring(5f, -8f, 18.5f, 0.2f, 80, resources.StarStreamColors?[0] ?? Color.Black, resources.MountainStarStreamTexture ?? MTN.MountainStarStream);
                        customStarstream1 = new Ring(4f, -6f, 18f, 1f, 80, resources.StarStreamColors?[1] ?? Calc.HexToColor("9228e2") * 0.5f, resources.MountainStarStreamTexture ?? MTN.MountainStarStream);
                        customStarstream2 = new Ring(3f, -4f, 17.9f, 1.4f, 80, resources.StarStreamColors?[2] ?? Calc.HexToColor("30ffff") * 0.5f, resources.MountainStarStreamTexture ?? MTN.MountainStarStream);

                        // restore values saved earlier.
                        customFog.TopColor = customFog.BotColor = fogColorBeforeReload;
                        customFog.Rotate(spinBeforeReload);
                        customFog2.Rotate(spinBeforeReload);

                        if (Engine.Scene is Overworld thisOverworld)
                        {
                            thisOverworld.Remove(customMoonParticles);
                            if (resources.StarBeltColors1 != null && resources.StarBeltColors2 != null)
                            {
                                // there are custom moon particle colors. build the new particles and add them to the scene
                                thisOverworld.Remove(vanillaMoonParticles);
                                thisOverworld.Add(customMoonParticles = new patch_MoonParticle3D(this, new Vector3(0f, 31f, 0f), resources.StarBeltColors1, resources.StarBeltColors2));
                            }
                            else
                            {
                                // there are no more moon particle colors. restore the vanilla particles
                                customMoonParticles = null;
                                thisOverworld.Add(vanillaMoonParticles);
                            }
                        }
                    }

                    PreviousSID = SIDToUse;
                    return;
                }
            }

            // if we are here, it means we don't have a custom mountain.

            if (customMoonParticles != null && Engine.Scene is Overworld overworld)
            {
                // revert back the moon particles to vanilla.
                overworld.Remove(customMoonParticles);
                customMoonParticles = null;
                overworld.Add(vanillaMoonParticles);
            }

            // run vanilla code.
            orig_BeforeRender(scene);

            // render the fade to black.
            Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
            Draw.Rect(-10f, -10f, 1940f, 1100f, Color.Black * fade);
            Draw.SpriteBatch.End();

            PreviousSID = SIDToUse;
        }
Exemplo n.º 34
0
        private Bitmap detectQuads(Bitmap bitmap)
        {
            var cardArtBitmap = bitmap;

            try
            {
                /*
                 *    This code works and crops well on 80% of the images but we need 100%
                 *  */

                var width  = bitmap.Width + bitmap.Width / 2;
                var height = bitmap.Height + bitmap.Height / 2;

                // Create a compatible bitmap
                var dest = new Bitmap(width, height, bitmap.PixelFormat);
                var gd   = Graphics.FromImage(dest);

                dest.Dispose();

                gd.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);

                // Greyscale
                filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap);

                // Contrast
                //ContrastStretch filter = new ContrastStretch();
                //filter.ApplyInPlace(filteredBitmap);

                var cutMargin = 80;

                // split the image to avoid the textbox beeing detected
                var cropFilterPre =
                    new Crop(new Rectangle(0, cutMargin, filteredBitmap.Width, filteredBitmap.Height / 100 * 60));
                filteredBitmap = cropFilterPre.Apply(filteredBitmap);

                // edge filter
                var edgeFilter = new SobelEdgeDetector(); //
                edgeFilter.ApplyInPlace(filteredBitmap);

                // Threshhold filter
                var threshholdFilter = new Threshold(190);
                threshholdFilter.ApplyInPlace(filteredBitmap);

                var bitmapData = filteredBitmap.LockBits(
                    new Rectangle(0, 0, filteredBitmap.Width, filteredBitmap.Height),
                    ImageLockMode.ReadWrite, filteredBitmap.PixelFormat);

                var blobCounter = new BlobCounter();

                blobCounter.FilterBlobs = true;
                blobCounter.MinHeight   = 200;
                blobCounter.MinWidth    = 200;

                blobCounter.ProcessImage(bitmapData);
                var blobs = blobCounter.GetObjectsInformation();
                filteredBitmap.UnlockBits(bitmapData);

                var shapeChecker = new SimpleShapeChecker();

                /*var bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb);
                 *
                 * var g = Graphics.FromImage(bm);
                 * g.DrawImage(filteredBitmap, 0, 0);
                 *
                 * var pen = new Pen(Color.Red, 5);
                 * //var cardPositions = new List<IntPoint>();*/

                // Loop through detected shapes
                for (int i = 0, n = blobs.Length; i < n; i++)
                {
                    var             edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                    List <IntPoint> corners;
                    var             sameCard = false;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        var subType = shapeChecker.CheckPolygonSubType(corners);

                        // Only return 4 corner rectanges
                        if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) &&
                            corners.Count == 4)
                        {
                            // Hack to prevent it from detecting smaller sections of the card instead of the art
                            if (GetArea(corners) < 120000)
                            {
                                continue;
                            }

                            //debug crap

                            /*Bitmap newImage = filteredBitmap;
                             * Random rnd = new Random();
                             * newImage.Save(@"X:\" + rnd.Next() + ".jpg", ImageFormat.Jpeg);*/

                            var x  = corners[0].X;
                            var y  = corners[0].Y + cutMargin;
                            var x2 = corners[2].X - corners[0].X;
                            var y2 = corners[2].Y - (corners[0].Y + 0);

                            if (x2 < 0 || y2 < 0)
                            {
                                x  = corners[1].X;
                                y  = corners[1].Y + cutMargin;
                                x2 = corners[3].X - corners[1].X;
                                y2 = corners[3].Y - (corners[1].Y + 0);
                            }

                            var cropframe = new Rectangle(x, y, x2, y2);

                            var gbfilter = new GaussianBlur(1, 5);
                            gbfilter.ApplyInPlace(bitmap);

                            var cropFilter = new Crop(cropframe);
                            cardArtBitmap = cropFilter.Apply(bitmap);

                            bitmap.Dispose();

                            // pen.Dispose();
                            // g.Dispose();

                            gd.Dispose();

                            filteredBitmap.Dispose();

                            return(cardArtBitmap);
                        }
                    }
                }

                Console.WriteLine("Fallback Triggered!");

                var gfilter = new GaussianBlur(1, 5);
                gfilter.ApplyInPlace(bitmap);

                //Fallback default crop, assumes XLHQ CCGHQ images

                var cropFilterFallback = new Crop(new Rectangle(88, 121, 564, 440));
                cardArtBitmap = cropFilterFallback.Apply(bitmap);

                bitmap.Dispose();

                //pen.Dispose();
                //g.Dispose();

                gd.Dispose();

                filteredBitmap.Dispose();
            }
            catch (Exception e)
            {
                throw;
            }

            return(cardArtBitmap);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Gaussian Blur algorithm. Here we create a new window from where we implement the algorithm.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gaussianBlur_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 {
                GaussianBlur gaussianBlurWindow = new GaussianBlur(m_data, m_vm);
                gaussianBlurWindow.Owner = this;
                gaussianBlurWindow.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);
            }
        }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            int totalImages = 0, currentImage = 0, q;

            Console.Write("Enter initial number for image folder names: ");
            q = Convert.ToInt32(Console.ReadLine());
            Thread.CurrentThread.IsBackground = true;
            //Get the current directory that the program is executing in.
            String directory = Directory.GetCurrentDirectory();

            directory += @"\Images";

            //Set a list of all images in the Image folder.
            String[] files = System.IO.Directory.GetFiles(directory, "*", System.IO.SearchOption.TopDirectoryOnly);
            totalImages = files.Length * 5;
            //Array to hold the images.
            Bitmap[] image;
            Bitmap   temp;
            int      blurAmount;

            //Outer loop increments through each file path in the list.
            for (int i = 0; i < files.Length; i++)
            {
                //Creates a new instance of the array to clear out the values that were left in the image array.
                image = new Bitmap[5];

                //Creates a new instance of random that will help scramble the images
                Random r       = new Random();
                bool[] visited = new bool[5];

                //Creates a new sub-directory based on the image that we're looking at.
                String newDir = directory + @"\Image" + q;
                System.IO.Directory.CreateDirectory(newDir);

                for (int j = 0; j < 5; j++)
                {
                    /*
                     * For simplicity, set the blur ammount to an already incrementing value.
                     * because each new image needs to be blurrier
                     */
                    blurAmount = j * 2;

                    if (j == 0)
                    {
                        image[j] = new Bitmap(files[i]);
                        temp     = new Bitmap(image[j]);
                        Console.WriteLine("\nRetrieving Image: " + files[i]);
                    }
                    else
                    {
                        //Used the previously blurred image to make the next one blurrier.
                        temp = new Bitmap(image[j - 1]);
                    }

                    //Calls the method to blur our image.
                    var blur = new GaussianBlur(temp);

                    //Stores our newly blurred image.
                    image[j] = temp;

                    //inefficiently finds a number between 0 and 4 inclusively that hasn't been already used to assign as the name of the new image
                    int rand = r.Next(0, 5);

                    //Shuffles the ordering of the elements of the array.
                    while (visited[rand] == true)
                    {
                        rand = r.Next(0, 5);
                    }
                    visited[rand] = true;

                    //Writes the image to a jpg file in its directory.
                    var result = blur.Process(blurAmount);
                    result.Save(newDir + "/img" + rand + ".jpg", ImageFormat.Jpeg);

                    Console.WriteLine("\nWrote: " + newDir + "/img" + rand + ".jpg");
                    currentImage++;
                    Console.WriteLine("\nProgress: " + currentImage + "/" + totalImages + " processed");
                }
                q++;
            }
            Console.WriteLine("\nCompleted! All files have been saved to the directory: \n" + directory);
            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 37
0
        public static Bitmap ApplyGaussianBlurFilter(Bitmap input, int kernelSize, double sigma)
        {
            GaussianBlur gaussianBlurFilter = new GaussianBlur(sigma, kernelSize);

            return(gaussianBlurFilter.Apply(input));

            //}
            //else {
            //    if (blurOutside)
            //    {
            //        int distanceToBlur = Math.Min(Math.Min(selectionX, selectionY), kernelSize);
            //        int pixelStep = Math.Max(3, distanceToBlur / kernelSize);
            //        int currentStep = pixelStep;
            //        int kernelReduction = distanceToBlur / pixelStep;
            //        Bitmap temp = (Bitmap)input.Clone();
            //        input = gaussianBlurFilter.Apply(input);
            //        while (kernelSize > 0)
            //        {

            //            if (kernelSize - kernelReduction < 1)
            //            {
            //                gaussianBlurFilter.Size = 2;
            //                input = gaussianBlurFilter.Apply(input);
            //                Rectangle rect1 = new Rectangle(selectionX, selectionY, selectionWidth, selectionHeight);
            //                Bitmap selectedPortion1 = new Bitmap(rect1.Width, rect1.Height);
            //                using (Graphics g = Graphics.FromImage(selectedPortion1))
            //                {
            //                    g.DrawImage(temp, new Rectangle(0, 0, rect1.Width, rect1.Height), rect1, GraphicsUnit.Pixel);
            //                }

            //                //selectedPortion = gaussianBlurFilter.Apply(selectedPortion);
            //                using (Graphics g = Graphics.FromImage(input))
            //                {
            //                    g.DrawImage(selectedPortion1, rect1);
            //                }
            //                break;
            //            }
            //            Rectangle rect = new Rectangle(selectionX-currentStep,selectionY- currentStep, input.Width+currentStep, input.Height + currentStep);
            //            Bitmap selectedPortion = new Bitmap(rect.Width, rect.Height);
            //            using (Graphics g = Graphics.FromImage(selectedPortion))
            //            {
            //                g.DrawImage(temp, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
            //            }
            //            gaussianBlurFilter.Size = kernelSize;
            //            selectedPortion = gaussianBlurFilter.Apply(selectedPortion);
            //            using (Graphics g = Graphics.FromImage(input))
            //            {
            //                g.DrawImage(selectedPortion, rect);
            //            }
            //            currentStep += pixelStep;
            //            kernelSize -= kernelReduction;
            //        }
            //        //Rectangle rect = new Rectangle(selectionX, selectionY, selectionWidth, selectionHeight);
            //            //Bitmap selectedPortion = new Bitmap(rect.Width, rect.Height);
            //        //    using (Graphics g = Graphics.FromImage(selectedPortion))
            //        //    {
            //        //        g.DrawImage(input, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
            //        //    }
            //        ////AddBitmapImageToImage(selectedPortion);
            //        ////Bitmap temp = (Bitmap)input.Clone();

            //        //while (kernelSize > 0 && distanceToBlur > pixelStep)
            //        //{
            //        //    Rectangle rect1 = new Rectangle(selectionX - distanceToBlur, selectionY - distanceToBlur, selectionWidth + distanceToBlur, selectionHeight + distanceToBlur);
            //        //    Bitmap selectedPortion1 = new Bitmap(rect.Width, rect.Height);
            //        //    using (Graphics g = Graphics.FromImage(selectedPortion1))
            //        //    {
            //        //        g.DrawImage(temp, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
            //        //    }
            //        //    using (Graphics g = Graphics.FromImage(input))
            //        //    {
            //        //        g.DrawImage(selectedPortion, rect);
            //        //    }
            //        //}
            //        //}
            //        //input = gaussianBlurFilter.Apply(input);
            //        return input;
            //    }
            //    else {
            //        Rectangle rect = new Rectangle(selectionX, selectionY, selectionWidth, selectionHeight);
            //        Bitmap selectedPortion = new Bitmap(rect.Width, rect.Height);
            //        using (Graphics g = Graphics.FromImage(selectedPortion))
            //        {
            //            g.DrawImage(input, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
            //        }
            //        //AddBitmapImageToImage(selectedPortion);

            //        selectedPortion = gaussianBlurFilter.Apply(selectedPortion);
            //        using (Graphics g = Graphics.FromImage(input))
            //        {
            //            g.DrawImage(selectedPortion, rect);
            //        }
            //        return input;
            //    }

            //}
        }
Exemplo n.º 38
0
        public Bitmap Run(Bitmap image)
        {
            GaussianBlur gaussianBlur = new GaussianBlur(image);

            return(gaussianBlur.Process(blurStrength));
        }
        // Initializor=============================================
        public override void Initialize()
        {
            // Initialize the Camera
            camera = new ShakedCamera(this);
            camera.Position = new Vector3(0, 13, 17);
            camera.Target = new Vector3(0, 0, 3);

            if (!Engine.Services.ContainsService(typeof(Camera)))
                Engine.Services.AddService(typeof(Camera), (ShakedCamera)camera);

            // Initialize the keyboard
            keyboard = Engine.Services.GetService<KeyboardDevice>();

            // Initialize the sounds

            music = Engine.Content.Load<Song>("Content\\Sounds\\music1");
            MediaPlayer.Play(music);
            MediaPlayer.Volume = 0.2f;
            MediaPlayer.IsRepeating = true;

            // Inistialize tha black Texture
            black = new Entity2D(Engine.Content.Load<Texture2D>("Content\\Textures\\black"),
                    Vector2.Zero, this);

            // Initialize tha Radar
            radar = new Radar(Engine.Content.Load<Model>("Content\\Models\\Radar"), Vector3.One, this);
            radar.Visible = false;

            // Initialize the Ball
            ball = new Ball(Engine.Content.Load<Model>("Content\\Models\\GameBall"),
                            new Vector3(0f,0f,5f), this);
            ball.defaultLightingEnabled = true;

            // Initialize the Bricks List
            brickLenghtLine = 3;
            brickLenghtColumn = 10;
            totalOfBricks = brickLenghtLine * brickLenghtColumn;
            totalOfBricksLeft = totalOfBricks;
            brickMapArray=new int[brickLenghtLine, brickLenghtColumn];
            brickObjectArray = new Brick[brickLenghtLine, brickLenghtColumn];

            for (int i = 0; i < brickLenghtLine; i++)
            {
                for (int j = 0; j < brickLenghtColumn; j++)
                {
                    brickMapArray[i, j] = Util.random.Next(0, 3);
                }
            }

            // Initialize the Released Object array
            ReleasedObjectArray = new ReleasedObject[totalOfBricks];
            for (int i = 0; i < totalOfBricks; i++)
                ReleasedObjectArray[i] = null;

            ReleasedObjectArrayIndex = 0;

            // initialize the ObjectArray of bricks
            for (int i = 0; i < brickLenghtLine; i++)
            {
                for (int j = 0; j < brickLenghtColumn; j++)
                {
                    Brick brick;
                    Model model;
                    // Type of Brick
                    Vector3 brikPos = new Vector3(-7f + j * 1.5f, 0f, -4f + i*1.5f);
                    switch (brickMapArray[i,j])
                    {
                        case 0:
                            // Type Normal
                            model = Engine.Content.Load<Model>("Content\\Models\\GameBrick1");
                            brick = new Brick(model, brikPos, this);
                            brick.BrickReleaseType = BrickReleaseType.Normal;
                            brickObjectArray[i, j] = brick;

                            model = Engine.Content.Load<Model>("Content\\Models\\ReleasedNormObject");
                            ReleasedObjectArray[brickLenghtColumn * i + j] = new NormalObject(model, brikPos, this);
                            break;
                        case 1:
                            // Type Score
                            model = Engine.Content.Load<Model>("Content\\Models\\GameBrick1");
                            brick = new Brick(model, brikPos, this);
                            brick.BrickReleaseType = BrickReleaseType.Money;
                            brickObjectArray[i, j] = brick;

                            model = Engine.Content.Load<Model>("Content\\Models\\ReleasedMoneyObject");
                            ReleasedObjectArray[brickLenghtColumn * i + j] = new MoneyObject(model, brikPos, this);
                            break;
                        case 2:
                            // Type Life
                            model = Engine.Content.Load<Model>("Content\\Models\\GameBrick1");
                            brick = new Brick(model, brikPos, this);
                            brick.BrickReleaseType = BrickReleaseType.Danger;
                            brickObjectArray[i, j] = brick;

                            model = Engine.Content.Load<Model>("Content\\Models\\ReleasedDangerObject");
                            ReleasedObjectArray[brickLenghtColumn * i + j] = new DangerObject(model, brikPos, this);
                            break;

                        default:
                            // Type Normal
                            model = Engine.Content.Load<Model>("Content\\Models\\GameBrick1");
                            brick = new Brick(model, brikPos, this);
                            brick.BrickReleaseType = BrickReleaseType.Normal;
                            brickObjectArray[i, j] = brick;

                            model = Engine.Content.Load<Model>("Content\\Models\\ReleasedNormObject");
                            ReleasedObjectArray[brickLenghtColumn * i + j] = new NormalObject(model, brikPos, this);
                            break;
                    }

                    // Update the ReleasedObjectArrayIndex
                    if (ReleasedObjectArrayIndex >= totalOfBricks)
                        ReleasedObjectArrayIndex = 0;
                    else
                        ReleasedObjectArrayIndex++;
                }
            }

            // Initialize the Paddle
            paddle = new Paddle(Engine.Content.Load<Model>("Content\\Models\\GamePaddle"), Vector3.Zero, this);
            paddle.defaultLightingEnabled = true;

            // Iniotialize the spiralRod
            paddleSupport = new PaddleSupport(Engine.Content.Load<Model>("Content\\Models\\SpiralRod"),
                                     new Vector3(0f, 0.6f, 9f), this);
            //paddleSupport.Rotation = Matrix.CreateRotationZ(MathHelper.ToRadians(90f));
            paddleSupport.defaultLightingEnabled = true;

            // Initialize the Blur
            blur = new GaussianBlur(Engine.Viewport.Width, Engine.Viewport.Height, this);
            blur.Visible = false;

            // Initialize HUD
            hud = new Hud(this);

            // Initialize the gameMap
            gameMap = new Entity3D(Engine.Content.Load<Model>("Content\\Models\\GameMap"), Vector3.Zero, this);
            gameMap.defaultLightingEnabled = true;

            base.Initialize();
        }
Exemplo n.º 40
0
        public Bitmap Blur(Bitmap image)
        {
            GaussianBlur filter = new GaussianBlur(4, 20);

            return(filter.Apply(image));
        }