Esempio n. 1
0
        //scaling image
        public static Bitmap ScaleImage(Bitmap mmap)
        {
            var obj    = new ResizeNearestNeighbor(50, 50);
            var result = obj.Apply(mmap);

            return(result);
        }
Esempio n. 2
0
        private double[] GetFeatures()
        {
            rtb = new RenderTargetBitmap((int)InkCanvas1.ActualWidth, (int)InkCanvas1.ActualHeight,
                                         96d, 96d, PixelFormats.Default);

            rtb.Render(InkCanvas1);

            //save the ink to a memory stream
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(rtb));

            byte[] bitmapBytes;
            Bitmap bmp;

            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                ms.Position = 0;
                bitmapBytes = ms.ToArray();

                ms.Seek(0, SeekOrigin.Begin);
                bmp = new Bitmap(ms);
            }

            bmp = resize.Apply(bmp);

            double[] features = ToFeatures(bmp);

            return(features);
        }
Esempio n. 3
0
        public void resize_nearest()
        {
            double[,] diag = Matrix.Magic(5);
            diag           = diag.Divide(diag.Max());

            Bitmap input = diag.ToBitmap();

            // Create a new resize bilinear filter
            var filter = new ResizeNearestNeighbor(7, 8);

            // Apply the filter
            Bitmap output = filter.Apply(input);

            Assert.AreEqual(7, output.Width);
            Assert.AreEqual(8, output.Height);

            double[,] actual;
            new ImageToMatrix().Convert(output, out actual);

            string str = actual.ToString(CSharpMatrixFormatProvider.InvariantCulture);

            double[,] expected =
            {
                {  0.67843137254902,  0.67843137254902, 0.956862745098039, 0.0392156862745098, 0.0392156862745098,  0.317647058823529,               0.6 },
                {  0.67843137254902,  0.67843137254902, 0.956862745098039, 0.0392156862745098, 0.0392156862745098,  0.317647058823529,               0.6 },
                { 0.917647058823529, 0.917647058823529,               0.2,   0.27843137254902,   0.27843137254902,  0.556862745098039,  0.63921568627451 },
                { 0.917647058823529, 0.917647058823529,               0.2,   0.27843137254902,   0.27843137254902,  0.556862745098039,  0.63921568627451 },
                { 0.156862745098039, 0.156862745098039,  0.23921568627451,  0.517647058823529,  0.517647058823529,                0.8,  0.87843137254902 },
                {               0.4,               0.4,  0.47843137254902,  0.756862745098039,  0.756862745098039,   0.83921568627451, 0.117647058823529 },
                {               0.4,               0.4,  0.47843137254902,  0.756862745098039,  0.756862745098039,   0.83921568627451, 0.117647058823529 },
                {  0.43921568627451,  0.43921568627451, 0.717647058823529,                  1,                  1, 0.0784313725490196, 0.356862745098039 }
            };

            Assert.IsTrue(expected.IsEqual(actual, 1e-6));
        }
        private string GerarThumbnail(string caminhoCompletoDoArquivo)
        {
            ImageInfo imageInfo;
            var       nomeSaida = Path.Combine(Path.GetDirectoryName(caminhoCompletoDoArquivo), string.Format("{0}_THUMB.JPG", Path.GetFileNameWithoutExtension(caminhoCompletoDoArquivo)));

            var bitmapOriginal = ImageDecoder.DecodeFromFile(caminhoCompletoDoArquivo, out imageInfo);
            int width;
            int height;

            if (bitmapOriginal.Width > bitmapOriginal.Height)
            {
                width  = Contexto.DimensoesThumbnail[1];
                height = Contexto.DimensoesThumbnail[0];
            }
            else
            {
                width  = Contexto.DimensoesThumbnail[0];
                height = Contexto.DimensoesThumbnail[1];
            }

            var filter   = new ResizeNearestNeighbor(width, height);
            var bmpThumb = filter.Apply(bitmapOriginal);

            this.SalvarComo(bmpThumb, nomeSaida, ImageFormat.Jpeg, 8, Contexto.QualidadeThumbnail);
            bmpThumb.Dispose();
            bitmapOriginal.Dispose();
            return(nomeSaida);
        }
Esempio n. 5
0
        public Bitmap getCut(System.Drawing.Point inP, System.Drawing.Point finP, System.Drawing.Image imgOrigin)
        {
            Crop   cut = null;
            Bitmap bmp = (Bitmap)imgOrigin;

            if (inP.X < finP.X && inP.Y < finP.Y)
            {
                cut = new Crop(new Rectangle(inP.X, inP.Y, finP.X - inP.X, finP.Y - inP.Y));
            }
            else if (inP.X > finP.X && inP.Y > finP.Y)
            {
                cut = new Crop(new Rectangle(finP.X, finP.Y, inP.X - finP.X, inP.Y - finP.Y));
            }
            else if (inP.X < finP.X && inP.Y > finP.Y)
            {
                cut = new Crop(new Rectangle(inP.X, finP.Y, finP.X - inP.X, inP.Y - finP.Y));
            }
            else if (inP.X > finP.X && inP.Y < finP.Y)
            {
                cut = new Crop(new Rectangle(finP.X, inP.Y, inP.X - finP.X, finP.Y - inP.Y));
            }
            bmp = cut.Apply(bmp);
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(bmp.Width * 2, bmp.Height * 2);

            bmp = filter.Apply(bmp);
            return(bmp);
        }
