Esempio n. 1
0
        public Bitmap GetThumb(string path, int maxSize)
        {
            using (var original = Image.FromFile(path))
            {
                //if (original.Width <= maxSize && original.Height < maxSize)
                //    return original;

                // Figure out the ratio
                var ratioX = maxSize / (double)original.Width;
                var ratioY = maxSize / (double)original.Height;
                // use whichever multiplier is smaller
                var ratio = ratioX < ratioY ? ratioX : ratioY;

                // now we can get the new height and width
                var newHeight = Convert.ToInt32(original.Height * ratio);
                var newWidth  = Convert.ToInt32(original.Width * ratio);

                // create filter
                var filter = new ResizeBilinear(newWidth, newHeight);
                // apply the filter
                var newImage = filter.Apply(original);

                return(newImage);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Predict a hand written digit from the pictureBox
        /// </summary>
        private void PredictDigit()
        {
            // получаем нарисованную мышью цифру
            Bitmap bitmap = new Bitmap(handWrittenPictureBox.Image);

            // приводим изображение к размеру 28x28
            ResizeBilinear resizer = new ResizeBilinear(ImageWidth, ImageHeight);
            Bitmap         img     = resizer.Apply(bitmap);

            // Раскладываем изображение в пиксели
            IEnumerable <byte> pixels = Enumerable.Range(0, ImageWidth)
                                        .SelectMany(y => Enumerable.Range(0, ImageHeight), (y, x) => img.GetPixel(x, y).B);

            // нормализуем пиксели
            double[] input = pixels
                             .Select(p => new { p, v = 1.0 * (BlackColourCode - p) / BlackColourCode })
                             .Select(t => t.v > 0.1 ? t.v : 0)
                             .ToArray();

            // запускаем вычисление нейросетью вектора с вероятностями
            double[] predictions = _network.Compute(input.ToArray());

            // показываем результат в элементах ProgressBar
            for (int i = 0; i < SymbolsCount; i++)
            {
                _bars[i].Value = (int)(100 * predictions[i]);
            }

            Refresh();
        }
Esempio n. 3
0
        // New frame received by the player
        private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
        {
            //DateTime now = DateTime.Now;
            Graphics g = Graphics.FromImage(image);

            // paint current time
            //SolidBrush brush = new SolidBrush( Color.Red );
            //g.DrawString( now.ToString( ), this.Font, brush, new PointF( 5, 5 ) );

            if (radioButtonFixPicNo.Checked)
            {
                Crop           filter   = new Crop(new Rectangle(50, 300, 400, 400));
                Bitmap         newImage = filter.Apply(image);
                ResizeBilinear filter1  = new ResizeBilinear(200, 200);
                newImage = filter1.Apply(newImage);
                GrayscaleBT709 filter2   = new GrayscaleBT709();
                Bitmap         grayImage = filter2.Apply(newImage);
                ResizeBilinear filter3   = new ResizeBilinear(28, 28);
                Bitmap         smallPic  = filter3.Apply(grayImage);

                pictureBox1.Image = grayImage;
                pictureBox2.Image = smallPic;
            }

            //brush.Dispose( );
            g.Dispose( );
        }
Esempio n. 4
0
        public static void vykresliNalezeneKrizkyDoObrazku(string slozka, int zmencovaciKonstanta, List <RozsirenyBod> souradniceKrizu, string jakUlozit)
        {
            string[]       slozkaObrazku = Directory.GetFiles(slozka, "*.png", SearchOption.TopDirectoryOnly);
            Bitmap         obrazek       = (Bitmap)Bitmap.FromFile(slozkaObrazku[0]);
            ResizeBilinear filterSize1   = new ResizeBilinear(obrazek.Width / zmencovaciKonstanta, obrazek.Height / zmencovaciKonstanta);

            obrazek = filterSize1.Apply(obrazek);
            BitmapData data = obrazek.LockBits(new Rectangle(0, 0, obrazek.Width, obrazek.Height), ImageLockMode.ReadWrite, obrazek.PixelFormat);

            foreach (var m in souradniceKrizu)
            {
                //vykresleni bodu - stredu nalezeneho krizku
                Drawing.Rectangle(data, new Rectangle(m.X, m.Y, 2, 2), Color.Red);
            }
            obrazek.UnlockBits(data);
            obrazek.Save(jakUlozit);



            souradniceKrizu = souradniceKrizu.OrderBy(p => p.X).ToList();

            /* Vypisu vsechny souradnice
             *
             * Console.WriteLine(souradniceKrizu.Count);
             * foreach (var item in souradniceKrizu)
             * {
             *  Console.WriteLine("X: " + item.X + " Y: " + item.Y);
             * }
             * Console.WriteLine("Xxxxxx: " + souradniceKrizu.Count);
             */
        }
Esempio n. 5
0
        /// <summary>
        /// Crop the blob from the image
        /// </summary>
        private Bitmap CropBlob(BlobPanel blob, System.Drawing.Image source, int rotationAngel = 0)
        {
            // Create the target image, this is a squared image.
            int    size     = Math.Max(blob.Height, blob.Width);
            Bitmap newImage = new Bitmap(size, size, PixelFormat.Format24bppRgb);

            // Get the graphics object of the image.
            Graphics g = Graphics.FromImage(newImage);

            // Create the background color to use (the image we create is larger than the blob (as we squared it)
            // so this would be the color of the excess areas.
            Color bColor = Color.FromArgb((int)txtExtractedBackColor.Value, (int)txtExtractedBackColor.Value, (int)txtExtractedBackColor.Value);

            // Fill back color.
            g.FillRectangle(new SolidBrush(bColor), 0, 0, size, size);

            // Now we clip the blob from the PictureBox image.
            g.DrawImage(source, new Rectangle(0, 0, blob.Width, blob.Height), blob.Left, blob.Top, blob.Width, blob.Height, GraphicsUnit.Pixel);
            g.Dispose();

            if (rotationAngel != 0)
            {
                RotateBilinear filter = new RotateBilinear(rotationAngel, true);
                filter.FillColor = bColor;
                // apply the filter
                newImage = filter.Apply(newImage);
            }

            // Resize the image.
            ResizeBilinear resizefilter = new ResizeBilinear((int)txtExportSize.Value, (int)txtExportSize.Value);

            newImage = resizefilter.Apply(newImage);

            return(newImage);
        }
Esempio n. 6
0
        /// <summary>
        /// 位图缩放
        /// </summary>
        /// <param name="bmp">源位图</param>
        /// <param name="newW">新宽度</param>
        /// <param name="newH">新高度</param>
        /// <returns>返回变换后的位图</returns>
        public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH)
        {
            // create filter
            ResizeBilinear filter = new ResizeBilinear(newW, newH);

            // apply the filter
            return(filter.Apply(bmp));

            #region 旧代码
            //try
            //{
            //    Bitmap b = new Bitmap(newW, newH, pf);
            //    Graphics g = Graphics.FromImage(b);

            //    // 插值算法的质量
            //    g.InterpolationMode = InterpolationMode.HighQualityBilinear;

            //    g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
            //    g.Dispose();

            //    return b;
            //}
            //catch(Exception ex)
            //{
            //    throw new Exception(ex.Message);
            //}
            #endregion
        }
Esempio n. 7
0
        public string GetLetter(Bitmap bmp)
        {
            List <Bitmap> brailePictures = pictures.BitmapList;

            try
            {
                foreach (var i in brailePictures)
                {
                    Size           size   = GetSize(i.Size, bmp.Size);
                    ResizeBilinear filter = new ResizeBilinear(size.Width, size.Height);
                    bmp = filter.Apply(bmp);
                    TemplateMatch[] matches = exhaustiveTemplateMatching.ProcessImage(i, bmp);
                    float           sim     = matches[0].Similarity;

                    if (sim >= similar)
                    {
                        similar     = sim;
                        letterCount = count;
                    }

                    count++;
                    Debug.WriteLine("The count is" + count);
                }


                return(Letters[letterCount]);
            }
            catch (IndexOutOfRangeException)
            {
                Debug.WriteLine("The letter could not be Identified");
                return("Unknown");
            }
        }
Esempio n. 8
0
        private void BtnChooseFileClick(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                InitialDirectory = Program.AppPath + @"backgrounds\",
                Filter           = "Image Files|*.jpg;*.gif;*.bmp;*.png;*.jpeg",
                FilterIndex      = 1
            };

            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                string fileName = ofd.FileName;
                Fpc.Fpobject.image = fileName;
                Image img = Image.FromFile(fileName);
                try
                {
                    Fpc.ImgPlan = (Image)img.Clone(); //
                    var rf = new ResizeBilinear(533, 400);
                    _floorPlanImage = rf.Apply((Bitmap)img);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                Fpc.NeedSizeUpdate = true;
                Fpc.NeedsRefresh   = true;
                if (txtName.Text.Trim() == "")
                {
                    txtName.Text = "Plan " + MainForm.NextFloorPlanId;
                }
                _pnlPlan.Invalidate();
            }
            ofd.Dispose();
        }
