Ejemplo n.º 1
0
        private string reconhecerCaptcha(Image img)
        {
            Bitmap imagem = new Bitmap(img);

            imagem = imagem.Clone(new Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Erosion        erosion    = new Erosion();
            Dilatation     dilatation = new Dilatation();
            Invert         inverter   = new Invert();
            ColorFiltering cor        = new ColorFiltering();

            cor.Blue  = new AForge.IntRange(200, 255);
            cor.Red   = new AForge.IntRange(200, 255);
            cor.Green = new AForge.IntRange(200, 255);
            Opening            open  = new Opening();
            BlobsFiltering     bc    = new BlobsFiltering();
            Closing            close = new Closing();
            GaussianSharpen    gs    = new GaussianSharpen();
            ContrastCorrection cc    = new ContrastCorrection();

            bc.MinHeight = 10;
            GrayscaleRMY    gray = new GrayscaleRMY();
            Threshold       thr  = new Threshold(200);
            Difference      diff = new Difference(dilatation.Apply(imagem));
            FiltersSequence seq  = new FiltersSequence(diff, inverter, erosion, gray, thr, cc);

            pictureBox.Image = seq.Apply(imagem);
            string reconhecido = OCR((Bitmap)pictureBox.Image);

            return(reconhecido);
        }
Ejemplo n.º 2
0
        private void reapplyToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Dilatation filter = new Dilatation();

            // apply the filter
            pictureBox2.Image = filter.Apply((Bitmap)pictureBox2.Image);
        }
Ejemplo n.º 3
0
        public Bitmap ToDilatation(Bitmap Im)
        {
            AForge.Imaging.Filters.Dilatation Img = new Dilatation();
            Bitmap bmImage = AForge.Imaging.Image.Clone(new Bitmap(Im), PixelFormat.Format24bppRgb);

            return(Img.Apply(bmImage));
        }
Ejemplo n.º 4
0
        public Bitmap GetNewFrame(Bitmap source)
        {
            var newFrame = dilatation.Apply(source);

            source.Dispose();
            return(newFrame);
        }