Esempio n. 6
0
        private void removeBlankPlaces()
        {
            Shrink shrinkFilter = new Shrink(Color.FromArgb(255, 255, 255));
            ResizeNearestNeighbor resizeFilter = new ResizeNearestNeighbor(0, 0);

            Bitmap tempImage = shrinkFilter.Apply(_processedImage.Bitmap);

            // image dimenstoin
            int width  = _processedImage.Width;
            int height = _processedImage.Height;
            // shrinked image dimension
            int tw = tempImage.Width;
            int th = tempImage.Height;
            // resize factors
            float fx = (float)width / (float)tw;
            float fy = (float)height / (float)th;

            if (fx > fy)
            {
                fx = fy;
            }
            // set new size of shrinked image
            int nw = (int)Math.Round(fx * tw);
            int nh = (int)Math.Round(fy * th);

            resizeFilter.NewWidth  = nw;
            resizeFilter.NewHeight = nh;

            // resize image
            Bitmap tempImage2 = resizeFilter.Apply(tempImage);

            Image <Bgr, Byte> imageCV = new Image <Bgr, byte>(tempImage2);

            _processedImage = imageCV.Mat;
        }
Esempio n. 7
0
        public static Bitmap ResizeNearestNeighbor(Bitmap Imagem, int newWidth, int newHeight)
        {
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(newWidth, newHeight);

            Imagem = Imagem.Clone(new Rectangle(0, 0, Imagem.Width, Imagem.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Imagem = filter.Apply(Imagem);
            return(Imagem);
        }
Esempio n. 8
0
        public static Bitmap Shrink(Bitmap img, float scaleFactor)
        {
            var newX  = (int)(img.Width * scaleFactor);
            var newY  = (int)(img.Height * scaleFactor);
            var scale = new ResizeNearestNeighbor(newX, newY);

            return(scale.Apply(img));
        }
Esempio n. 9
0
        public Bitmap Resize(Bitmap bmp, int newWidth, int newHeight)
        {
            // create filter
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(newWidth, newHeight);
            // apply the filter
            Bitmap newImage = filter.Apply(bmp);

            return(newImage);
        }
        public Bitmap ResizeImage()
        {
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(BitmapToBeResized.Width * 5, BitmapToBeResized.Height * 5);


            Bitmap resizedImage = filter.Apply(BitmapToBeResized);

            return(resizedImage);
        }
Esempio n. 11
0
        /// <summary>
        /// Resize an image to 10x20 px
        /// </summary>
        /// <param name="image">Reference to a Bitmap</param>
        private void Resize(ref System.Drawing.Bitmap image)
        {
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(10, 17);

            try
            {
                image = filter.Apply(image);
            }
            catch (Exception) { }
        }
Esempio n. 12
0
        void goruntuGuncelle()
        {
            try
            {
                if (comboBox1.SelectedIndex == 0)
                {
                    //resim döndürme filtresi tanımlandı
                    //bu filtre sistemi yormuyor
                    //diğerleri sistemi zorluyor
                    //resim döndürme saat yönünün tersine doğru yapılıyor

                    //fonksiyona paremetre olarak true verilirse resmin tamamı ekrana sığdırılmıyor
                    //bazı yerler kırpılıyor
                    //fakat resim boyutu (genişliği ve yükseliği) değişmiyor
                    //görüntü daha güzel görünüyor

                    //eğer false olursa resim küçültme büyütme işlemelerinde resim boyutuda (genişliği ve yükseliği) değişiyor
                    //yani false olunca resim daima ekrana sığdırılıyor
                    RotateNearestNeighbor boyutlandirmaFiltresi = new RotateNearestNeighbor(trackBar1.Value, tamEkran);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image);
                    //resim boyut değiştirme filtresi tanımlandı
                    //bu filtre sistemi yormuyor
                    //diğerleri sistemi zorluyor
                    ResizeNearestNeighbor boyutlandirma = new ResizeNearestNeighbor(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image);
                }
                if (comboBox1.SelectedIndex == 1)
                {
                    //resim döndürme filtresi tanımlandı
                    RotateBilinear boyutlandirmaFiltresi = new RotateBilinear(trackBar1.Value, tamEkran);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image);
                    //resim boyut değiştirme filtresi tanımlandı
                    ResizeBicubic boyutlandirma = new ResizeBicubic(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image);
                }
                if (comboBox1.SelectedIndex == 2)
                {
                    //resim döndürme filtresi tanımlandı
                    RotateBicubic boyutlandirmaFiltresi = new RotateBicubic(trackBar1.Value, tamEkran);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirmaFiltresi.Apply((Bitmap)pictureBox1.Image);
                    //resim boyut değiştirme filtresi tanımlandı
                    ResizeBilinear boyutlandirma = new ResizeBilinear(resim.Width + trackBar2.Value, resim.Height + trackBar2.Value);
                    //resim dosyasına filtre uygulandı
                    pictureBox2.Image = boyutlandirma.Apply((Bitmap)pictureBox1.Image);
                }
            }
            catch
            {
            }
        }
Esempio n. 13
0
 private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
 {
     /* Zwolnienie pamieci */
     if (actualFrame != null)
     {
         actualFrame.Dispose();
     }
     /* Kopiowanie obrazka dostarczonego przez kamere */
     actualFrame = (Bitmap)eventArgs.Frame.Clone();
     /* Zastosowanie filtra lustra */
     filter.ApplyInPlace(actualFrame);
     /* Usuniecie poprzedniego obrazka u klienta */
     if (clientView.myVideoPictureBox.Image != null)
     {
         clientView.Invoke(new MethodInvoker(delegate() { clientView.myVideoPictureBox.Image.Dispose(); }));
     }
     /* Zaladowanie nowego obrazka */
     clientView.myVideoPictureBox.Image = filterSize.Apply(actualFrame);
     /*Wyslanie obecnego obrazka do partnera*/
     SendVideo(actualFrame);
 }
