Esempio n. 1
0
        public void resize_bicubic()
        {
            double[,] diag = Matrix.Magic(5);
            diag           = diag.Divide(diag.Max());

            Bitmap input = diag.ToBitmap();

            // Create a new resize bilinear filter
            var filter = new ResizeBicubic(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.725490196078431, 0.780392156862745,                 1, 0.352941176470588, 0.0313725490196078, 0.341176470588235, 0.588235294117647 },
                { 0.733333333333333, 0.749019607843137, 0.909803921568627, 0.313725490196078, 0.0745098039215686, 0.352941176470588,  0.56078431372549 },
                {                 1, 0.827450980392157, 0.376470588235294, 0.211764705882353,  0.286274509803922, 0.501960784313725, 0.596078431372549 },
                { 0.733333333333333, 0.568627450980392,  0.16078431372549, 0.250980392156863,  0.470588235294118, 0.666666666666667, 0.745098039215686 },
                {  0.16078431372549, 0.164705882352941, 0.223529411764706, 0.407843137254902,  0.623529411764706, 0.811764705882353, 0.866666666666667 },
                { 0.290196078431373, 0.290196078431373, 0.364705882352941,  0.56078431372549,  0.780392156862745, 0.874509803921569, 0.462745098039216 },
                { 0.443137254901961,  0.43921568627451, 0.529411764705882, 0.745098039215686,  0.819607843137255, 0.654901960784314, 0.203921568627451 },
                { 0.447058823529412, 0.474509803921569,  0.67843137254902,  0.96078431372549,   0.72156862745098,  0.12156862745098, 0.282352941176471 }
            };

            Assert.IsTrue(expected.IsEqual(actual, 1e-6));
        }
 private static Bitmap CreateGrayscale(Bitmap image)
 {
     
     const int size = 512;
     float scale = Math.Min(size / (float)image.Width, size / (float)image.Height);
     ResizeBicubic resize = new ResizeBicubic((int)(image.Width*scale), (int)(image.Height*scale));
     
     ImageStatistics stat = new ImageStatistics( image );
     LevelsLinear levelsLinear = new LevelsLinear
     {
         Output = new IntRange(0, 255),
         InRed = stat.Red.GetRange(.95),
         InBlue = stat.Blue.GetRange(.95),
         InGreen = stat.Green.GetRange(.95)
     };
     SaturationCorrection sc = new SaturationCorrection(-1);
     Bitmap square = new Bitmap(size, size);
     using(Bitmap resized = resize.Apply(sc.Apply(levelsLinear.Apply(image)).MakeGrayscale()))
     using (Graphics g = Graphics.FromImage(square))
     {
         g.DrawImage(resized, new Point((size-resized.Width) / 2 ,0));
     }
     
     return square;
 }
Esempio n. 3
0
        public static Bitmap ResizeImage(this Bitmap originalImage, int newWidth, int newHeight)
        {
            double aspectRatio;
            int    calculatedWidth, calculatedHeight;

            if (originalImage.Width > originalImage.Height)
            {
                calculatedWidth  = newWidth;
                aspectRatio      = (float)newWidth / originalImage.Width;
                calculatedHeight = Convert.ToInt32(originalImage.Height * aspectRatio);
            }
            else
            {
                calculatedHeight = newHeight;
                aspectRatio      = (float)newHeight / originalImage.Height;
                calculatedWidth  = Convert.ToInt32(originalImage.Width * aspectRatio);
            }

            if (originalImage.Width <= calculatedWidth || originalImage.Height <= calculatedHeight)
            {
                calculatedHeight = originalImage.Height;
                calculatedWidth  = originalImage.Width;
            }

            var    resizeFilter = new ResizeBicubic(calculatedWidth, calculatedHeight);
            Bitmap result       = resizeFilter.Apply(originalImage);

            return(result);
        }
Esempio n. 4
0
        public Bitmap ReescaladoBicubico(int anchura, int altura)
        {
            ResizeBicubic resize = new ResizeBicubic(anchura, altura);

            imagen = resize.Apply(imagen);
            return(imagen);
        }