Ejemplo n.º 5
0
        public static Bitmap Dilatation(Bitmap Imagem)
        {
            Dilatation filter = new Dilatation();

            Imagem = Imagem.Clone(new Rectangle(0, 0, Imagem.Width, Imagem.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Imagem = filter.Apply(Imagem);
            return(Imagem);
        }
Ejemplo n.º 6
0
        public static Bitmap DilatImage(Bitmap bit)
        {
            Bitmap bmp = bit.Clone(new Rectangle(0, 0, bit.Width, bit.Height), PixelFormat.Format24bppRgb);

            Dilatation dila = new Dilatation();

            return(dila.Apply(bmp));
        }
Ejemplo n.º 7
0
        public static BitmapImage DilatationImage(this BitmapImage bitmapimage)
        {
            Bitmap     bitmap     = bitmapimage.BitmapImage2Bitmap();
            Dilatation dilatation = new Dilatation();

            dilatation.Apply(bitmap);
            return(bitmap.ToBitmapImage());
        }
        /// <returns>Morphology opened image</returns>
        public static Bitmap MorphologyOpening(this Bitmap image, int kernel)
        {
            if (image.PixelFormat != PixelFormat.Format8bppIndexed)
            {
                throw new NotSupportedException("Operation can be applied to binary 8bpp images only");//we use morphology only for binarized images
            }
            Erosion morphologyErosion = new Erosion();
            Bitmap  temp = morphologyErosion.Apply(image);

            for (int i = 0; i < kernel - 1; i++)
            {
                temp = morphologyErosion.Apply(temp);
            }
            Dilatation morphologyDilatation = new Dilatation();

            for (int i = 0; i < kernel; i++)
            {
                temp = morphologyDilatation.Apply(temp);
            }
            return(temp);
        }
Ejemplo n.º 9
0
        private void resultGestureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int           dir;
            int           no;
            List <string> filedir = new List <string>(Directory.GetDirectories(path));

            for (dir = 0, no = 0; (dir < filedir.Count && no <= 26); dir++, no++)
            {
                string[]      filePaths = Directory.GetFiles(filedir[dir].ToString());
                List <Bitmap> y         = new List <Bitmap>();
                foreach (var iI in filePaths)
                {
                    Bitmap Image = new Bitmap(iI);
                    y.Add(Image);
                }

                foreach (Bitmap img in y)
                {
                    pictureBox1.Image = img;
                    srcImg            = img;
                    dstImg            = img;
                    Bitmap skin  = new Bitmap(pictureBox1.Image);
                    var    rect  = new Rectangle(0, 0, skin.Width, skin.Height);
                    var    data  = skin.LockBits(rect, ImageLockMode.ReadWrite, skin.PixelFormat);
                    var    depth = Bitmap.GetPixelFormatSize(data.PixelFormat) / 8; //bytes per pixel

                    var buffer = new byte[data.Width * data.Height * depth];

                    //copy pixels to buffer
                    Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);

                    System.Threading.Tasks.Parallel.Invoke(
                        () =>
                    {
                        //upper-left
                        Process(buffer, 0, 0, data.Width / 2, data.Height / 2, data.Width, depth);
                    },
                        () =>
                    {
                        //upper-right
                        Process(buffer, data.Width / 2, 0, data.Width, data.Height / 2, data.Width, depth);
                    },
                        () =>
                    {
                        //lower-left
                        Process(buffer, 0, data.Height / 2, data.Width / 2, data.Height, data.Width, depth);
                    },
                        () =>
                    {
                        //lower-right
                        Process(buffer, data.Width / 2, data.Height / 2, data.Width, data.Height, data.Width, depth);
                    }
                        );

                    //Copy the buffer back to image
                    Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);

                    skin.UnlockBits(data);
                    pictureBox2.Image = skin;



                    Bitmap src = new Bitmap(pictureBox1.Image);
                    Bitmap res = new Bitmap(pictureBox2.Image);
                    src = resize(src, new Size(200, 200));
                    res = resize(res, new Size(200, 200));
                    pictureBox1.Image = src;
                    pictureBox2.Image = res;

                    GrayscaleBT709 grayoject = new GrayscaleBT709();
                    pictureBox2.Image = grayoject.Apply((Bitmap)pictureBox2.Image);

                    Dilatation filter = new Dilatation();
                    // apply the filter
                    pictureBox2.Image = filter.Apply((Bitmap)pictureBox2.Image);

                    ExtractBiggestBlob filter1 = new ExtractBiggestBlob();
                    pictureBox2.Image = filter.Apply((Bitmap)pictureBox2.Image);
                    blob = filter1.BlobPosition;

                    Bitmap src1   = new Bitmap(pictureBox1.Image);
                    Bitmap res1   = new Bitmap(pictureBox2.Image);
                    Bitmap newBmp = new Bitmap(src1.Width, res1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);


                    //Threshold t = new Threshold();
                    //pictureBox2.Image = t.Apply((Bitmap)pictureBox2.Image);
                    for (int i = 0; i < res1.Width; i++)
                    {
                        for (int j = 0; j < res1.Height; j++)
                        {
                            System.Drawing.Color srcColor = src1.GetPixel(i + blob.X, j + blob.Y);
                            System.Drawing.Color dstColor = res1.GetPixel(i, j);
                            if (!(dstColor.R >= 0 && dstColor.R <= 10 && dstColor.G >= 0 && dstColor.G <= 10 && dstColor.B >= 0 && dstColor.B <= 10))
                            {
                                newBmp.SetPixel(i, j, srcColor);
                            }
                            else
                            {
                                newBmp.SetPixel(i, j, Color.Black);
                            }
                        }
                    }
                    res1 = newBmp;
                    pictureBox2.Image = newBmp;

                    List <double>  edgeCount  = new List <double>();
                    List <double>  ratio      = new List <double>();
                    int            pixelCount = 0;
                    Bitmap         Destimg    = new Bitmap(pictureBox2.Image);
                    GrayscaleBT709 go         = new GrayscaleBT709();
                    pictureBox2.Image = go.Apply((Bitmap)pictureBox2.Image);
                    Destimg           = go.Apply(Destimg);
                    CannyEdgeDetector filter2 = new CannyEdgeDetector(0, 0, 1.4);
                    pictureBox2.Image = filter2.Apply((Bitmap)pictureBox2.Image);
                    Destimg           = filter2.Apply(Destimg);


                    var imgarray = new System.Drawing.Image[36];

                    for (int i = 0; i < 6; i++)
                    {
                        for (int j = 0; j < 6; j++)
                        {
                            pixelCount++;
                            var index = i * 6 + j;
                            imgarray[index] = new Bitmap(40, 40);
                            var graphics = Graphics.FromImage(imgarray[index]);
                            graphics.DrawImage(Destimg, new Rectangle(0, 0, 40, 40), new Rectangle(i * 40, j * 40, 40, 40), GraphicsUnit.Pixel);
                            graphics.Dispose();
                        }
                    }

                    for (int n = 0; n < 36; n++)
                    {
                        int counter = 0;


                        Bitmap bufferImage = new Bitmap(imgarray[n]);
                        for (int i = 0; i < 40; i++)
                        {
                            for (int j = 0; j < 40; j++)
                            {
                                System.Drawing.Color hoefColor = bufferImage.GetPixel(i, j);
                                //if(hoefColor.R<=255 && hoefColor.R>=230 && hoefColor.G <= 255 && hoefColor.G >= 230 && hoefColor.B <= 255 && hoefColor.B >= 230)
                                if (!(hoefColor.R == 0 && hoefColor.G == 0 && hoefColor.B == 0))
                                {
                                    counter++;
                                }
                            }
                        }

                        edgeCount.Add(counter);
                    }

                    double total = edgeCount.Sum();
                    foreach (double x in edgeCount)
                    {
                        var a = (float)x / total;
                        ratio.Add(a);
                    }

                    FileStream   fs = new FileStream(@"D:\AI.txt", FileMode.Append, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);


                    sw.Write((no) + " ");
                    for (int i = 0; i < ratio.Count; ++i)
                    {
                        sw.Write(i + ":" + ratio[i].ToString() + " ");
                    }
                    sw.WriteLine();
                    sw.Close();
                    fs.Close();

                    Problem train = Problem.Read(@"D:\AI.txt");
                    Problem test  = Problem.Read(@"D:\test.txt");

                    Parameter parameters = new Parameter();

                    double C;
                    double Gamma;

                    parameters.C = 32; parameters.Gamma = 8;
                    Model model = Training.Train(train, parameters);
                    Prediction.Predict(test, @"D:\result.txt", model, false);
                }
            }
        }