Esempio n. 14
0
        void reader_IRFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            var reference = e.FrameReference.AcquireFrame();

            using (InfraredFrame frame = reference.InfraredFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    int      width     = frame.FrameDescription.Width;
                    int      height    = frame.FrameDescription.Height;
                    ushort[] data      = new ushort[width * height];
                    byte[]   pixelData = new byte[width * height * 4];
                    int      xcoord    = 0;
                    int      ycoord    = 0;

                    frame.CopyFrameDataToArray(data);
                    int    akt    = 0;
                    Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                    for (int infraredIndex = 0; infraredIndex < data.Length; infraredIndex++)
                    {
                        ushort ir        = data[infraredIndex];
                        byte   intensity = (byte)(ir >> 8);

                        pixelData[infraredIndex * 4]     = intensity; // Blue
                        pixelData[infraredIndex * 4 + 1] = intensity; // Green
                        pixelData[infraredIndex * 4 + 2] = intensity; // Red
                        pixelData[infraredIndex * 4 + 3] = 255;       //Brightness
                    }
                    var bitmapdata = bitmap.LockBits(
                        new Rectangle(0, 0, width, height),
                        ImageLockMode.WriteOnly,
                        bitmap.PixelFormat
                        );
                    IntPtr ptr = bitmapdata.Scan0;

                    Marshal.Copy(pixelData, 0, ptr, pixelData.Length);
                    bitmap.UnlockBits(bitmapdata);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);

                    EuclideanColorFiltering filter  = new EuclideanColorFiltering();
                    ResizeNearestNeighbor   filter2 = new ResizeNearestNeighbor(512, 424);
                    filter.Radius      = (short)trackBar1.Value; //Increase this to allow off-whites
                    filter.FillOutside = false;

                    Bitmap bmp = filter.Apply(bitmap);

                    filter2.Apply(bmp);
                    //filter3.Apply(bmp);
                    pictureBox1.Image = bitmap;
                }
            }
        }
Esempio n. 15
0
    public void UpdateBitmapMethod()
    {
        try {
            /*// resize image
             * Bitmap newImage = resizeFilter.Apply(localCacheBitmap);
             * //update image
             * updateBitmapMethod(newImage, 255);
             * //free temp bitmap
             * newImage.Dispose();*/



            //if image should be cropped apply filter, otherwise just set it to resized image
            if (cropHPixelOffset > 0)
            {
                Bitmap croppedImage          = cropFilter.Apply(localCacheBitmap);
                Bitmap resizedImageAfterCrop = resizeFilter.Apply(croppedImage);
                //update image
                UpdateBitmapMethod(resizedImageAfterCrop, 255);


                resizedImageAfterCrop.Dispose();
                croppedImage.Dispose();
            }
            else
            {
                // resize image
                Bitmap resizedImage = resizeFilter.Apply(localCacheBitmap);
                //update image
                UpdateBitmapMethod(resizedImage, 255);
                //free temp bitmap
                resizedImage.Dispose();
            }
        }
        catch (System.ArgumentException e)
        {
            //this happens if localCacheBitmap is disposed?
        }
    }
Esempio n. 16
0
        private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand)
        {
            Crop c         = new Crop(rect);
            var  handImage = c.Apply(mask);

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

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

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


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


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

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

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

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

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

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

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

                    pbHand.Image = leftHand;
                }
            }
        }
Esempio n. 17
0
        private Bitmap Detecting(Bitmap _bitmap)
        {
            UnmanagedImage im = UnmanagedImage.FromManagedImage(_bitmap);

            float xscale = im.Width / 160f;
            float yscale = im.Height / 120f;

            ResizeNearestNeighbor resize     = new ResizeNearestNeighbor(160, 120);
            UnmanagedImage        downsample = resize.Apply(im);


            Rectangle[] regions = detector.ProcessFrame(downsample);


            if (regions.Length > 0)
            {
                tracker.Reset();

                // Reduce the face size to avoid tracking background
                Rectangle window = new Rectangle(
                    (int)((regions[0].X + regions[0].Width / 2f) * xscale),
                    (int)((regions[0].Y + regions[0].Height / 2f) * yscale),
                    1, 1);

                window.Inflate(
                    (int)(0.2f * regions[0].Width * xscale),
                    (int)(0.4f * regions[0].Height * yscale));

                this.FaceTracked = window;

                // Initialize tracker
                tracker.SearchWindow = window;
                tracker.ProcessFrame(im);

                marker = new RectanglesMarker(window);
                marker.ApplyInPlace(im);

                // (Bitmap) Helpers.BitmapHelper.ByteArrayToImage(Helpers.RijndaelHelper.EncryptBytes(Helpers.BitmapHelper.ImageToByte(im.ToManagedImage()), "fzafa", "afzd"))

                this.isTracking = true;

                return(im.ToManagedImage());
            }
            else
            {
                this.isDetecting = false;
                return(_bitmap);
            }
        }