Esempio n. 9
0
        public void resize_bilinear()
        {
            double[,] diag = Matrix.Magic(5);
            diag           = diag.Divide(diag.Max());

            Bitmap input = diag.ToBitmap();

            // Create a new resize bilinear filter
            var filter = new ResizeBilinear(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.874509803921569,  0.56078431372549, 0.0784313725490196, 0.274509803921569,  0.47843137254902,               0.6 },
                { 0.827450980392157, 0.580392156862745, 0.356862745098039,  0.227450980392157, 0.423529411764706, 0.556862745098039, 0.623529411764706 },
                { 0.725490196078431, 0.356862745098039, 0.262745098039216,  0.376470588235294, 0.576470588235294, 0.662745098039216, 0.698039215686274 },
                { 0.250980392156863,  0.23921568627451, 0.341176470588235,  0.525490196078431, 0.725490196078431, 0.811764705882353, 0.847058823529412 },
                {  0.27843137254902, 0.333333333333333, 0.474509803921569,  0.662745098039216, 0.792156862745098, 0.635294117647059, 0.498039215686275 },
                { 0.403921568627451,  0.47843137254902, 0.627450980392157,  0.780392156862745, 0.749019607843137,               0.4, 0.145098039215686 },
                { 0.427450980392157, 0.592156862745098, 0.776470588235294,  0.843137254901961,  0.36078431372549, 0.282352941176471, 0.294117647058824 },
                {  0.43921568627451, 0.635294117647059, 0.835294117647059,  0.866666666666667, 0.207843137254902, 0.235294117647059, 0.356862745098039 }
            };

            Assert.IsTrue(expected.IsEqual(actual, 1e-6));
        }