Ejemplo n.º 10
0
        // Process new frame
        public void ProcessFrame(ref Bitmap image)
        {
            if (backgroundFrame == null)
            {
                // create initial backgroung image
                backgroundFrame = processingFilter1.Apply(image);

                // get image dimension
                width  = image.Width;
                height = image.Height;

                // just return for the first time
                return;
            }

            Bitmap tmpImage;

            // apply the the first filters sequence
            tmpImage = processingFilter1.Apply(image);

            if (++counter == 2)
            {
                counter = 0;

                // move background towards current frame
                moveTowardsFilter.OverlayImage = tmpImage;
                moveTowardsFilter.ApplyInPlace(backgroundFrame);
            }

            // set backgroud frame as an overlay for difference filter
            differenceFilter.OverlayImage = backgroundFrame;

            // lock temporary image to apply several filters
            bitmapData = tmpImage.LockBits(new Rectangle(0, 0, width, height),
                                           ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

            // apply difference filter
            differenceFilter.ApplyInPlace(bitmapData);
            // apply threshold filter
            thresholdFilter.ApplyInPlace(bitmapData);
            // apply dilatation filter
            Bitmap tmpImage2 = dilatationFilter.Apply(bitmapData);

            // unlock temporary image
            tmpImage.UnlockBits(bitmapData);
            tmpImage.Dispose( );

            // calculate amount of changed pixels
            pixelsChanged = (calculateMotionLevel) ?
                            CalculateWhitePixels(tmpImage2) : 0;

            // find edges
            Bitmap tmpImage2b = edgesFilter.Apply(tmpImage2);

            tmpImage2.Dispose( );

            // extract red channel from the original image
            Bitmap redChannel = extrachChannel.Apply(image);

            //  merge red channel with moving object borders
            mergeFilter.OverlayImage = tmpImage2b;
            Bitmap tmpImage3 = mergeFilter.Apply(redChannel);

            redChannel.Dispose( );
            tmpImage2b.Dispose( );

            // replace red channel in the original image
            replaceChannel.ChannelImage = tmpImage3;
            Bitmap tmpImage4 = replaceChannel.Apply(image);

            tmpImage3.Dispose( );

            image.Dispose( );
            image = tmpImage4;
        }
Ejemplo n.º 11
0
        public override Bitmap ApplyFilter(List <Bitmap> bitmap)
        {
            Dilatation filter = new Dilatation(Matrix);

            return(filter.Apply(bitmap[0]));
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (FinalFrame.IsRunning == true)
            {
                pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
            }
            Bitmap     InputImage = (Bitmap)pictureBox2.Image;
            Rectangle  Tile       = new Rectangle(0, 0, InputImage.Width, InputImage.Height);
            BitmapData bitmapdata = InputImage.LockBits(Tile, ImageLockMode.ReadWrite, InputImage.PixelFormat);
            int        formatsize = Bitmap.GetPixelFormatSize(bitmapdata.PixelFormat) / 8;
            var        tempreg    = new byte[bitmapdata.Width * bitmapdata.Height * formatsize];

            Marshal.Copy(bitmapdata.Scan0, tempreg, 0, tempreg.Length);

            System.Threading.Tasks.Parallel.Invoke(
                () =>
            {
                multithread1(tempreg, 0, 0, bitmapdata.Width / 2, bitmapdata.Height / 2, bitmapdata.Width, formatsize);
            },
                () =>
            {
                multithread1(tempreg, 0, bitmapdata.Height / 2, bitmapdata.Width / 2, bitmapdata.Height, bitmapdata.Width, formatsize);
            },
                () =>
            {
                multithread1(tempreg, bitmapdata.Width / 2, 0, bitmapdata.Width, bitmapdata.Height / 2, bitmapdata.Width, formatsize);
            },
                () =>
            {
                multithread1(tempreg, bitmapdata.Width / 2, bitmapdata.Height / 2, bitmapdata.Width, bitmapdata.Height, bitmapdata.Width, formatsize);
            }
                );

            Marshal.Copy(tempreg, 0, bitmapdata.Scan0, tempreg.Length);
            InputImage.UnlockBits(bitmapdata);

            Grayscale  grayfilter   = new Grayscale(0.2125, 0.7154, 0.0721);//GrayscaleBT709 grayfilter=new GrayscaleBT709();
            Dilatation dilatefilter = new Dilatation();
            Erosion    erodefilter  = new Erosion();

            InputImage = grayfilter.Apply((Bitmap)InputImage);
            InputImage = dilatefilter.Apply((Bitmap)InputImage);
            InputImage = erodefilter.Apply((Bitmap)InputImage);
            //Opening openfilter = new Opening();
            //InputImage=openfilter.Apply((Bitmap)InputImage);
            //Closing closefilter = new Closing();
            //InputImage=closefilter.Apply((Bitmap)InputImage);

            ExtractBiggestBlob blob = new ExtractBiggestBlob();

            InputImage = blob.Apply(InputImage);
            int cordx = blob.BlobPosition.X;
            int cordy = blob.BlobPosition.Y;

            Bitmap source               = new Bitmap(pictureBox1.Image);
            Bitmap destination          = new Bitmap(InputImage);
            var    sourcerectangle      = new Rectangle(0, 0, source.Width, source.Height);
            var    destinationrectangle = new Rectangle(0, 0, destination.Width, destination.Height);
            var    sourcedata           = source.LockBits(sourcerectangle, ImageLockMode.ReadWrite, source.PixelFormat);
            var    destinationdata      = destination.LockBits(destinationrectangle, ImageLockMode.ReadWrite, destination.PixelFormat);
            var    sourcedepth          = Bitmap.GetPixelFormatSize(sourcedata.PixelFormat) / 8;
            var    destinationdepth     = Bitmap.GetPixelFormatSize(destinationdata.PixelFormat) / 8;
            var    source1              = new byte[sourcedata.Width * sourcedata.Height * sourcedepth];
            var    destination1         = new byte[destinationdata.Width * destinationdata.Height * destinationdepth];

            Marshal.Copy(sourcedata.Scan0, source1, 0, source1.Length);
            Marshal.Copy(destinationdata.Scan0, destination1, 0, destination1.Length);

            System.Threading.Tasks.Parallel.Invoke(
                () =>
            {
                multithread2(source1, destination1, cordx, 0, cordy, 0, cordx + (destinationdata.Width / 2), destinationdata.Width / 2, cordy + (destinationdata.Height / 2), destinationdata.Height / 2, sourcedata.Width, destinationdata.Width, sourcedepth, destinationdepth);
            },
                () =>
            {
                multithread2(source1, destination1, cordx + (destinationdata.Width / 2), destinationdata.Width / 2, cordy, 0, cordx + (destinationdata.Width), destinationdata.Width, cordy + (destinationdata.Height / 2), destinationdata.Height / 2, sourcedata.Width, destinationdata.Width, sourcedepth, destinationdepth);
            },
                () =>
            {
                multithread2(source1, destination1, cordx, 0, cordy + (destinationdata.Height / 2), destinationdata.Height / 2, cordx + (destinationdata.Width / 2), destinationdata.Width / 2, cordy + (destinationdata.Height), destinationdata.Height, sourcedata.Width, destinationdata.Width, sourcedepth, destinationdepth);
            },
                () =>
            {
                multithread2(source1, destination1, cordx + (destinationdata.Width / 2), destinationdata.Width / 2, cordy + (destinationdata.Height / 2), destinationdata.Height / 2, cordx + (destinationdata.Width), destinationdata.Width, cordy + (destinationdata.Height), destinationdata.Height, sourcedata.Width, destinationdata.Width, sourcedepth, destinationdepth);
            }
                );

            Marshal.Copy(source1, 0, sourcedata.Scan0, source1.Length);
            Marshal.Copy(destination1, 0, destinationdata.Scan0, destination1.Length);
            source.UnlockBits(sourcedata);
            destination.UnlockBits(destinationdata);
            InputImage = destination;

            InputImage = grayfilter.Apply((Bitmap)InputImage);
            CannyEdgeDetector edgesoutline = new CannyEdgeDetector();

            InputImage        = edgesoutline.Apply(InputImage);
            pictureBox2.Image = InputImage;

            Bitmap blocks = new Bitmap(InputImage);

            int[]    numofedges = new int[100];
            double[] normalized = new double[400];
            String   alphabet   = null;
            int      total      = 0;
            int      sq         = 1;

            for (int p = 1; p <= 8; p++)
            {
                for (int q = 1; q <= 8; q++)
                {
                    for (int x = (p - 1) * blocks.Width / 8; x < (p * blocks.Width / 8); x++)
                    {
                        for (int y = (q - 1) * blocks.Height / 8; y < (q * blocks.Height / 8); y++)
                        {
                            Color colorPixel = blocks.GetPixel(x, y);

                            int r = colorPixel.R;
                            int g = colorPixel.G;
                            int b = colorPixel.B;

                            if (r != 0 & g != 0 & b != 0)
                            {
                                numofedges[sq]++;
                            }
                        }
                    }
                    sq++;
                }
            }

            for (sq = 1; sq <= 64; sq++)
            {
                total = total + numofedges[sq];
            }
            for (sq = 1; sq <= 64; sq++)
            {
                normalized[sq] = (double)numofedges[sq] / total;
                alphabet       = alphabet + " " + sq.ToString() + ":" + normalized[sq].ToString();
            }
            File.WriteAllText(@"datasets\testalpha.txt", label.ToString() + alphabet + Environment.NewLine);

            Problem   train     = Problem.Read(@"datasets\trainedset.txt");
            Problem   test      = Problem.Read(@"datasets\testalpha.txt");
            Parameter parameter = new Parameter();

            parameter.C     = 32;
            parameter.Gamma = 8;
            Model model = Training.Train(train, parameter);

            Prediction.Predict(test, @"datasets\result.txt", model, false);
            int    value = Convert.ToInt32(File.ReadAllText(@"datasets\result.txt"));
            String res   = null;

            res         = res + (char)(value + 65);
            label1.Text = res;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
            Bitmap         src        = new Bitmap(pictureBox2.Image);
            Bitmap         res        = new Bitmap(pictureBox2.Image);
            SaveFileDialog saveDialog = new SaveFileDialog();

            src = resize(src, new Size(200, 200));
            res = resize(res, new Size(200, 200));
            pictureBox2.Image = src;
            srcImg            = src;
            pictureBox2.Image = res;
            Bitmap sampleImage = new Bitmap(pictureBox2.Image);
            var    rect        = new Rectangle(0, 0, sampleImage.Width, sampleImage.Height);
            var    data        = sampleImage.LockBits(rect, ImageLockMode.ReadWrite, sampleImage.PixelFormat);
            var    depth       = Bitmap.GetPixelFormatSize(data.PixelFormat) / 8; //bytes per pixel

            var buffer = new byte[data.Width * data.Height * depth];

            //copy pixels to buffer
            Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);

            System.Threading.Tasks.Parallel.Invoke(
                () =>
            {
                //upper-left
                Process(buffer, 0, 0, data.Width / 2, data.Height / 2, data.Width, depth);
            },
                () =>
            {
                //upper-right
                Process(buffer, data.Width / 2, 0, data.Width, data.Height / 2, data.Width, depth);
            },
                () =>
            {
                //lower-left
                Process(buffer, 0, data.Height / 2, data.Width / 2, data.Height, data.Width, depth);
            },
                () =>
            {
                //lower-right
                Process(buffer, data.Width / 2, data.Height / 2, data.Width, data.Height, data.Width, depth);
            }
                );

            //Copy the buffer back to image
            Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);

            sampleImage.UnlockBits(data);
            pictureBox2.Image = sampleImage;
            dstImg            = sampleImage;
            void Process(byte[] buffer1, int x, int y, int endx, int endy, int width, int depth1)
            {
                for (int i = x; i < endx; i++)
                {
                    for (int j = y; j < endy; j++)
                    {
                        var offset = ((j * width) + i) * depth;
                        var B      = buffer[offset + 0];
                        var G      = buffer[offset + 1];
                        var R      = buffer[offset + 2];
                        var a      = Math.Max(R, Math.Max(B, G));
                        var b      = Math.Min(R, Math.Min(B, G));
                        if (!(((R > 95) && (G > 40) && (B > 20) && ((a - b) > 15) && (Math.Abs(R - G) > 15) && (R > G) && (R > B)) || ((R > 220) && (G > 210) && (B > 170) && ((a - b) > 15) && (Math.Abs(R - G) > 15) && (R > G) && (G > B))))
                        {
                            buffer[offset + 0] = buffer[offset + 1] = buffer[offset + 2] = 0;
                        }
                        else
                        {
                            buffer[offset + 0] = buffer[offset + 1] = buffer[offset + 2] = 255;
                        }
                    }
                }
            }

            //Graysacle
            GrayscaleBT709 filter = new GrayscaleBT709();

            pictureBox2.Image = filter.Apply((Bitmap)pictureBox2.Image);
            dstImg            = filter.Apply(dstImg);
            //Dilatation
            try
            {
                Dilatation filter1 = new Dilatation();
                pictureBox2.Image = filter1.Apply((Bitmap)pictureBox2.Image);
                dstImg            = filter1.Apply(dstImg);
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("Apply Grayscale");
            }
            //Biggest Blob Extraction
            ExtractBiggestBlob filter2 = new ExtractBiggestBlob();

            pictureBox2.Image = filter2.Apply((Bitmap)pictureBox2.Image);
            dstImg            = filter2.Apply(dstImg);
            blob = filter2.BlobPosition;
            Bitmap newBmp = new Bitmap(dstImg.Width, dstImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (Graphics gfx = Graphics.FromImage(newBmp))
            {
                gfx.DrawImage(dstImg, 0, 0);
            }
            //newBmp = dstImg;
            for (int i = 0; i < dstImg.Width; i++)
            {
                for (int j = 0; j < dstImg.Height; j++)
                {
                    System.Drawing.Color srcColor = srcImg.GetPixel(i + blob.X, j + blob.Y);
                    System.Drawing.Color dstColor = dstImg.GetPixel(i, j);
                    if (!(dstColor.R >= 0 && dstColor.R <= 10 && dstColor.G >= 0 && dstColor.G <= 10 && dstColor.B >= 0 && dstColor.B <= 10))
                    {
                        newBmp.SetPixel(i, j, srcColor);
                    }
                }
            }
            dstImg            = newBmp;
            pictureBox2.Image = newBmp;

            List <double> edgeCount  = new List <double>();
            List <double> ratio      = new List <double>();
            int           pixelCount = 0;

            Bitmap         hoefImage  = new Bitmap(pictureBox2.Image);
            GrayscaleBT709 grayFilter = new GrayscaleBT709();

            hoefImage = grayFilter.Apply((Bitmap)pictureBox2.Image);
            CannyEdgeDetector cannyFilter = new CannyEdgeDetector(0, 0, 1.4);

            hoefImage         = cannyFilter.Apply(hoefImage);
            pictureBox2.Image = hoefImage;
            var imgarray = new System.Drawing.Image[36];

            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    pixelCount++;
                    var index = i * 6 + j;
                    imgarray[index] = new Bitmap(40, 40);
                    var graphics = Graphics.FromImage(imgarray[index]);
                    graphics.DrawImage(hoefImage, new Rectangle(0, 0, 40, 40), new Rectangle(i * 40, j * 40, 40, 40), GraphicsUnit.Pixel);
                    graphics.Dispose();
                }
            }
            for (int n = 0; n < 36; n++)
            {
                int    counter     = 0;
                Bitmap bufferImage = new Bitmap(imgarray[n]);
                for (int i = 0; i < 40; i++)
                {
                    for (int j = 0; j < 40; j++)
                    {
                        System.Drawing.Color hoefColor = bufferImage.GetPixel(i, j);
                        if (!(hoefColor.R == 0 && hoefColor.G == 0 && hoefColor.B == 0))
                        {
                            counter++;
                        }
                    }
                }
                edgeCount.Add(counter);
            }
            double Total = edgeCount.Sum();

            foreach (double x in edgeCount)
            {
                var a = x / Total;
                ratio.Add(a);
            }

            FileStream   fs = new FileStream(@"E:\test.txt", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            int          no = 0;

            sw.Write((++no) + " ");
            for (int i = 0; i < ratio.Count; ++i)
            {
                sw.Write(i + ":" + ratio[i].ToString() + " ");
            }
            sw.WriteLine();

            sw.Close();
            fs.Close();
            //Support Vector Machine
            Problem train = Problem.Read(@"E:\AI.txt");
            Problem test  = Problem.Read(@"E:\test.txt");

            Parameter parameters = new Parameter();

            double C;
            double Gamma;

            parameters.C = 32; parameters.Gamma = 8;
            Model model = Training.Train(train, parameters);

            Prediction.Predict(test, @"E:\result.txt", model, false);

            FileStream   fs1 = new FileStream(@"E:\result.txt", FileMode.Open, FileAccess.Read);
            StreamReader sw1 = new StreamReader(fs1);
            string       w   = sw1.ReadLine();

            if (w == "1")
            {
                MessageBox.Show("A");
            }
            else if (w == "2")
            {
                MessageBox.Show("B");
            }
            else if (w == "3")
            {
                MessageBox.Show("C");
            }
            else if (w == "4")
            {
                MessageBox.Show("D");
            }
            else if (w == "5")
            {
                MessageBox.Show("E");
            }
            else if (w == "6")
            {
                MessageBox.Show("F");
            }
            else if (w == "7")
            {
                MessageBox.Show("G");
            }
            else if (w == "8")
            {
                MessageBox.Show("H");
            }
            else if (w == "9")
            {
                MessageBox.Show("I");
            }
            else if (w == "10")
            {
                MessageBox.Show("J");
            }
            else if (w == "11")
            {
                MessageBox.Show("K");
            }
            //else { MessageBox.Show("L"); }
        }