Esempio n. 5
0
        private Bitmap preProcess(Bitmap originalImage)
        {
            Invert invertObj   = new Invert();
            Bitmap invertImage = invertObj.Apply((Bitmap)originalImage.Clone());


            invertImage = Grayscale.CommonAlgorithms.BT709.Apply(invertImage);
            Threshold bwObject = new Threshold();

            invertImage = bwObject.Apply(invertImage);

            ExtractBiggestBlob blobObject = new ExtractBiggestBlob();

            invertImage = blobObject.Apply(invertImage);

            ResizeBicubic resize = new ResizeBicubic(60, 90);

            invertImage = resize.Apply(invertImage);


            //CannyEdgeDetector edgeDetector = new CannyEdgeDetector();
            //invertImage = edgeDetector.Apply(invertImage);

            return(invertImage);
        }
        /// <summary>
        /// 将图片大小标准化(4M限制)
        /// </summary>
        /// <param name="image"></param>
        /// <param name="width">压缩目标宽,会按原比例缩放</param>
        /// <param name="height">压缩目标高,会按原比例缩放</param>
        /// <returns></returns>
        public static Bitmap miniSizeImage(System.Drawing.Image image, int width, int height)
        {
            int _height = 0;
            int _width  = 0;

            //height much bigger , so height is the max number of size
            if (image.Size.Height > image.Size.Width)
            {
                _height = height;
                _width  = (int)((double)image.Size.Width / image.Size.Height * height);
            }
            else
            {
                _height = (int)((double)image.Size.Height / image.Size.Width * width);
                _width  = width;
            };
            ResizeBicubic filter = new ResizeBicubic(_width, _height);

            // apply the filter
            try
            {
                return(filter.Apply(image as Bitmap));
            }
            catch (Exception ex)
            {
                return(image as Bitmap);
            }
        }
Esempio n. 7
0
        private void CameraOne_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap    bitmap1 = (Bitmap)(eventArgs.Frame.DeepClone());
            Grayscale filter  = new Grayscale(0.2, 0.7, 0.07);

            if (checkBox1.Checked)
            {
                bitmap1 = filter.Apply(bitmap1);
            }
            int x = 0;

            Invoke(new MethodInvoker(delegate
            {
                x = trackBar1.Value;
            }));
            RotateNearestNeighbor filterrot = new RotateNearestNeighbor(x, true);

            bitmap1 = filterrot.Apply(bitmap1);
            ResizeBicubic filterResizeBicubic = new ResizeBicubic(320, 240);

            bitmap1 = filterResizeBicubic.Apply(bitmap1);
            if (button1WasClicked)
            {
                Convolution conv = new Convolution(new[, ]
                {
                    { int.Parse(textBox1.Text), int.Parse(textBox2.Text), int.Parse(textBox3.Text) },
                    { int.Parse(textBox4.Text), int.Parse(textBox5.Text), int.Parse(textBox6.Text) },
                    { int.Parse(textBox7.Text), int.Parse(textBox8.Text), int.Parse(textBox9.Text) }
                });
                bitmap1 = conv.Apply(bitmap1);
            }
            pictureBox1.Image = bitmap1;
        }
Esempio n. 8
0
        public Bitmap GenerateThumb(int width)
        {
            int           height       = Convert.ToInt32(Convert.ToDouble(this.ComicImage.Height) / Convert.ToDouble(this.ComicImage.Width) * Convert.ToDouble(width));
            ResizeBicubic filterResize = new ResizeBicubic(width, height);

            return(filterResize.Apply(this.ComicImage));
        }
Esempio n. 9
0
        public static Bitmap FitImage(Size targetSize, Bitmap inputBitmap)
        {
            Size resize = GetFitImageSize(new Size(inputBitmap.Width, inputBitmap.Height), targetSize);

            ResizeBicubic filterResize = new ResizeBicubic(resize.Width, resize.Height);

            return(filterResize.Apply(inputBitmap));
        }
Esempio n. 10
0
        public static Bitmap Zoom(Bitmap image, double zoomPercentage)
        {
            int           newWidth  = (int)Math.Floor(image.Width * zoomPercentage);
            int           newHeight = (int)Math.Floor(image.Height * zoomPercentage);
            ResizeBicubic resizer   = new ResizeBicubic(newWidth, newHeight);

            return(resizer.Apply(image));
        }
Esempio n. 11
0
        void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            ResizeBicubic filter   = new ResizeBicubic(328, 275);
            Bitmap        newImage = filter.Apply((Bitmap)eventArgs.Frame.Clone());

            pictureBox1.Image = newImage;
            //pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
        }