Esempio n. 10
0
        // =========================================================
        private void ZoomFunct(ref Bitmap frame, double Factor)
        {
            if (Factor < 0.1)
            {
                return;
            }

            int centerX  = frame.Width / 2;
            int centerY  = frame.Height / 2;
            int OrgSizeX = frame.Width;
            int OrgSizeY = frame.Height;

            int fromX = centerX - (int)(centerX / Factor);
            int fromY = centerY - (int)(centerY / Factor);
            int SizeX = (int)(OrgSizeX / Factor);
            int SizeY = (int)(OrgSizeY / Factor);

            try {
                Crop CrFilter = new Crop(new Rectangle(fromX, fromY, SizeX, SizeY));
                frame = CrFilter.Apply(frame);
                ResizeBilinear RBfilter = new ResizeBilinear(OrgSizeX, OrgSizeY);
                frame = RBfilter.Apply(frame);
            } catch {
            }
        }
Esempio n. 11
0
        public void ProcessImage(string urlImage)       //Görüntünün işlendiği metot.
        {
            Stopwatch watch = Stopwatch.StartNew();     //Görüntünün işlenmesi sırasında süre tutulması için süre başlatılmaktadır.

            Bitmap root         = new Bitmap(urlImage); //Root Image (Default Image)
            Bitmap bmp          = new Bitmap(root);     //Resize Image
            Bitmap bmp1         = new Bitmap(root);     //Smoothing Image
            Bitmap bmp2         = new Bitmap(root);     //Color Filtering Image
            string outputstring = "";

            ///Root
            outputstring          = this.Ocr(root);
            txtNumbePlate1.Text   = outputstring;
            ptBNumberPlate1.Image = root;


            //Resize Image to : 1920x1080
            outputstring = "";
            ResizeBilinear filterr = new ResizeBilinear(1920, 1080);

            bmp = filterr.Apply(bmp);

            outputstring          = this.Ocr(bmp);
            txtNumbePlate2.Text   = outputstring;
            ptBNumberPlate2.Image = bmp;


            //Smoothing
            outputstring = "";
            if (BitmapFilter.GaussianBlur(bmp1, 4))
            {
                if (BitmapFilter.GaussianBlur(bmp1, 4))
                {
                    if (BitmapFilter.MeanRemoval(bmp1, 9))
                    {
                    }
                }
            }
            outputstring          = this.Ocr(bmp1);
            txtNumbePlate3.Text   = outputstring;
            ptBNumberPlate3.Image = bmp1;


            //Color Filtering
            outputstring = "";
            ColorFiltering filter = new ColorFiltering();

            filter.Green = new IntRange(175, 255);
            bmp2         = filter.Apply(bmp2);

            outputstring          = this.Ocr(bmp2);
            txtNumbePlate4.Text   = outputstring;
            ptBNumberPlate4.Image = bmp2;

            watch.Stop(); //Stop The Timer
            lblTime.Text  = String.Format("Total Time : {0} Seconds", watch.Elapsed.TotalSeconds);
            lblCount.Text = position.ToString() + "/" + lstimages.Count.ToString();
            System.Threading.Thread.Sleep(5000);
        }
        public static Bitmap encryptImage(Bitmap mainImage, Bitmap hiddenImage)
        {
            if (hiddenImage.Height != mainImage.Height || hiddenImage.Width != mainImage.Width)
            {
                ResizeBilinear resizeFilter = new ResizeBilinear(mainImage.Width, mainImage.Height);
                hiddenImage = resizeFilter.Apply(hiddenImage);
            }

            Color pixelContainerImage = new Color();
            Color pixelMsgImage       = new Color();

            byte[] MsgBits;
            byte[] AlphaBits;
            byte[] RedBits;
            byte[] GreenBits;
            byte[] BlueBits;

            byte newAlpha = 0;
            byte newRed   = 0;
            byte newGreen = 0;
            byte newBlue  = 0;

            for (int i = 0; i < mainImage.Height; i++)
            {
                for (int j = 0; j < mainImage.Width; j++)
                {
                    pixelMsgImage = hiddenImage.GetPixel(j, i);
                    MsgBits       = getBits((byte)pixelMsgImage.R);

                    pixelContainerImage = mainImage.GetPixel(j, i);
                    AlphaBits           = getBits((byte)pixelContainerImage.A);
                    RedBits             = getBits((byte)pixelContainerImage.R);
                    GreenBits           = getBits((byte)pixelContainerImage.G);
                    BlueBits            = getBits((byte)pixelContainerImage.B);

                    AlphaBits[6] = MsgBits[0];
                    AlphaBits[7] = MsgBits[1];

                    RedBits[6] = MsgBits[2];
                    RedBits[7] = MsgBits[3];

                    GreenBits[6] = MsgBits[4];
                    GreenBits[7] = MsgBits[5];

                    BlueBits[6] = MsgBits[6];
                    BlueBits[7] = MsgBits[7];

                    newAlpha = getByte(AlphaBits);
                    newRed   = getByte(RedBits);
                    newGreen = getByte(GreenBits);
                    newBlue  = getByte(BlueBits);

                    pixelContainerImage = Color.FromArgb(newAlpha, newRed, newGreen, newBlue);
                    mainImage.SetPixel(j, i, pixelContainerImage);
                }
            }

            return(mainImage);
        }
        //used to actually resize the bitmap to match the reference image.
        private static Bitmap resizeBitmap(Bitmap bitmap, int width, int height)
        {
            ResizeBilinear resizer = new ResizeBilinear(width, height);

            Bitmap result = resizer.Apply(bitmap);

            return(result);
        }