Ejemplo n.º 14
0
        //! @copydoc IMotionDetector::ProcessFrame(ref Bitmap,ref Bitmap)
        public void ProcessFrame(ref Bitmap image, ref Bitmap player)
        {
            if (lastProcessedImageTime + processImageInterval > DateTime.UtcNow)
            {
                return;
            }


            if (backgroundFrame == null)
            {
                // create initial backgroung image
                backgroundFrame = processingFilter1.Apply(image);

                backgroundPlayerFrame = processingFilter1.Apply(player);

                // get image dimension
                width  = image.Width;
                height = image.Height;

                // just return for the first time
                return;
            }

            Bitmap tmpImage;

            // apply the the first filters sequence
            tmpImage = processingFilter1.Apply(image);

            // set backgroud frame as an overlay for difference filter
            differenceFilter.OverlayImage = backgroundFrame;

            //actualizar o backgroud
            backgroundFrame = tmpImage.Clone(new Rectangle(0, 0, width, height), PixelFormat.Format8bppIndexed);

            // lock temporary image to apply several filters
            bitmapData = tmpImage.LockBits(new Rectangle(0, 0, width, height),
                                           ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

            // apply difference filter
            differenceFilter.ApplyInPlace(bitmapData);
            // apply threshold filter
            thresholdFilter.ApplyInPlace(bitmapData);
            // apply dilatation filter
            Bitmap tmpImage2 = dilatationFilter.Apply(bitmapData);

            // unlock temporary image
            tmpImage.UnlockBits(bitmapData);
            tmpImage.Dispose();

            Bitmap playerProccessed = processingFilter1.Apply(player);
            Add    addFilter        = new Add(playerProccessed);
            Bitmap tmpPlayer        = addFilter.Apply(backgroundPlayerFrame);

            // calculate amount of changed pixels
            pixelsChanged = CalculateWhitePixels(tmpImage2, tmpPlayer);

            if (MotionLevel >= alarmLevel)
            {
                if (MotionDetected != null)
                {
                    MotionDetected(this, EventArgs.Empty);
                }
            }

            tmpImage2.Dispose();
            tmpPlayer.Dispose();
            backgroundPlayerFrame = playerProccessed;
            //image = backgroundPlayerFrame;

            lastProcessedImageTime = DateTime.UtcNow;
        }
Ejemplo n.º 15
0
        public static Bitmap SmoothingFilter(this Bitmap sourceBitmap, MainForm form,
                                             SmoothingFilterType smoothFilter =
                                             SmoothingFilterType.Nenhum)
        {
            Bitmap inputBitmap = null;

            //Progress bar
            form.algorithmProgress = 0;

            switch (smoothFilter)
            {
            case SmoothingFilterType.Nenhum:
            {
                inputBitmap = sourceBitmap;
            } break;

            case SmoothingFilterType.Gaussiano3x3:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Gaussian3x3, 1.0 / 16.0, 0);
            } break;

            case SmoothingFilterType.Gaussiano5x5:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Gaussian5x5, 1.0 / 159.0, 0);
            } break;

            case SmoothingFilterType.Gaussiano7x7:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Gaussian7x7, 1.0 / 136.0, 0);
            } break;

            case SmoothingFilterType.Mediano3x3:
            {
                inputBitmap = sourceBitmap.MedianFilter(3);
            } break;

            case SmoothingFilterType.Mediano5x5:
            {
                inputBitmap = sourceBitmap.MedianFilter(5);
            } break;

            case SmoothingFilterType.Mediano7x7:
            {
                inputBitmap = sourceBitmap.MedianFilter(7);
            } break;

            case SmoothingFilterType.Mediano9x9:
            {
                inputBitmap = sourceBitmap.MedianFilter(9);
            } break;

            case SmoothingFilterType.Mean3x3:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Mean3x3, 1.0 / 9.0, 0);
            } break;

            case SmoothingFilterType.Mean5x5:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Mean5x5, 1.0 / 25.0, 0);
            } break;

            case SmoothingFilterType.LowPass3x3:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.LowPass3x3, 1.0 / 16.0, 0);
            } break;

            case SmoothingFilterType.LowPass5x5:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.LowPass5x5, 1.0 / 60.0, 0);
            } break;

            case SmoothingFilterType.Sharpen3x3:
            {
                inputBitmap = sourceBitmap.ConvolutionFilter(
                    Matrix.Sharpen3x3, 1.0 / 8.0, 0);
            } break;
            }

            //Progress bar
            form.algorithmProgress = 20;


            // START additional filters ADDED BY GABRIEL
            inputBitmap = AForge.Imaging.Image.Clone(inputBitmap, PixelFormat.Format24bppRgb); //Accepted format
            Bilateral           filterB = new Bilateral();
            Grayscale           filterG = new Grayscale(0.2125, 0.7154, 0.0721);               //arbitrary values
            CannyEdgeDetector   filterE = new CannyEdgeDetector();
            ColorImageQuantizer filterC = new ColorImageQuantizer(new MedianCutQuantizer());
            Dilatation          filterD = new Dilatation();

            //Bilateral filter as present in the article
            filterB.KernelSize    = form.kernelValue;
            filterB.SpatialFactor = form.spatialFactor;
            filterB.ColorFactor   = form.colorFactor;
            filterB.ColorPower    = form.colorPower;
            filterB.ApplyInPlace(inputBitmap);

            form.algorithmProgress = 40;

            /* GENERATING BORDERS */
            //Generate a grayscale version for edge detection
            Bitmap edges = filterG.Apply(inputBitmap);

            filterE.HighThreshold = form.highThreshold;
            filterE.LowThreshold  = form.lowThreshold;
            filterE.ApplyInPlace(edges); // a new image, edges, is created here defining the edges of inputBitmap
            //Dilatation filter
            edges = filterD.Apply(edges);
            generateBorder(edges);
            //Making bg transparent
            edges.MakeTransparent(Color.White);


            form.algorithmProgress = 70;


            // Color reduction as present in the article
            inputBitmap = filterC.ReduceColors(inputBitmap, form.colorReductionFactor);         // reduces to 24 variation

            inputBitmap = AForge.Imaging.Image.Clone(inputBitmap, PixelFormat.Format32bppArgb); //Accepted format

            // images merge
            Bitmap   bitmapResult = new Bitmap(inputBitmap.Width, inputBitmap.Height, inputBitmap.PixelFormat);
            Graphics g            = Graphics.FromImage(bitmapResult);

            g.DrawImage(inputBitmap, 0, 0, inputBitmap.Width, inputBitmap.Height);
            g.DrawImage(edges, 0, 0, inputBitmap.Width, inputBitmap.Height);
            // END additional filters ADDED BY GABRIEL

            form.algorithmProgress = 100;

            return(bitmapResult); // it was returning input Bitmap before
        }