Esempio n. 12
0
        public AForge.Imaging.UnmanagedImage GetImage()
        {
            ResizeBicubic resize = new ResizeBicubic(28, 28);

            lock (balanceLock)
            {
                return(resize.Apply(processed));
            }
        }
        private static Bitmap Resizeimage(Bitmap image, int NewWidth, int NewHeight)
        {
            //set up filter
            ResizeBicubic ResizeFilter = new ResizeBicubic(NewWidth, NewHeight);

            //apply filter
            image = ResizeFilter.Apply(image);
            return(image);
        }
        //scale bicubic
        private static Bitmap Scale(Bitmap image)
        {
            IRandomNumberGenerator generator = new GaussianGenerator(1.05f, 0.1f);

            ResizeBicubic filter = new ResizeBicubic((int)(image.Width * 1.035), (int)(image.Height * 1.035));

            // apply the filter
            return(filter.Apply(image));
        }
Esempio n. 15
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. 16
0
        public AForge.Imaging.UnmanagedImage  GetInput(out double[] input, int countBlocks = 100)
        {
            double toDbl(Color c)
            {
                var s = c.R + c.B + c.G;

                if (s > 50)
                {
                    return(1.0);
                }
                return(-1);
            }

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

            lock (balanceLock)
            {
                angle = AngleRad;
                if (processed.Height == countBlocks && processed.Width == countBlocks)
                {
                    img = processed.Clone();
                }
                else
                {
                    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);
        }
Esempio n. 17
0
        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = FilterResize.Apply((Bitmap)eventArgs.Frame.Clone());

            pictureBox1.Image = (Bitmap)img.Clone();

            Grayscale FilterGrayscale = new Grayscale(red, green, blue);

            img = FilterGrayscale.Apply((Bitmap)img.Clone());

            pictureBox2.Image = (Bitmap)img.Clone();

            SobelEdgeDetector FilterSobelEdgeDetector = new SobelEdgeDetector();

            img = FilterSobelEdgeDetector.Apply((Bitmap)img.Clone());

            pictureBox3.Image = (Bitmap)img.Clone();
            pictureBox5.Image = (Bitmap)img.Clone();
            pictureBox8.Image = (Bitmap)img.Clone();

            if (mutex)
            {
                gest  = (Bitmap)img.Clone();
                mutex = false;
                pictureBox11.Image = (Bitmap)gest.Clone();
            }

            float sim = 0;

            ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.5f);

            TemplateMatch[] matchings;

            Bitmap overlay = (Bitmap)img.Clone();

            Add AddFilter = new Add(overlay);

            if (gest != null)
            {
                overlay = AddFilter.Apply((Bitmap)gest.Clone());
            }

            pictureBox9.Image = (Bitmap)overlay.Clone();

            matchings = tm.ProcessImage(img, overlay);
            if (matchings.Length > 0)
            {
                sim = matchings[0].Similarity;
            }

            this.label4.BeginInvoke((MethodInvoker)(() => this.label4.Text = Convert.ToString(sim)));
        }
Esempio n. 18
0
 private void finalFrameEvent(Object sender, NewFrameEventArgs nfea)
 {
     try
     {
         ResizeBicubic filter = new ResizeBicubic(pboReader.Width, pboReader.Height);
         pboReader.Image = filter.Apply((Bitmap)nfea.Frame.Clone());
     }
     catch (Exception ex)
     {
         Integrity.GetExceptionDetails(ex);
         this.CloseCam();
     }
 }
        public Bitmap Filter(Bitmap input_image)
        {
            Grayscale gray_filter = new Grayscale(0.2125, 0.7154, 0.0721);
            BradleyLocalThresholding threshold_filter = new BradleyLocalThresholding();

            threshold_filter.PixelBrightnessDifferenceLimit = 0.5f;
            ResizeBicubic scale_small_filter = new ResizeBicubic(28, 28);
            Crop          crop_filter        = new Crop(new Rectangle(51, 51, 199, 199));


            BlobCounter blober = new BlobCounter();

            blober.FilterBlobs  = true;
            blober.ObjectsOrder = ObjectsOrder.Size;

            Bitmap image = gray_filter.Apply(input_image);

            image = threshold_filter.Apply(image);

            image = crop_filter.Apply(image);
            //blober.ProcessImage(image);

            //Blob[] blobs = blober.GetObjectsInformation();
            //if (blobs.Length > 0)
            //{
            //    var bigger = blobs[0];
            //    UnmanagedImage img = UnmanagedImage.FromManagedImage(image);
            //    blober.ExtractBlobsImage(img, bigger, false);
            //    Accord.Point mc = bigger.CenterOfGravity;
            //    Accord.Point ic = new Accord.Point((float)bigger.Image.Width / 2, (float)bigger.Image.Height / 2);


            //    float AngleRad = (ic.Y - mc.Y) / (ic.X - mc.X);
            //    float Angle = (float)(AngleRad * 180 / Math.PI);

            //    image = img.ToManagedImage();



            //    RotateBicubic rot_filter = new RotateBicubic(Angle);
            //    image = rot_filter.Apply(image);
            //}


            image = scale_small_filter.Apply(image);



            return(image);
        }