Esempio n. 14
0
 public BlobExtractor(int blobMin, int blobMax)
 {
     extractor             = new BlobCounter();
     extractor.FilterBlobs = true;
     extractor.MinWidth    = extractor.MinHeight = blobMin;
     extractor.MaxWidth    = extractor.MaxHeight = blobMax;
     quadTransformer       = new QuadrilateralTransformation();
     resizer = new ResizeBilinear(blobWidth, blobHeight);
 }
Esempio n. 15
0
        public Bitmap Multiply(Bitmap leftOperand, Bitmap rightOperand)
        {
            ResizeBilinear resize = new ResizeBilinear(leftOperand.Width, leftOperand.Height);

            rightOperand = resize.Apply(rightOperand);
            Multiply filter = new Multiply(rightOperand);

            return(filter.Apply(leftOperand));
        }
Esempio n. 16
0
        public Bitmap Difference(Bitmap leftOperand, Bitmap rightOperand)
        {
            ResizeBilinear resize = new ResizeBilinear(leftOperand.Width, leftOperand.Height);

            rightOperand = resize.Apply(rightOperand);
            Difference filter = new Difference(rightOperand);

            return(filter.Apply(leftOperand));
        }
Esempio n. 17
0
        public static Bitmap ResizeBilinear(Bitmap bmp, int width, int height)
        {
            // create filter
            ResizeBilinear filter = new ResizeBilinear(width, height);
            // apply the filter
            Bitmap newImage = filter.Apply(bmp);

            return(newImage);
        }