Esempio n. 18
0
        private void button7_Click(object sender, EventArgs e)
        {
            string path        = OriPath + "\\test.jpg";
            string pathoutput2 = OriPath + "\\testoutput2.jpg";
            string pathoutput3 = OriPath + "\\testoutput3.jpg";
            string pathoutput4 = OriPath + "\\testoutput4.jpg";
            string pathoutput5 = OriPath + "\\testoutput5.jpg";
            string pathoutput6 = OriPath + "\\testoutput6.jpg";
            string pathoutput7 = OriPath + "\\testoutput7.jpg";


            Bitmap image = new Bitmap(path);

            // 普通最近领算法
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(4000, 3000);
            // 双线性插值
            ResizeBicubic filter2 = new ResizeBicubic(4000, 3000);
            // 双三次插值
            ResizeBilinear filter3 = new ResizeBilinear(4000, 3000);

            // create filter - rotate for 30 degrees keeping original image size
            RotateNearestNeighbor filter4 = new RotateNearestNeighbor(30, true);

            RotateBilinear filter5 = new RotateBilinear(30, true);

            RotateBicubic filter6 = new RotateBicubic(30, true);

            // apply the filter
            Bitmap newImage = filter.Apply(image);

            newImage.Save(pathoutput2);

            newImage = filter2.Apply(image);
            newImage.Save(pathoutput3);

            newImage = filter3.Apply(image);
            newImage.Save(pathoutput4);

            newImage = filter4.Apply(image);
            newImage.Save(pathoutput5);

            newImage = filter5.Apply(image);
            newImage.Save(pathoutput6);

            newImage = filter6.Apply(image);
            newImage.Save(pathoutput7);
        }
        public static BitmapSheet FromImage(string path, int scale, int pieceScale, int pieceSize, bool saveSheet, bool savePieces = false, bool animated = false)
        {
            var bs = new BitmapSheet {
                Bitmaps = new Dictionary <ushort, Bitmap>()
            };

            var bitmap      = AImage.FromFile(path);
            var totalBitmap = new Bitmap(bitmap.Width * scale, bitmap.Height * scale);

            var index = 0;

            for (var y = 0; y < bitmap.Height; y += pieceSize)
            {
                for (var x = 0; x < bitmap.Width; x += pieceSize)
                {
                    var crop  = new Crop(new Rectangle(x, y, pieceSize, pieceSize));
                    var piece = crop.Apply(bitmap);

                    var resizeW = System.Math.Min(32, pieceSize * 4);
                    var resizeH = System.Math.Min(32, pieceSize * 4);
                    var outW    = System.Math.Min(40, pieceSize * 5);
                    var outH    = System.Math.Min(40, pieceSize * 5);

                    var resize = new ResizeNearestNeighbor(resizeW, resizeH);
                    piece = resize.Apply(piece);

                    var outBitmap = new Bitmap(outW, outH);
                    outBitmap.Add(piece);

                    outBitmap = outBitmap.OutlineGlow(0, 0, .8, 1.4, 10);
                    if (savePieces)
                    {
                        outBitmap.Save($"{path} - 0x{index:x2}.png", ImageFormat.Png);
                    }

                    totalBitmap.Add(outBitmap, x * 5, y * 5);
                    bs.Bitmaps.Add((ushort)index, outBitmap);
                    index++;
                }
            }
            if (saveSheet)
            {
                totalBitmap.SavePng($"{path} - {(int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds}.png");
            }

            return(bs);
        }
Esempio n. 20
0
        private void Stream_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            int x, y;

            //gets the current size of the output image so the stream can be resized correctly
            x = imgOutput.Size.Width;
            y = imgOutput.Size.Height;

            Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();

            //resizing Image
            ResizeNearestNeighbor filter = new ResizeNearestNeighbor(x, y);
            Bitmap resizedImage          = filter.Apply(bmp);

            //sets the output image to the before rezized image
            imgOutput.Image = resizedImage;
        }
Esempio n. 21
0
        public AForge.Imaging.UnmanagedImage GetInput(out double[] input, int countBlocks = 100)
        {
            double toDbl(Color c)
            {
                var s = c.A + c.B + c.G;

                return(s > 50 ? 1 : 0);
            }

            input = new double[countBlocks * countBlocks + 1];
            AForge.Imaging.UnmanagedImage img;
            var    filter = new ResizeNearestNeighbor(countBlocks, countBlocks);
            double angle;

            lock (balanceLock)
            {
                angle = AngleRad;
                img   = filter.Apply(processed);
            }

            double max_input = 0;

            for (int i = 0; i < countBlocks; i++)
            {
                for (int j = 0; j < countBlocks; j++)
                {
                    var d = toDbl(img.GetPixel(i, j));
                    input[i * countBlocks + j] = d;
                    if (d > max_input)
                    {
                        max_input = d;
                    }
                }
            }
            if (max_input != 0)
            {
                for (int i = 0; i < input.Length - 1; i++)
                {
                    input[i] /= max_input;
                }
            }
            input[countBlocks * countBlocks] = AngleRad / Math.PI / 2.0;
            return(img);
        }
        public Contour Extract(UnmanagedImage blob)
        {
            switch (Method)
            {
            case PreprocessMethod.ExtendAndDilatation:
                // extend with 1px indention
                UnmanagedImage preprocessed = UnmanagedImage.Create(blob.Width + 2, blob.Height + 2, blob.PixelFormat);
                blob.CopyWithOffset(preprocessed, new IntPoint(1, 1));

                // dilatation
                m_dilatation.ApplyInPlace(preprocessed);

                // delete internal pixels
                m_deleteInternal.ApplyInPlace(preprocessed);

                // trace edge
                return(m_edgeTracer.Extract(preprocessed));

            case PreprocessMethod.Scale:
                int scaleMultiplier = 3;
                m_resizer.NewHeight = blob.Height * scaleMultiplier;
                m_resizer.NewWidth  = blob.Width * scaleMultiplier;

                // scale blob
                UnmanagedImage resized = m_resizer.Apply(blob);

                // delete internal pixels
                m_deleteInternal.ApplyInPlace(resized);

                // trace edge
                return(m_edgeTracer.Extract(resized));

            case PreprocessMethod.None:
                // delete internal pixels
                m_deleteInternal.ApplyInPlace(blob);

                // trace edge
                return(m_edgeTracer.Extract(blob));

            default:
                throw new Exception();
            }
        }