Esempio n. 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        private Image ResizeImage(Image image, int newSize)
        {
            float largeSize = Math.Max(image.Width, image.Height);
            float factor    = (float)newSize / largeSize;

            ResizeBicubic filter = new ResizeBicubic((int)Math.Round(image.Width * factor), (int)Math.Round(image.Height * factor));
            Image         dst    = filter.Apply(image as Bitmap);

            foreach (PropertyItem item in image.PropertyItems)
            {
                dst.SetPropertyItem(item);
            }
            return(dst);
        }
Esempio n. 21
0
        private void button_catch_Click(object sender, EventArgs e)
        {
            Bitmap        input_image  = pictureBox1.Image as Bitmap;
            ResizeBicubic scale_filter = new ResizeBicubic(pictureBox2.Width, pictureBox2.Height);

            image = net.Filter(input_image);

            pictureBox3.Image = image;
            pictureBox3.Refresh();

            Bitmap bigger_image = scale_filter.Apply(image);

            pictureBox2.Image = bigger_image;
            pictureBox2.Refresh();
        }
Esempio n. 22
0
        private void WindowsUIButton_Capture_Click(object sender, EventArgs e)
        {
            if (this.videoSourcePlayer.VideoSource == null)
            {
                return;
            }

            Bitmap frame = this.videoSourcePlayer.GetCurrentVideoFrame();

            if (frame == null)
            {
                return;
            }

            string code      = this.Message.Split(new string[] { " " }, StringSplitOptions.None)[0];
            string file_name = "data\\photo\\" + code + ".jpg";

            try
            {
                // clip
                Bitmap gray = null;
                if (!Accord.Imaging.Image.IsGrayscale(frame))
                {
                    gray = Accord.Imaging.Filters.Grayscale.CommonAlgorithms.BT709.Apply(frame);
                }

                List <Rectangle> ff = this.detector.FastDetect(gray);
                if (ff.Count > 0)
                {
                    Bitmap bmp = frame.Clone(this.EnlargeBoundingBox(this.GetPrimaryFace(ff), frame.Size), frame.PixelFormat);
                    // resize
                    Accord.Imaging.Filters.ResizeBicubic resizer = new ResizeBicubic(800, 800);
                    bmp = resizer.Apply(bmp);
                    bmp.Save(file_name, System.Drawing.Imaging.ImageFormat.Jpeg);

                    this.BindPhoto();


                    // save to database
                    Repository.SimpleDBHelper.RegisterAsPhoto(code, file_name);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("保存失败,请重试" + ex.Message);
            }
        }
Esempio n. 23
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);
        }
Esempio n. 24
0
        /// <summary>getFrame from the videosource</summary>
        private void nextFrame(object sender, NewFrameEventArgs eventArgs)
        {
            //Get New Frame
            Bitmap bitmap    = eventArgs.Frame;
            Bitmap lastFrame = (Bitmap)bitmap.Clone();

            //Update Preview Window
            MemoryStream ms = new MemoryStream();

            bitmap.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);
            BitmapImage bi = new BitmapImage();

            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();
            bi.Freeze();

            Dispatcher.BeginInvoke(new Action(() => {
                cameraPreview.Source = bi;
            }));

            //Camera window needs to be visible
            if (this.cameraWindow.Visibility != Visibility.Collapsed)
            {
                //Don't check more than every 10 seconds
                if (DateTime.Now.Subtract(lastCheck).TotalSeconds > 10)
                {
                    //Only continue if there is no processing happening in the background
                    if (!working)
                    {
                        //We can now process a frame
                        //Set flags
                        lastCheck = DateTime.Now;
                        working   = true;

                        //Resize Frame
                        ResizeBicubic resize  = new ResizeBicubic(lastFrame.Width / 2, lastFrame.Height / 2);
                        Bitmap        resized = resize.Apply(lastFrame);

                        //Process image
                        processImage(resized);
                    }
                }
            }
        }