Esempio n. 18
0
        public Bitmap Subtract(Bitmap leftOperand, Bitmap rightOperand)
        {
            ResizeBilinear resize = new ResizeBilinear(leftOperand.Width, leftOperand.Height);

            rightOperand = resize.Apply(rightOperand);
            Subtract filter = new Subtract(rightOperand);

            return(filter.Apply(leftOperand));
        }
Esempio n. 19
0
        public ProcessingResult <FlattenedCroppedArea> ScaleAndFlatten(ICroppedArea croppedArea)
        {
            FlattenedCroppedArea output;

            using (croppedArea)
            {
                var flattenedResults = new List <OrderedFlattenedBitmap>();


                foreach (var croppedAreaPart in croppedArea.CroppedParts)
                {
                    if (croppedAreaPart.Bitmap == null)
                    {
                        flattenedResults.Add(new OrderedFlattenedBitmap(croppedAreaPart.Order, null));
                        continue;
                    }

                    //EMNIST expects black background and white text
                    new Invert().ApplyInPlace(croppedAreaPart.Bitmap);

                    //Bitmap will force stride to be 4x, so let's avoid mess up and do it ourselves
                    var inputSizeAsMultipliesOfFour = GetInputSizeFromBitmap(croppedAreaPart.Bitmap).GetInputSizeAsMultipliesOfFour();

                    //Downscale to height = 28 and width scaled by same factor
                    var inputSizeAfterDownscale = GetDimensionsForResizeBeforeCentering(inputSizeAsMultipliesOfFour);

                    //And fix it to mulitple of 4 again
                    inputSizeAfterDownscale = inputSizeAfterDownscale.GetInputSizeAsMultipliesOfFour();

                    //Blur it a little for better feature recognition
                    new GaussianBlur(0.4, 3).ApplyInPlace(croppedAreaPart.Bitmap);

                    //Resize to multiples of four
                    using (var bitmapFixedToMultiplyOfFour =
                               new ResizeBilinear(inputSizeAsMultipliesOfFour.Width, inputSizeAsMultipliesOfFour.Height)
                               .Apply(croppedAreaPart.Bitmap))
                        //Resize to 28*XX
                        using (var bitmapDownscaledToExpectedHeight =
                                   new ResizeBilinear(inputSizeAfterDownscale.Width, inputSizeAfterDownscale.Height).Apply(
                                       bitmapFixedToMultiplyOfFour))
                        //using (var bitmapResized =
                        //            new ResizeBilinear(28, 28)
                        //                .Apply(croppedAreaPart.Bitmap))
                        {
                            //Resize canvas and center to 28*28
                            flattenedResults.Add(new OrderedFlattenedBitmap(croppedAreaPart.Order,
                                                                            CreatedSquaredAndCenteredBitmapFrom(bitmapDownscaledToExpectedHeight)));
                        }
                }

                output = new FlattenedCroppedArea(croppedArea.AreaUsedForCropping, flattenedResults, croppedArea.DocumentId);
            }

            //Make bitmap squared instead of rectangular
            return(ProcessingResult <FlattenedCroppedArea> .Success(output));
        }