Esempio n. 23
0
        public Bitmap ProcessFrame(Bitmap inputBitmap, int x, int y)
        {
            // Create an image for AForge to process
            Bitmap workingImage = new Bitmap(inputBitmap.Width, inputBitmap.Height);

            workingImage = AForge.Imaging.Image.Clone(inputBitmap, PixelFormat.Format24bppRgb);

            // Create a mask for ROI selection
            Rectangle roi = new Rectangle(x - 30, y - 30, 80, 80);

            Crop   roicrop  = new Crop(roi);
            Bitmap outimage = roicrop.Apply(workingImage);

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ObjectsOrder = ObjectsOrder.Area;

            Blob[] blobs;

            // Find the blobs
            blobCounter.ProcessImage(outimage);
            blobs = blobCounter.GetObjectsInformation();
            List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[0]);

            GrahamConvexHull grahamScan = new GrahamConvexHull();
            List <IntPoint>  hullPoints = grahamScan.FindHull(edgePoints);

            Graphics g      = Graphics.FromImage(outimage);
            Pen      redPen = new Pen(Color.Red, 2);

            g.DrawPolygon(redPen, ToPointsArray(hullPoints));

            //g.Clear(Color.Black);
            //g.DrawImage(handImage, x, y);
            //g.DrawRectangle(redPen, roi);
            //g.DrawEllipse(redPen, x, y, 20, 20);

            ResizeNearestNeighbor resizeFilter = new ResizeNearestNeighbor(160, 160);
            Bitmap resizedImage = resizeFilter.Apply(outimage);

            return(resizedImage);
        }
Esempio n. 24
0
        private UnmanagedImage ZoomImage(UnmanagedImage lfu)
        {
            if (ZFactor > 1)
            {
                var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height);
                var f2 = new Crop(ViewRectangle);
                try
                {
                    lfu = f2.Apply(lfu);
                    lfu = f1.Apply(lfu);
                }
                catch (Exception ex)
                {
                    if (ErrorHandler != null)
                    {
                        ErrorHandler(ex.Message);
                    }
                }
            }

            return(lfu);
        }
Esempio n. 25
0
        public static Bitmap AForge_ResizeFast(this Bitmap source, int width, int height)
        {
            if (source.IsNullOrEmpty() || width <= 0 || height <= 0)
            {
                return(null);
            }

            if (source.Width == width && source.Height == height)
            {
                return(source.TryCopy());
            }

            try
            {
                ResizeNearestNeighbor filter = new ResizeNearestNeighbor(width, height);
                return(filter.Apply(source));
            }
            catch (Exception ex)
            {
                ex.WriteToExcpetionBuffer();
                return(null);
            }
        }
Esempio n. 26
0
        void myReader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            var reference = e.FrameReference.AcquireFrame();

            using (var frame = reference.ColorFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    var width  = frame.FrameDescription.Width;
                    var height = frame.FrameDescription.Height;
                    var data   = new byte[width * height * 32 / 8];
                    frame.CopyConvertedFrameDataToArray(data, ColorImageFormat.Bgra);

                    var bitmap     = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                    var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);


                    Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
                    bitmap.UnlockBits(bitmapData);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);

                    ColorFiltering       filter  = new ColorFiltering();
                    BrightnessCorrection filter2 = new BrightnessCorrection(+50);

                    ResizeNearestNeighbor filter3 = new ResizeNearestNeighbor(512, 424);
                    Bitmap newImage = filter3.Apply(bitmap);

                    filter.Red   = new AForge.IntRange(0, 255);
                    filter.Green = new AForge.IntRange(0, 75);
                    filter.Blue  = new AForge.IntRange(0, 75);
                    //filter2.ApplyInPlace(bitmap);
                    //filter.ApplyInPlace(bitmap);
                    pictureBox1.Image = newImage;
                }
            }
        }