Esempio n. 25
0
        private void OpenPictureButton_Click(object sender, EventArgs e)
        {
            StopVideoCaptureDevice();

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "Image Files (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Bitmap managedImage = (Bitmap)Bitmap.FromFile(ofd.FileName);

                ResizeBicubic resizer = new ResizeBicubic(m_frameSize.Width, m_frameSize.Height);
                Bitmap        resized = resizer.Apply(managedImage);

                NewFrameReceived(this, new NewFrameEventArgs(resized));
            }
        }
Esempio n. 26
0
        private static void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = FilterResize.Apply((Bitmap)eventArgs.Frame.Clone());

            Image_original = (Bitmap)img.Clone();

            Bitmap bmp = (Bitmap)img.Clone();

            Grayscale         FilterGrayscale         = new Grayscale(Data.Red, Data.Green, Data.Blue);
            SobelEdgeDetector FilterSobelEdgeDetector = new SobelEdgeDetector();

            bmp = FilterGrayscale.Apply(bmp);
            bmp = FilterSobelEdgeDetector.Apply(bmp);

            Image_ready = (Bitmap)bmp.Clone();

            Update_frame();
        }
Esempio n. 27
0
        public Bitmap Convert(Bitmap source, Size size)
        {
            if (source == null)
            {
                return(null);
            }

            Bitmap result = source.Clone(System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            if (result.Size != size)
            {
                if (size.Width >= result.Width && size.Height >= result.Height)
                {
                    size = result.Size; // no change
                }
                else
                {
                    var ratioWidth  = (double)size.Width / result.Width;
                    var ratioHeight = (double)size.Height / result.Height;

                    var ratio = Math.Min(ratioWidth, ratioHeight);
                    size = new Size((int)(result.Width * ratio), (int)(result.Height * ratio));

                    ResizeBicubic filter = new ResizeBicubic(size.Width, size.Height);
                    result = filter.Apply(result);
                }
            }

            ColorImageQuantizer  colorImageQuantizer = new ColorImageQuantizer(new MedianCutQuantizer());
            BurkesColorDithering dither = new BurkesColorDithering
            {
                ColorTable = palette
            };

            result = dither.Apply(result);

            return(result);
        }
Esempio n. 28
0
        public List <Bitmap> PickSlices(IReadOnlyList <Bitmap> inputImages, Size sliceSize)
        {
            var edgeImages = inputImages.Select(grayscaleFilter.Apply).ToList();

            edgeImages.ForEach(edgeDetectionFilter.ApplyInPlace);

            var edgeDensityHistograms = edgeImages.Select(x => new HorizontalIntensityStatistics(x).Gray).ToList();

            var imagesAndHistograms = Enumerable.Range(0, inputImages.Count).Select(index => {
                return(new ImagesAndHistogram {
                    OriginalImage = inputImages[index],
                    EdgeImage = edgeImages[index],
                    EdgeDensityHistogram = edgeDensityHistograms[index],
                    Rating = ratingCalculator.ComputeRating(inputImages[index], edgeDensityHistograms[index], sliceSize.Width, sliceSize.Height)
                });
            }).OrderBy(x => x.Rating).ToList();

            var sliceAspect = sliceSize.Width / (double)sliceSize.Height;

            foreach (var imagesAndHistogram in imagesAndHistograms)
            {
                var desiredWidth = (int)(imagesAndHistogram.OriginalImage.Height * sliceAspect);
                if (desiredWidth > imagesAndHistogram.OriginalImage.Width)
                {
                    continue;
                }
                var range = thumbnailGeneratorUtilities.GetRangeOfWidth(imagesAndHistogram.EdgeDensityHistogram, desiredWidth);

                var horizontalCrop      = new Crop(new Rectangle(range.Min, 0, range.Max - range.Min, imagesAndHistogram.OriginalImage.Height)).Apply(imagesAndHistogram.OriginalImage);
                var horizontalCrop24bpp = horizontalCrop.Clone(new Rectangle(Point.Empty, horizontalCrop.Size), PixelFormat.Format24bppRgb);
                imagesAndHistogram.SliceImage = horizontalCrop24bpp;
                var resizer = new ResizeBicubic(sliceSize.Width, sliceSize.Height);
                imagesAndHistogram.SliceImageResized = resizer.Apply(horizontalCrop24bpp);
            }

            return(imagesAndHistograms.Where(x => x.SliceImageResized != null).Select(x => x.SliceImageResized).ToList());
        }
Esempio n. 29
0
        public void GetInputLines(out double[] inp, int countBlocks)
        {
            var input = new double[countBlocks * 2 + 1].Select(d => 0.0).ToArray();

            AForge.Imaging.UnmanagedImage img;
            var    filter = new ResizeBicubic(countBlocks, countBlocks);
            double angle;

            lock (balanceLock)
            {
                angle = AngleRad;
                if (processed.Height == countBlocks && processed.Width == countBlocks)
                {
                    img = processed.Clone();
                }
                else
                {
                    img = filter.Apply(processed);
                }
            }



            img.CollectActivePixels().ForEach(p => { input[p.Y] += 1; input[countBlocks + p.X] += 1; });
            var mx = input.Max();

            if (mx != 0)
            {
                for (int i = 0; i < input.Length; i++)
                {
                    input[i] /= mx;
                }
            }
            input[input.Length - 1] = (double)angle / Math.PI / 2;

            inp = input;
        }
Esempio n. 30
0
 public SVM_SURFProcessor(MsgService msgService, Constants.SignType signType)
     : base(msgService, VisionMessage.msgType)
 {
     this.signType = signType;
     if (signs == null)
     {
         signs = new Bitmap[Constants.NUM_OF_SIGN_TYPES + 1];
         ResizeBicubic resizer = new ResizeBicubic(32, 32);
         for (int i = 1; i <= Constants.NUM_OF_SIGN_TYPES; i++)
         {
             String file_name = "signs\\sign_" + (i < 10 ? ("0" + i) : ("" + i)) + ".bmp";
             signs[i] = resizer.Apply((Bitmap)Bitmap.FromFile(Constants.base_folder + file_name, false));
         }
     }
     if (model == null)
     {
         BinaryFormatter formatter = new BinaryFormatter();
         FileStream stream = new FileStream(Constants.base_folder + Constants.NN_SVM_SURF + "_" + (signType == Constants.SignType.circular ? "circle" : "triangle") + ".dat", FileMode.Open, FileAccess.Read, FileShare.None);
         model = (Model)formatter.Deserialize(stream);
         stream.Close();
     }
 }
Esempio n. 31
0
        public static Bitmap ResizeImage(Bitmap originalImage, Int32 newWidth, Int32 newHeight)
        {
            var resizer = new ResizeBicubic(newWidth, newHeight);

            return(resizer.Apply(originalImage));
        }
Esempio n. 32
0
 public NN_SURFProcessor(MsgService msgService, Constants.SignType signType)
     : base(msgService, VisionMessage.msgType)
 {
     this.signType = signType;
     if (signs == null)
     {
         signs = new Bitmap[Constants.NUM_OF_SIGN_TYPES + 1];
         ResizeBicubic resizer = new ResizeBicubic(32, 32);
         for (int i = 1; i <= Constants.NUM_OF_SIGN_TYPES; i++)
         {
             String file_name = "signs\\sign_" + (i < 10 ? ("0" + i) : ("" + i)) + ".bmp";
             signs[i] = resizer.Apply((Bitmap)Bitmap.FromFile(Constants.base_folder + file_name, false));
         }
     }
     if (network == null)
     {
         network = Network.Load(Constants.base_folder + Constants.NN_SVM_SURF + "_" + (signType == Constants.SignType.circular ? "circle" : "triangle") + ".dat");
     }
 }
Esempio n. 33
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image )
        {
            UnmanagedImage bgImage = null;
            BitmapData bgLockedData = null;

            // get image size
            int width  = image.Width;
            int height = image.Height;
            int offset = image.Stride - ( ( image.PixelFormat == PixelFormat.Format8bppIndexed ) ? width : width * 3 );
            
            // check if we have provided background
            if ( ( backgroundImage == null ) && ( unmanagedBackgroundImage == null ) )
            {
                // resize image to 1/3 of its original size to make bluring faster
                ResizeBicubic resizeFilter = new ResizeBicubic( (int) width / 3, (int) height / 3 );
                UnmanagedImage tempImage = resizeFilter.Apply( image );

                // create background image from the input image blurring it with Gaussian 5 times
                GaussianBlur blur = new GaussianBlur( 5, 21 );

                blur.ApplyInPlace( tempImage );
                blur.ApplyInPlace( tempImage );
                blur.ApplyInPlace( tempImage );
                blur.ApplyInPlace( tempImage );
                blur.ApplyInPlace( tempImage );

                // resize the blurred image back to original size
                resizeFilter.NewWidth  = width;
                resizeFilter.NewHeight = height;
                bgImage = resizeFilter.Apply( tempImage );

                tempImage.Dispose( );
            }
            else
            {
                if ( backgroundImage != null )
                {
                    // check background image
                    if ( ( width != backgroundImage.Width ) || ( height != backgroundImage.Height ) || ( image.PixelFormat != backgroundImage.PixelFormat ) )
                    {
                        throw new InvalidImagePropertiesException( "Source image and background images must have the same size and pixel format" );
                    }

                    // lock background image
                    bgLockedData = backgroundImage.LockBits(
                        new Rectangle( 0, 0, width, height ),
                        ImageLockMode.ReadOnly, backgroundImage.PixelFormat );

                    bgImage = new UnmanagedImage( bgLockedData );
                }
                else
                {
                    bgImage = unmanagedBackgroundImage;
                }
            }

            // get background image's statistics (mean value is used as correction factor)
            ImageStatistics bgStatistics = new ImageStatistics( bgImage );

            byte* src = (byte*) image.ImageData.ToPointer( );
            byte* bg  = (byte*) bgImage.ImageData.ToPointer( );

            // do the job
            if ( image.PixelFormat == PixelFormat.Format8bppIndexed )
            {
                // grayscale image
                double mean = bgStatistics.Gray.Mean;

                for ( int y = 0; y < height; y++ )
                {
                    for ( int x = 0; x < width; x++, src++, bg++ )
                    {
                        if ( *bg != 0 )
                        {
                            *src = (byte) Math.Min( mean * *src / *bg, 255 );
                        }
                    }
                    src += offset;
                    bg  += offset;
                }
            }
            else
            {
                // color image
                double meanR = bgStatistics.Red.Mean;
                double meanG = bgStatistics.Green.Mean;
                double meanB = bgStatistics.Blue.Mean;

                for ( int y = 0; y < height; y++ )
                {
                    for ( int x = 0; x < width; x++, src += 3, bg += 3 )
                    {
                        // red
                        if ( bg[RGB.R] != 0 )
                        {
                            src[RGB.R] = (byte) Math.Min( meanR * src[RGB.R] / bg[RGB.R], 255 );
                        }
                        // green
                        if ( bg[RGB.G] != 0 )
                        {
                            src[RGB.G] = (byte) Math.Min( meanG * src[RGB.G] / bg[RGB.G], 255 );
                        }
                        // blue
                        if ( bg[RGB.B] != 0 )
                        {
                            src[RGB.B] = (byte) Math.Min( meanB * src[RGB.B] / bg[RGB.B], 255 );
                        }
                    }
                    src += offset;
                    bg  += offset;
                }
            }

            if ( backgroundImage != null )
            {
                backgroundImage.UnlockBits( bgLockedData );
            }

            // dispose background image if it was not set manually
            if ( ( backgroundImage == null ) && ( unmanagedBackgroundImage == null ) )
            {
                bgImage.Dispose( );
            }
        }
Esempio n. 34
0
 public NN_Processor(MsgService msgService, Constants.SignType signType)
     : base(msgService, VisionMessage.msgType)
 {
     this.signType = signType;
     if (signs == null)
     {
         signs = new Bitmap[Constants.NUM_OF_SIGN_TYPES + 1];
         ResizeBicubic resizer = new ResizeBicubic(32, 32);
         for (int i = 1; i <= Constants.NUM_OF_SIGN_TYPES; i++)
         {
             String file_name = "signs\\sign_" + (i < 10 ? ("0" + i) : ("" + i)) + ".bmp";
             signs[i] = resizer.Apply((Bitmap)Bitmap.FromFile(Constants.base_folder + file_name, false));
         }
     }
     if (networks == null)
     {
         networks = NNTrain.loadNetworks();
     }
 }