Esempio n. 20
0
        public List <double> GetSensorsFromBitmap(Bitmap image)
        {
            List <double> sensors = new List <double>(cnt_blocks_one_line * cnt_blocks_one_line);

            //Bitmap im = (Bitmap)pictureBox1.Image;
            ResizeBilinear filter = new ResizeBilinear(28, 28);
            Bitmap         im     = filter.Apply(image);

            /*
             * for (int y = 0; y < 28; ++y)
             * {
             *  double sum = 0;
             *  for (int x = 0; x < 28; ++x)
             *  {
             *      Color c = im.GetPixel(x, y);
             *      double curr_value = (int)c.R;
             *      sum += curr_value / 255.0;
             *  }
             *  input_camera.Add((sum / 28.0));// * 2 - 1);
             * }
             * for (int x = 0; x < 28; ++x)
             * {
             *  double sum = 0;
             *  for (int y = 0; y < 28; ++y)
             *  {
             *      double curr_value = (int)im.GetPixel(x, y).R;
             *      sum += curr_value / 255.0;
             *  }
             *  input_camera.Add((sum / 28.0));// * 2 - 1);
             * }
             */

            int length = 28 / cnt_blocks_one_line;

            for (int y1 = 0; y1 < cnt_blocks_one_line; ++y1)
            {
                for (int x1 = 0; x1 < cnt_blocks_one_line; ++x1)
                {
                    double sum = 0;
                    for (int y2 = 0; y2 < length; ++y2)
                    {
                        for (int x2 = 0; x2 < length; ++x2)
                        {
                            int y          = y1 * length + y2;
                            int x          = x1 * length + x2;
                            int curr_value = (int)im.GetPixel(x, y).R;
                            sum += curr_value / 255.0;
                        }
                    }
                    int ind = y1 * cnt_blocks_one_line + x1;
                    sensors.Add((sum / length / length));// * 2 - 1);
                }
            }

            return(sensors);
        }
Esempio n. 21
0
        private static string ExtractText(Bitmap bmp)
        {
            // create filter
            var resizeBilinear = new ResizeBilinear(bmp.Width * 2, bmp.Height * 2);
            var greyScale      = new Grayscale(0.2125, 0.7154, 0.0721);

            var biggerImage = new FiltersSequence(resizeBilinear).Apply(bmp);

            return(string.Join(", ", TesseractTestBase.ExtractText(biggerImage)));
        }
Esempio n. 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 /// <remarks></remarks>
 public BoardDetector()
 {
     this.median         = new Median();
     this.quadFinder     = new QuadrilateralFinder();
     this.resize         = new ResizeBilinear(640, 480);
     this.boardCorners   = new List <IntPoint>();
     this.oldCorners     = new List <List <IntPoint> >();
     this.filteredBoard  = new Bitmap(640, 480);
     this.rectifiedBoard = new Bitmap(640, 480);
 }
Esempio n. 23
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. 24
0
        //-------------------------------------------------------------
        private void process_imginput(Bitmap img, String Plate_Type)
        {
            //grayscale
            IFilter way_filt;//= new GrayscaleY();

            //process_image = way_filt.Apply(img);
            //resize
            if (Plate_Type == "1hang")
            {
                way_filt = new ResizeBilinear(600, 120); //bien 1 hang
            }
            else
            {
                way_filt = new ResizeBilinear(300, 200); //bien 2 hang
            }

            process_image = way_filt.Apply(img);
            //process_image = get_plate(process_image, 10, 210, 30, 330);
            input_image = way_filt.Apply(input_image);
            p           = process_image;
            //threshold
            way_filt      = new Threshold(125);
            process_image = way_filt.Apply(process_image);


            //K-means
            process_image = kmean(process_image);


            //invert
            way_filt      = new Invert();
            process_image = way_filt.Apply(process_image);


            //liembt
            //UCM
            way_filt      = new Median();
            process_image = way_filt.Apply(process_image);

            //way_filt = new AdaptiveSmooth();
            //process_image = way_filt.Apply(process_image);

            //end liembt
            //filter k
            BlobsFiltering filter = new BlobsFiltering();

            filter.MinHeight = 25;//50
            filter.MinWidth  = 10;
            filter.MaxHeight = 100;
            filter.ApplyInPlace(process_image);
            //p = process_image;
            input_width  = process_image.Width;
            input_height = process_image.Height;
        }
Esempio n. 25
0
        private void getFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap         BsourceImage = (Bitmap)eventArgs.Frame.Clone();
            ResizeBilinear scale_filter = new ResizeBilinear(pictureBox1.Width, pictureBox1.Height);

            BsourceImage      = scale_filter.Apply(BsourceImage);
            pictureBox1.Image = BsourceImage;

            g = Graphics.FromImage(pictureBox1.Image);
            g.DrawRectangle(Pens.Red, new Rectangle(50, 50, 200, 200));
        }