Esempio n. 27
0
        public static Bitmap CaptureFromDisplay(ref ImageCaptureInfo info)
        {
            Bitmap b = new Bitmap((int)info.actual_crop_size_x, (int)info.actual_crop_size_y);

            //Full screen
            var watch = System.Diagnostics.Stopwatch.StartNew();

            using (Graphics g = Graphics.FromImage(b))
            {
                g.CopyFromScreen((int)(info.center_of_frame_x - info.actual_crop_size_x / 2 + info.actual_offset_x),
                                 (int)(info.center_of_frame_y - info.actual_crop_size_y / 2 + info.actual_offset_y), 0, 0, new Size((int)info.actual_crop_size_x, (int)info.actual_crop_size_y), CopyPixelOperation.SourceCopy);
            }

            if (b.Size.Width != info.featureSizeX && b.Size.Height != info.featureSizeY)
            {
                ResizeNearestNeighbor filter = new ResizeNearestNeighbor(info.featureSizeX, info.featureSizeY);
                b = filter.Apply(b);
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            return(b);
        }
Esempio n. 28
0
        private void VideoNewFrame(object sender, NewFrameEventArgs e)
        {
            var nf = NewFrame;
            var f  = e.Frame;

            if (_requestedToStop || nf == null || f == null)
            {
                return;
            }


            if (_lastframeEvent > DateTime.MinValue)
            {
                if ((Helper.Now < _nextFrameTarget))
                {
                    return;
                }
                CalculateFramerates();
            }

            _lastframeEvent = Helper.Now;

            if (_updateResources)
            {
                _updateResources = false;
                DrawFont.Dispose();
                DrawFont = null;
                ForeBrush.Dispose();
                ForeBrush = null;
                BackBrush.Dispose();
                BackBrush = null;
                SetMaskImage();
                RotateFlipType rft;
                if (Enum.TryParse(CW.Camobject.rotateMode, out rft))
                {
                    RotateFlipType = rft;
                }
                else
                {
                    RotateFlipType = RotateFlipType.RotateNoneFlipNone;
                }
            }


            Bitmap bmOrig  = null;
            bool   bMotion = false;

            lock (_sync)
            {
                try
                {
                    bmOrig = ResizeBmOrig(f);

                    if (RotateFlipType != RotateFlipType.RotateNoneFlipNone)
                    {
                        bmOrig.RotateFlip(RotateFlipType);
                    }

                    _width  = bmOrig.Width;
                    _height = bmOrig.Height;

                    if (ZPoint == Point.Empty)
                    {
                        ZPoint = new Point(bmOrig.Width / 2, bmOrig.Height / 2);
                    }

                    if (CW.NeedMotionZones)
                    {
                        CW.NeedMotionZones = !SetMotionZones(CW.Camobject.detector.motionzones);
                    }

                    if (Mask != null)
                    {
                        ApplyMask(bmOrig);
                    }

                    if (CW.Camobject.alerts.active && Plugin != null && Alarm != null)
                    {
                        bmOrig = RunPlugin(bmOrig);
                    }

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

                    //this converts the image into a windows displayable image so do it regardless
                    using (var lfu = new UnmanagedImage(bmd))
                    {
                        if (_motionDetector != null)
                        {
                            bMotion = ApplyMotionDetector(lfu);
                        }
                        else
                        {
                            MotionDetected = false;
                        }

                        if (CW.Camobject.settings.FishEyeCorrect)
                        {
                            _feCorrect.Correct(lfu, CW.Camobject.settings.FishEyeFocalLengthPX,
                                               CW.Camobject.settings.FishEyeLimit, CW.Camobject.settings.FishEyeScale, ZPoint.X,
                                               ZPoint.Y);
                        }

                        if (ZFactor > 1)
                        {
                            var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height);
                            var f2 = new Crop(ViewRectangle);
                            try
                            {
                                using (var imgTemp = f2.Apply(lfu))
                                {
                                    f1.Apply(imgTemp, lfu);
                                }
                            }
                            catch (Exception ex)
                            {
                                ErrorHandler?.Invoke(ex.Message);
                            }
                        }
                    }
                    bmOrig.UnlockBits(bmd);
                    PiP(bmOrig);
                    AddTimestamp(bmOrig);
                }
                catch (UnsupportedImageFormatException ex)
                {
                    CW.VideoSourceErrorState   = true;
                    CW.VideoSourceErrorMessage = ex.Message;

                    bmOrig?.Dispose();

                    return;
                }
                catch (Exception ex)
                {
                    bmOrig?.Dispose();

                    ErrorHandler?.Invoke(ex.Message);

                    return;
                }


                if (MotionDetector != null && !CW.Calibrating && MotionDetector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing && !CW.PTZNavigate && CW.Camobject.settings.ptzautotrack)
                {
                    try
                    {
                        ProcessAutoTracking();
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler?.Invoke(ex.Message);
                    }
                }
            }

            if (!_requestedToStop)
            {
                nf.Invoke(this, new NewFrameEventArgs(bmOrig));
            }
            if (bMotion)
            {
                TriggerDetect(this);
            }
        }