Esempio n. 26
0
        public BitmapProcessor(Crop crop, Grayscale grayscale, ContrastStretch contrastStretch, ResizeBilinear resizeBilinear, BitmapProcessingParams bitmapProcessingParams)
        {
            _crop                   = crop;
            _grayscale              = grayscale;
            _contrastStretch        = contrastStretch;
            _resizeBilinear         = resizeBilinear;
            _bitmapProcessingParams = bitmapProcessingParams;

            _resizeBilinear.NewWidth  = _bitmapProcessingParams.ResizeWidth;
            _resizeBilinear.NewHeight = _bitmapProcessingParams.ResizeHeight;
        }
Esempio n. 27
0
        public Bitmap GetThumb(string path, int width, int height)
        {
            using (var original = Image.FromFile(path))
            {
                // create filter
                var filter = new ResizeBilinear(width, height);
                // apply the filter
                var newImage = filter.Apply(original);

                return(newImage);
            }
        }
Esempio n. 28
0
        public Encoder(int sampleRate, int FFTSize, Size frameSize, int startLine, int[] randomizer)
        {
            randomizerSequence = randomizer;
            randomizerMask     = BuildSequence(randomizerSequence);
            frequencyMask      = Abs(randomizerMask);

            this.SampleRate = sampleRate;
            this.FFTSize    = FFTSize;
            resizer         = new ResizeBilinear(frameSize.Width, frameSize.Height);
            this.FrameSize  = frameSize;
            this.StartLine  = startLine;
        }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 /// <remarks></remarks>
 public TileDetector()
 {
     median                   = new Median();
     blobCounter              = new BlobCounter();
     blobCounter.FilterBlobs  = true;
     blobCounter.MinWidth     = (int)Math.Ceiling(15f / scale);
     blobCounter.MinHeight    = (int)Math.Ceiling(15f / scale);
     blobCounter.ObjectsOrder = ObjectsOrder.XY;
     resize                   = new ResizeBilinear(640, 480);
     this.filteredBoard       = new Bitmap(640, 480);
     this.tileBlobs           = new List <Blob>();
 }
        public static System.Drawing.Image ResizeImage(System.Drawing.Image SourceImage)
        {
            try {
//				// binarization filtering sequence
//	            FiltersSequence filter = new FiltersSequence(
//	                new Crop(rect),
//	                new Median(),
//	                new ContrastCorrection(),
//	                //new Mean(),
//	                new AForge.Imaging.Filters.Blur(),
//	                new GrayscaleBT709(),
//	                //new Threshold(),
//	                new Threshold(),
//	                new Invert()
//
//	            );


                // load image
                Bitmap image = (Bitmap)SourceImage;

                // format image
                AForge.Imaging.Image.Clone(image, image.PixelFormat);
                //            AForge.Imaging.Image.FormatImage(ref image);

                // lock the source image
                BitmapData sourceData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);

                // create filter
                ResizeBilinear filter = new ResizeBilinear(image.Width / 2, image.Height / 2);
                // apply the filter
//	            Bitmap newImage = filter.Apply( image );

                UnmanagedImage binarySource = filter.Apply(new UnmanagedImage(sourceData));


                Bitmap binarizedImage = binarySource.ToManagedImage();


                // unlock source image
                image.UnlockBits(sourceData);

                // dispose temporary binary source image
                binarySource.Dispose();

                System.Drawing.Image img = (System.Drawing.Image)binarizedImage;

                return(img);
            } catch (Exception ex) {
                throw ex;
            }
        }
        private bool ProcessFace(Tag face, Bitmap intermediateImage, Bitmap image)
        {
            if (face.MouthCenter == null)
            {
                return false;
            }
            var center = ConvertPoint(face.MouthCenter, image);
            IntPoint left, right;
            if (face.MouthLeft != null && face.MouthRight != null)
            {
                left = ConvertPoint(face.MouthLeft, image);
                right = ConvertPoint(face.MouthRight, image);
            }
            else if (face.EyeLeft != null && face.EyeRight != null)
            {
                var eyeLeft = ConvertPoint(face.EyeLeft, image);
                var eyeRight = ConvertPoint(face.EyeRight, image);
                var midY = (eyeLeft.Y + eyeRight.Y)/2;
                var midX = (eyeLeft.X + eyeRight.X)/2;
                left = new IntPoint(eyeLeft.X - midX + center.X, eyeLeft.Y - midY + center.Y);
                right = new IntPoint(eyeRight.X - midX + center.X, eyeRight.Y - midY + center.Y);
            }
            else
            {
                return false;
            }

            var overlay = null == _overlayImageProvider ? null : _overlayImageProvider.GetRandomOverlayImage();
            if (null != overlay)
            {
                using (overlay)
                {
                    var targetWidth = (left.DistanceTo(center) + right.DistanceTo(center)) / 2 * 4;
                    var bmOverlay = new Bitmap(overlay);
                    using (bmOverlay)
                    {
                        var resizedOverlay = new ResizeBilinear((int)targetWidth, (int)(overlay.Height * targetWidth / overlay.Width)).Apply(bmOverlay);
                        using (resizedOverlay)
                        {
                            using (var g = Graphics.FromImage(image))
                            {
                                g.DrawImage(resizedOverlay, new System.Drawing.Point(center.X - resizedOverlay.Width / 2, center.Y - resizedOverlay.Height / 2));
                            }
                        }
                    }
                }
            }

            new PointsMarker(new [] { center }, Color.Blue).ApplyInPlace(intermediateImage);
            new PointsMarker(new [] { left }, Color.Green).ApplyInPlace(intermediateImage);
            new PointsMarker(new [] { right }, Color.Purple).ApplyInPlace(intermediateImage);

            return null != overlay;
        }
        /// <summary>
        /// Scales down the byte size of the image by reducing dimensions and/or introducing compression.  It aims to get it under 2MB so the web service won't reject it.
        /// </summary>
        private byte[] ResizePictureForDetection(byte[] data)
        {
            const int maxLength = 2*1000*1000; // be conservative
            if (data == null || data.Length < maxLength)
                return data;

            using (var ms = new MemoryStream(data))
            {
                using (var rawImage = (Bitmap) Image.FromStream(ms))
                {
                    log.DebugFormat("Image is too big @ {0} bytes, {1}x{2}, shrinking", data.Length, rawImage.Width, rawImage.Height);

                    // too big - try some measures to downsize things
                    for (var cutSize = 1;; cutSize++)
                    {
                        // first, let's cut the image down
                        using (var smallerImage = new ResizeBilinear(rawImage.Width/cutSize, rawImage.Height/cutSize).Apply(rawImage))
                        {
                            log.DebugFormat("Sized down to {0}x{1}", smallerImage.Width, smallerImage.Height);

                            // now, see what a PNG would be...
                            var png = ImageHelper.GetBytes(s => smallerImage.Save(s, ImageFormat.Png));
                            log.DebugFormat("PNG is {0} bytes", png.Length);
                            if (png.Length < maxLength)
                                return png;

                            // too big, try JPEG @ Q100
                            var jpgQ100 = ImageHelper.GetBytes(s => smallerImage.Save(s, ImageHelper.JPEGEncoder(), ImageHelper.Quality(100)));
                            log.DebugFormat("JPG@Q100 is {0} bytes", jpgQ100.Length);
                            if (jpgQ100.Length < maxLength)
                                return jpgQ100;

                            // too big, try JPEG @ Q99
                            var jpgQ99 = ImageHelper.GetBytes(s => smallerImage.Save(s, ImageHelper.JPEGEncoder(), ImageHelper.Quality(99)));
                            log.DebugFormat("JPG@Q99 is {0} bytes", jpgQ99.Length);
                            if (jpgQ99.Length < maxLength)
                                return jpgQ99;

                            // too big, try JPEG @ Q95
                            var jpgQ95 = ImageHelper.GetBytes(s => smallerImage.Save(s, ImageHelper.JPEGEncoder(), ImageHelper.Quality(95)));
                            log.DebugFormat("JPG@Q95 is {0} bytes", jpgQ95.Length);
                            if (jpgQ95.Length < maxLength)
                                return jpgQ95;

                            // still too big, guess we'll have to use a smaller image
                        }
                    }
                }
            }
        }