Esempio n. 29
0
        // New frame received by the player
        private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
        {
            if (!detecting && !tracking)
            {
                return;
            }

            lock (this)
            {
                if (detecting)
                {
                    detecting = false;
                    tracking  = false;

                    UnmanagedImage im = UnmanagedImage.FromManagedImage(image);

                    float xscale = image.Width / 160f;
                    float yscale = image.Height / 120f;

                    ResizeNearestNeighbor resize     = new ResizeNearestNeighbor(160, 120);
                    UnmanagedImage        downsample = resize.Apply(im);

                    Rectangle[] regions = detector.ProcessFrame(downsample);

                    if (regions.Length > 0)
                    {
                        tracker.Reset();

                        // Will track the first face found
                        Rectangle face = regions[0];

                        // Reduce the face size to avoid tracking background
                        Rectangle window = new Rectangle(
                            (int)((regions[0].X + regions[0].Width / 2f) * xscale),
                            (int)((regions[0].Y + regions[0].Height / 2f) * yscale),
                            1, 1);

                        window.Inflate(
                            (int)(0.2f * regions[0].Width * xscale),
                            (int)(0.4f * regions[0].Height * yscale));

                        // Initialize tracker
                        tracker.SearchWindow = window;
                        tracker.ProcessFrame(im);

                        marker = new RectanglesMarker(window);
                        marker.ApplyInPlace(im);

                        image = im.ToManagedImage();

                        tracking = true;
                        //detecting = true;
                    }
                    else
                    {
                        detecting = true;
                    }
                }
                else if (tracking)
                {
                    UnmanagedImage im = UnmanagedImage.FromManagedImage(image);

                    // Track the object
                    tracker.ProcessFrame(im);

                    // Get the object position
                    var obj = tracker.TrackingObject;
                    var wnd = tracker.SearchWindow;

                    if (displayBackprojectionToolStripMenuItem.Checked)
                    {
                        var backprojection = tracker.GetBackprojection(PixelFormat.Format24bppRgb);
                        im = UnmanagedImage.FromManagedImage(backprojection);
                    }

                    if (drawObjectAxisToolStripMenuItem.Checked)
                    {
                        LineSegment axis = obj.GetAxis();

                        // Draw X axis
                        Drawing.Line(im, axis.Start.Round(), axis.End.Round(), Color.Red);
                    }


                    if (drawObjectBoxToolStripMenuItem.Checked && drawTrackingWindowToolStripMenuItem.Checked)
                    {
                        marker = new RectanglesMarker(new Rectangle[] { wnd, obj.Rectangle });
                    }
                    else if (drawObjectBoxToolStripMenuItem.Checked)
                    {
                        //InteractionPoints p = new InteractionPoints();
                        //p.setHead(obj.Rectangle);

                        marker = new RectanglesMarker(obj.Rectangle);
                    }
                    else if (drawTrackingWindowToolStripMenuItem.Checked)
                    {
                        marker = new RectanglesMarker(wnd);
                    }
                    else
                    {
                        marker = null;
                    }


                    if (marker != null)
                    {
                        marker.ApplyInPlace(im);
                    }
                    image = im.ToManagedImage();
                }
                else
                {
                    if (marker != null)
                    {
                        image = marker.Apply(image);
                    }
                }
            }
        }
        // New frame received by the player
        private void videoSourcePlayer_NewFrame(object sender, NewFrameEventArgs args)
        {
            var direccion      = "Centro";
            int direccionServo = 2;

            if (!detecting && !tracking)
            {
                return;
            }

            lock (this)
            {
                if (detecting)
                {
                    detecting = false;
                    tracking  = false;

                    UnmanagedImage im = UnmanagedImage.FromManagedImage(args.Frame);

                    float xscale = im.Width / 160f;
                    float yscale = im.Height / 120f;

                    ResizeNearestNeighbor resize     = new ResizeNearestNeighbor(160, 120);
                    UnmanagedImage        downsample = resize.Apply(im);

                    Rectangle[] regions = detector.ProcessFrame(downsample);

                    if (regions.Length > 0)
                    {
                        tracker.Reset();

                        // Will track the first face found
                        Rectangle face = regions[0];

                        // Reduce the face size to avoid tracking background
                        Rectangle window = new Rectangle(
                            (int)((regions[0].X + regions[0].Width / 2f) * xscale),
                            (int)((regions[0].Y + regions[0].Height / 2f) * yscale),
                            1, 1);
                        Console.Write("x:" + (int)((regions[0].X + regions[0].Width / 2f) * xscale));
                        Console.Write("y:" + (int)((regions[0].X + regions[0].Height / 2f) * xscale));
                        window.Inflate(
                            (int)(0.2f * regions[0].Width * xscale),
                            (int)(0.4f * regions[0].Height * yscale));

                        // Initialize tracker
                        tracker.SearchWindow = window;
                        tracker.ProcessFrame(im);

                        marker = new RectanglesMarker(window);
                        marker.ApplyInPlace(im);

                        args.Frame = im.ToManagedImage();

                        tracking = true;
                        //detecting = true;
                    }
                    else
                    {
                        detecting = true;
                    }
                }
                else if (tracking)
                {
                    UnmanagedImage im = UnmanagedImage.FromManagedImage(args.Frame);

                    // Track the object
                    tracker.ProcessFrame(im);

                    // Get the object position
                    var obj = tracker.TrackingObject;
                    var wnd = tracker.SearchWindow;

                    //if (displayBackprojectionToolStripMenuItem.Checked)
                    //{
                    //    var backprojection = tracker.GetBackprojection(PixelFormat.Format24bppRgb);
                    //    im = UnmanagedImage.FromManagedImage(backprojection);
                    //}

                    //if (drawObjectAxisToolStripMenuItem.Checked)
                    //{
                    //    LineSegment axis = obj.GetAxis();

                    //    // Draw X axis
                    //    if (axis != null)
                    //        Drawing.Line(im, axis.Start.Round(), axis.End.Round(), Color.Red);
                    //    else detecting = true;
                    //}
                    if (obj.Rectangle.Width < (args.Frame.Width / 3) * 2)
                    {
                        if (obj.Rectangle.X < args.Frame.Width / 3)
                        {
                            direccion      = "Izquierda";
                            direccionServo = 1;
                        }
                        else if (obj.Rectangle.X > (args.Frame.Width / 3) * 2)
                        {
                            direccion      = "Derecha";
                            direccionServo = 3;
                        }
                    }
                    try
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            if (textBox1 != null)
                            {
                                textBox1.Text = obj.Rectangle.X.ToString();
                                textBox2.Text = obj.Rectangle.Y.ToString();
                                label1.Text   = direccion;
                            }
                        });
                        ComunicacionPuertoSerie.Instance.enviarEvento(direccionServo.ToString());
                    }
                    catch (Exception e) { }
                    if (/*drawObjectBoxToolStripMenuItem.Checked && drawTrackingWindowToolStripMenuItem.Checked*/ false)
                    {
                        marker = new RectanglesMarker(new Rectangle[] { wnd, obj.Rectangle });
                    }
                    else if (/*drawObjectBoxToolStripMenuItem.Checked*/ true)
                    {
                        marker = new RectanglesMarker(obj.Rectangle);
                    }
                    else if (/*drawTrackingWindowToolStripMenuItem.Checked*/ true)
                    {
                        marker = new RectanglesMarker(wnd);
                    }
                    else
                    {
                        marker = null;
                    }


                    if (marker != null)
                    {
                        marker.ApplyInPlace(im);
                    }
                    args.Frame = im.ToManagedImage();
                }
                else
                {
                    if (marker != null)
                    {
                        args.Frame = marker.Apply(args.Frame);
                    }
                }
            }
        }
Esempio n. 31
0
        // New frame received by the player
        private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
        {
            if (!detecting && !tracking)
                return;

            lock (this)
            {
                if (detecting)
                {
                    detecting = false;
                    tracking = false;

                    UnmanagedImage im = UnmanagedImage.FromManagedImage(image);

                    float xscale = image.Width / 160f;
                    float yscale = image.Height / 120f;

                    ResizeNearestNeighbor resize = new ResizeNearestNeighbor(160, 120);
                    UnmanagedImage downsample = resize.Apply(im);

                    Rectangle[] regions = detector.ProcessFrame(downsample);

                    if (regions.Length > 0)
                    {
                        tracker.Reset();

                        // Will track the first face found
                        Rectangle face = regions[0];

                        // Reduce the face size to avoid tracking background
                        Rectangle window = new Rectangle(
                            (int)((regions[0].X + regions[0].Width / 2f) * xscale),
                            (int)((regions[0].Y + regions[0].Height / 2f) * yscale),
                            1, 1);

                        window.Inflate(
                            (int)(0.2f * regions[0].Width * xscale),
                            (int)(0.4f * regions[0].Height * yscale));

                        // Initialize tracker
                        tracker.SearchWindow = window;
                        tracker.ProcessFrame(im);

                        marker = new RectanglesMarker(window);
                        marker.ApplyInPlace(im);

                        image = im.ToManagedImage();

                        tracking = true;
                        //detecting = true;
                    }
                    else
                    {
                        detecting = true;
                    }
                }
                else if (tracking)
                {
                    UnmanagedImage im = UnmanagedImage.FromManagedImage(image);

                    // Track the object
                    tracker.ProcessFrame(im);

                    // Get the object position
                    var obj = tracker.TrackingObject;
                    var wnd = tracker.SearchWindow;

                    if (displayBackprojectionToolStripMenuItem.Checked)
                    {
                        var backprojection = tracker.GetBackprojection(PixelFormat.Format24bppRgb);
                        im = UnmanagedImage.FromManagedImage(backprojection);
                    }

                    if (drawObjectAxisToolStripMenuItem.Checked)
                    {
                        LineSegment axis = obj.GetAxis();

                        // Draw X axis
                        Drawing.Line(im, axis.Start.Round(), axis.End.Round(), Color.Red);
                    }

                    if (drawObjectBoxToolStripMenuItem.Checked && drawTrackingWindowToolStripMenuItem.Checked)
                    {
                        marker = new RectanglesMarker(new Rectangle[] { wnd, obj.Rectangle });
                    }
                    else if (drawObjectBoxToolStripMenuItem.Checked)
                    {
                        //InteractionPoints p = new InteractionPoints();
                        //p.setHead(obj.Rectangle);

                        marker = new RectanglesMarker(obj.Rectangle);
                    }
                    else if (drawTrackingWindowToolStripMenuItem.Checked)
                    {
                        marker = new RectanglesMarker(wnd);
                    }
                    else
                    {
                        marker = null;
                    }

                    if (marker != null)
                        marker.ApplyInPlace(im);
                    image = im.ToManagedImage();
                }
                else
                {
                    if (marker != null)
                        image = marker.Apply(image);
                }

            }
        }
Esempio n. 32
0
		/// <summary>
		/// Detects face regions and creates trackers
		/// </summary>
		/// <param name="image">Image to search for faces on</param>
		private async void DetectFacesAsync(UnmanagedImage image) {
			if (this.detector == null)
				throw new NullReferenceException("Initialize provider first! detector is null");

			var sw = new System.Diagnostics.Stopwatch();
			sw.Start();
			this.isDetectingInProgress = true;

			double xScale = image.Width / this.DetectingFrameWidthDefault;
			double yScale = image.Height / this.DetectingFrameHeightDefault;

			// Resize image (downsample)
			var resize = new ResizeNearestNeighbor((int) this.DetectingFrameWidthDefault,
												   (int) this.DetectingFrameHeightDefault);
			UnmanagedImage downsampledImage = resize.Apply(image);

			// Get detector regions
			var regions = new Rectangle[0];
			await Task.Run(() => regions = detector.ProcessFrame(downsampledImage));

			// Check if the face has been steady for 5 frames in a row
			if (this.detector.Steady > 5) {
				// Create face tracker for each of detected regions
				foreach (var region in regions) {
					this.CreateFaceTracker(region, xScale, yScale, image);
				}
			}

			this.isDetectingInProgress = false;
			sw.Stop();
			this.log.Info("\n{0} faces detected in {1}ms",
						  regions.Length, sw.ElapsedMilliseconds);
		}
Esempio n. 33
0
        private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand)
        {
            Crop c = new Crop(rect);
            var handImage = c.Apply(mask);

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

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

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


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


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

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

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

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

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

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

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

                    pbHand.Image = leftHand;
                }
            }
        }