Threshold binarization
Inheritance: IFilter
Example #1
1
        private void cBFilters_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bitmap pictureTransform = (Bitmap)pbChoose.Image;
                if ((string)cBFilters.SelectedItem == "HSL_Filter")
                {
                    AForge.Imaging.Filters.SaturationCorrection filter = new SaturationCorrection(0.1);
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Mediana")
                {
                    AForge.Imaging.Filters.Median filter = new Median();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                /*if ((string)cBFilters.SelectedItem == "Fourier_Transformation")
                {
                 Complex[] dst = new Complex[n];

                    AForge.Math.FourierTransform filter = AForge.Math.FourierTransform.DFT();// .FromBitmap(pictureTransform);
                    Bitmap newImage = filter.Apply();
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }*/

                if ((string)cBFilters.SelectedItem == "Binarization")
                {
                    pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                    Threshold threshold = new Threshold(127);
                    threshold.ApplyInPlace(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = pictureTransform;
                }

                if ((string)cBFilters.SelectedItem == "Grayscale")
                {
                    AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "FillHoles")
                {

                    pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                    Threshold threshold = new Threshold(127);
                    threshold.ApplyInPlace(pictureTransform);
                    AForge.Imaging.Filters.FillHoles filter = new AForge.Imaging.Filters.FillHoles();
                    filter.MaxHoleHeight = 5;
                    filter.MaxHoleWidth = 15;
                    filter.CoupledSizeFiltering = false;
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Opening")
                {
                    AForge.Imaging.Filters.Opening filter = new AForge.Imaging.Filters.Opening();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Closing")
                {
                    AForge.Imaging.Filters.Closing filter = new AForge.Imaging.Filters.Closing();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Erosion")
                {
                    AForge.Imaging.Filters.Erosion filter = new AForge.Imaging.Filters.Erosion();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Dilatation")
                {
                    AForge.Imaging.Filters.Dilatation filter = new AForge.Imaging.Filters.Dilatation();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Edges")
                {
                    AForge.Imaging.Filters.Edges filter = new AForge.Imaging.Filters.Edges();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }
        }
        public VideoProcessor()
        {
            background = null;

            pixelateFilter = new Pixellate();
            pixelateFilter.PixelSize = 10;

            differenceFilter = new Difference();
            thresholdFilter = new Threshold(15);
            grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            erosionFilter = new Erosion();

            moveTowardsFilter = new MoveTowards();

            filters1 = new FiltersSequence();
            filters1.Add(pixelateFilter);
            filters1.Add(grayscaleFilter);

            filters2 = new FiltersSequence();

            filters2.Add(differenceFilter);
            filters2.Add(thresholdFilter);
            filters2.Add(erosionFilter);

            rat1 = new Tracker(640 / 2, 480 / 2, Color.Red);

            rat2 = new Tracker(400, 300, Color.Green);

            counter = 0;
        }
Example #3
0
        public static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Parameter missing: Path to picture");
                return 1;
            }

            var inputImagePath = args[0];
            var blackTreshold = (args.Length >= 2) ? byte.Parse(args[1]) : (byte.MaxValue / 2);
            var backgroundTreshold = (args.Length >= 3) ? byte.Parse(args[2]) : (byte?)null;

            var inputImage = Image.FromFile(inputImagePath);
            var workingDir = Path.GetDirectoryName(inputImagePath) ?? Directory.GetCurrentDirectory();
            var fileName = Path.GetFileNameWithoutExtension(inputImagePath);

            // Generate grayscale
            var grayscaleImage = Grayscale.CommonAlgorithms.BT709.Apply(inputImage);
            grayscaleImage.Save(Path.Combine(workingDir, string.Format("{0}.{1}.png", fileName, "gray")), ImageFormat.Png);

            // Generate monochrome
            var monochromeImage = new Threshold(blackTreshold).Apply(grayscaleImage);
            monochromeImage.Save(Path.Combine(workingDir, string.Format("{0}.{1}.{2}.png", fileName, "mono", blackTreshold)), ImageFormat.Png);

            // Generate labeled image (using custom algorithm)
            var result = new ConnectedComponentsAlgorithm().Apply(monochromeImage, backgroundTreshold);
            result.Bitmap.Save(Path.Combine(workingDir, string.Format("{0}.{1}.{2}.png", fileName, "blobs", blackTreshold)), ImageFormat.Png);
            Console.WriteLine("My algorithm counted {0} blobs.", result.BlobCount);

            return 0;
        }
Example #4
0
 public BitmapSource Apply(BitmapSource image)
 {
     var grayScale = ToGrayScale(image);
     var filter = new Threshold(factor);
     var bmp = filter.Apply(grayScale);
     return bmp.ToBitmapImage();
 }
Example #5
0
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     pictureBox1.Image = new Bitmap(Bitmap.FromFile("C:\\testimg\\" +comboBox1.SelectedIndex + ".png"), pictureBox1.Size);
     Bitmap channel = selected.Apply((Bitmap)pictureBox1.Image);
     thresholdFilter = new Threshold(Int32.Parse(textBox1.Text));
     thresholdFilter.ApplyInPlace(channel);
     pictureBox2.Image = channel;
     pictureBox3.Image = brownFilter.Apply((Bitmap)pictureBox1.Image);
 }
 private Bitmap binarizationImage(Bitmap image)
 {
     Grayscale filterGrayscale = Grayscale.CommonAlgorithms.BT709;
     //Grayscale filterGrayscale = new Grayscale(0.5, 0.419, 0.081); // R-Y
     Bitmap grayImage = filterGrayscale.Apply(image);
     Threshold filter = new Threshold(200);
     filter.ApplyInPlace(grayImage);
     return doBlackAndWhiteImage(grayImage);
 }
Example #7
0
 public ColorFilter()
 {
     this.applyFilters = false;
     this.colorFilter = new YCbCrFiltering();
     this.grayFilter = new GrayscaleRMY();
     this.binaryFilter = new Threshold(1);
     this.erosionFilter = new BinaryErosion3x3();
     this.rgbFilter = new GrayscaleToRGB();
 }
Example #8
0
File: Form1.cs Project: bdus/AForge
        private void button2_Click(object sender, EventArgs e)
        {
            Bitmap b = new Bitmap(pictureBox2.Image);
            //            b = new Grayscale(0.7, 0.2, 0.1).Apply(b);
            b = new Grayscale(0.299, 0.587, 0.114).Apply(b);

            b = new Threshold(50).Apply(b);

            this.pictureBox2.Image = b;
        }
Example #9
0
        static DiffCalculator()
        {
            threshold = new Threshold(THERSHOLD);
            fillHoles = new FillHoles();
            fillHoles.MaxHoleHeight = 125;
            fillHoles.MaxHoleWidth = 125;
            fillHoles.CoupledSizeFiltering = true;

            gaussianBlur = new GaussianBlur(3, 11);
        }
Example #10
0
 private Bitmap filter()
 {
     Bitmap filtered_image;
     AForge.Imaging.Filters.Grayscale gr = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
     AForge.Imaging.Filters.Threshold th = new AForge.Imaging.Filters.Threshold(100);
     AForge.Imaging.Filters.Invert invert = new AForge.Imaging.Filters.Invert();
     filtered_image = gr.Apply(scanned_image);
     filtered_image = invert.Apply(filtered_image);
     filtered_image = th.Apply(filtered_image);
     return filtered_image;
 }
Example #11
0
        private Bitmap filter()
        {
            Bitmap filtered_image;

            AForge.Imaging.Filters.Grayscale gr     = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
            AForge.Imaging.Filters.Threshold th     = new AForge.Imaging.Filters.Threshold(100);
            AForge.Imaging.Filters.Invert    invert = new AForge.Imaging.Filters.Invert();
            filtered_image = gr.Apply(scanned_image);
            filtered_image = invert.Apply(filtered_image);
            filtered_image = th.Apply(filtered_image);
            return(filtered_image);
        }
 public static Bitmap ApplyBinarization(Bitmap pBitmap)
 {
     var colourDepth = pBitmap.PixelFormat;
     Bitmap bitmap;
     if (colourDepth == PixelFormat.Format16bppGrayScale)
     {
         Threshold filter = new Threshold(200);
         return filter.Apply(pBitmap);
     }
     else
     {
         Threshold filter = new Threshold(30);
         return filter.Apply(pBitmap);
     }
 }
Example #13
0
        public Bitmap process(Bitmap bmp)
        {
            Bitmap newImage = (Bitmap)bmp.Clone();

            newImage = new AForge.Imaging.Filters.GrayscaleY().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Threshold(50).Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Dilatation().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Erosion().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Erosion().Apply(newImage);

            return(newImage);
        }
Example #14
0
        public static FoundBlobs FindAny(FoundColorSpaces colorSpaces)
        {
            FoundBlobs foundBlobs = new FoundBlobs();

            SobelEdgeDetector edge = new SobelEdgeDetector();
            Bitmap edges = edge.Apply(colorSpaces.GrayColorSpace);

            Threshold threshold = new Threshold(50);
            threshold.ApplyInPlace(edges);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.ProcessImage(edges);
            foundBlobs.Blobs = blobCounter.GetObjects(colorSpaces.GrayColorSpace, false).ToArray();

            foundBlobs.BlobCounter = blobCounter;

            return foundBlobs;
        }
        public double GetTemperature()
        {
            var temp = 0.0;

            var image = Image.FromFile(filename);

            var grayscale = new Grayscale(0.2125, 0.7154, 0.0721);
            image = grayscale.Apply(image);

            var invert = new Invert();
            image = invert.Apply(image);

            var stats = new ImageStatistics(image);
            var levelsLinear = new LevelsLinear
            {
                InGray = stats.Gray.GetRange(2.90)
            };

            image = levelsLinear.Apply(image);

            var contrast = new ContrastStretch();
            image = contrast.Apply(image);

            var erosion = new Erosion();
            image = erosion.Apply(image);

            var blur = new GaussianBlur(2, 3);
            image = blur.Apply(image);

            var threshold = new Threshold(79);
            image = threshold.Apply(image);

            image.Save(processedFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            image.Dispose();
            var text = Recognise();

            double.TryParse(text.Replace(',', '.'), out temp);

            return temp;
        }
Example #16
0
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox2.SelectedIndex)
            {
                case 0:
                    selected = redFilter;
                    break;
                case 1:
                    selected = greenFilter;
                    break;
                case 2:
                    selected = blueFilter;
                    break;
                default:
                    break;

            }
            Bitmap channel = selected.Apply((Bitmap)pictureBox1.Image);
            thresholdFilter = new Threshold(Int32.Parse(textBox1.Text));
            thresholdFilter.ApplyInPlace(channel);
            pictureBox2.Image = channel;
        }
Example #17
0
        // Process image
        private void ProcessImage(Bitmap bitmap)
        {
            // create filter
            HistogramEqualization hisFilter = new HistogramEqualization();
            // process image
            //hisFilter.ApplyInPlace(Image);

            // create filter
            ContrastCorrection contrastFilter = new ContrastCorrection(4);
            // apply the filter
            contrastFilter.ApplyInPlace(bitmap);

            //QuantizeImage(bitmap);

            Grayscale grayscaleFilter = new Grayscale(0.33, 0.33, 0.34);
            // apply the filter
            Bitmap grayImage = grayscaleFilter.Apply(bitmap);

            // create filter
            SobelEdgeDetector sobelFilter = new SobelEdgeDetector();
            // apply the filter
            sobelFilter.ApplyInPlace(grayImage);
            Threshold filter = new Threshold(110);
            // apply the filter
            filter.ApplyInPlace(grayImage);

            if (GetIntersect(grayImage, bitmap, intersectPoint)) {
                //MessageBox.Show("draw");
                Graphics g = Graphics.FromImage(bitmap);
                //Sorting

                for (int i = 0; i < 19; i++)
                {
                    for (int j = 0; j < 19; j++)
                    {
                        for (int k = 0; k < 19 - 1; k++)
                        {
                            if (Math.Abs(intersectPoint[1, i, k]) > Math.Abs(intersectPoint[1, i, k + 1]))
                            {
                                int tempX = Math.Abs(intersectPoint[0, i, k]);
                                int tempY = Math.Abs(intersectPoint[1, i, k]);
                                intersectPoint[0, i, k] = Math.Abs(intersectPoint[0, i, k + 1]);
                                intersectPoint[1, i, k] = Math.Abs(intersectPoint[1, i, k + 1]);
                                intersectPoint[0, i, k + 1] = tempX;
                                intersectPoint[1, i, k + 1] = tempY;
                                //MessageBox.Show(i + " " + k +" " +tempX + " " + tempY + " " + intersectPoint[0, i, k] + " " + intersectPoint[1, i, k] ,"ok", MessageBoxButtons.OK);
                            }
                        }
                    }
                }

                for (int i = 0; i < 19; i++)
                {
                    for (int j = 0; j < 19; j++)
                    {
                        for (int k = 0; k < 19 - 1; k++)
                        {
                            if (Math.Abs(intersectPoint[0, k, i]) > Math.Abs(intersectPoint[0, k + 1, i]))
                            {
                                int tempX = Math.Abs(intersectPoint[0, k, i]);
                                int tempY = Math.Abs(intersectPoint[1, k, i]);
                                intersectPoint[0, k, i] = intersectPoint[0, k + 1, i];
                                intersectPoint[1, k, i] = intersectPoint[1, k + 1, i];
                                intersectPoint[0, k + 1, i] = tempX;
                                intersectPoint[1, k + 1, i] = tempY;
                            }
                        }
                    }
                }

                Pen redPen = new Pen(Color.Red, 4);
                for (int i = 0; i < 19; i++)
                {
                    for (int j = 0; j < 19; j++)
                    {
                        g.DrawEllipse(redPen, Math.Abs(intersectPoint[0, i, j]) , Math.Abs(intersectPoint[1, i, j]) , (int)5, (int)5);
                        //g.DrawEllipse(redPen, 0, 0, (int)5, (int)5);

                        //Debug.WriteLine((Math.Abs(intersectPoint[0, i, j]) - 2) + " " + (Math.Abs(intersectPoint[1, i, j]) - 2));
                    }
                }

                Pen greenPen = new Pen(Color.Green, 4);

                greenPen.Dispose();
                redPen.Dispose();
                g.Dispose();

                // Initializes the variables to pass to the MessageBox.Show method.
                EspacioCamera.Image = bitmap;
                string message = "Do you accecpt this detection?";
                string caption = "The system found totally 38 lines.";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result;

                // Displays the MessageBox.

                result = MessageBox.Show(message, caption, buttons);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    // Closes the parent form.
                    locked = true;
                }
            }

            EspacioCamera.Image = bitmap;
        }
        public void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            UnmanagedImage image = UnmanagedImage.FromManagedImage((Bitmap) eventArgs.Frame.Clone());

            var extractChannel = new ExtractChannel(RGB.R);
            UnmanagedImage channel = extractChannel.Apply(image);
            //		UnmanagedImage originalRed = channel.Clone();
            if (true) {
                var threshold = new Threshold(200);
                threshold.ApplyInPlace(channel);

                ////filter to convert RGB image to 8bpp gray scale for image processing
                //IFilter gray_filter = new GrayscaleBT709();
                //gray_image = gray_filter.Apply(gray_image);

                ////thresholding a image
                //Threshold th_filter = new Threshold(color_data.threshold);
                //th_filter.ApplyInPlace(gray_image);

                //erosion filter to filter out small unwanted pixels
                Erosion3x3 erosion = new Erosion3x3();
                erosion.ApplyInPlace(channel);

                //dilation filter
                //Dilatation3x3 dilatation = new Dilatation3x3();
                //dilatation.ApplyInPlace(channel);

                //GrayscaleToRGB filter = new GrayscaleToRGB();
                //image = filter.Apply(channel);

                //ReplaceChannel replaceFilter = new ReplaceChannel(RGB.B, channel);
                //replaceFilter.ApplyInPlace(image);
            }

            BlobCounter bc = new BlobCounter();
            //arrange blobs by area
            bc.ObjectsOrder = ObjectsOrder.Area;
            bc.FilterBlobs = true;
            bc.MinHeight = minObjectSize;
            bc.MinWidth = minObjectSize;
            bc.MaxHeight = maxObjectSize;
            bc.MaxWidth = maxObjectSize;

            //process image for blobs
            bc.ProcessImage(channel);
            channel.Dispose();

            //	if (motionDetector.ProcessFrame(image) > 0.02) {
            //	for (int i = 0; i < blobCountingObjectsProcessing.ObjectRectangles.Length; i++) {
            Rectangle[] rectangles = bc.GetObjectsRectangles();
            Blob[] blobs = bc.GetObjectsInformation();
            for (int i = 0; i < bc.ObjectsCount; i++) {
                Rectangle rectangle = rectangles[i];
                int width = rectangle.Width;
                int height = rectangle.Height;

            //		if (width < maxObjectSize && height < maxObjectSize && width > minObjectSize && height > minObjectSize) {
                    Drawing.Rectangle(image, rectangle, colorList[i % colorList.Length]);

                    if (i == 0) {
                        Position = GetCenterOfMass(image, rectangle);
                        Drawing.FillRectangle(image, rectangle, Color.BlanchedAlmond);
                        Drawing.FillRectangle(image, new Rectangle((int) Position.U - dotSize, (int) Position.V - dotSize, dotSize * 3, dotSize * 3), Color.Indigo);
                    }
            //		}
            }
            //	}

            Image = image.ToManagedImage();
            //	videoForm.ImageDestination.Image = image.ToManagedImage();
        }
Example #19
0
        public static Bitmap ApplyFiliter(ImageFiliter imgFilter, Bitmap bmp, byte Value, byte Value2)
        {
            Bitmap newImage = null;
            //ContrastCorrection filter2 = new ContrastCorrection(1.0);
            //newImage = filter2.Apply(bmp);
            if (imgFilter != ImageFiliter.None)
            {
                IFilter filter3 = Grayscale.CommonAlgorithms.Y;
                newImage = filter3.Apply(bmp);

                if (imgFilter == ImageFiliter.Threshold)
                {
                    IFilter filter = null;
                    if (Value == 0) filter = new Threshold();
                    else filter = new Threshold(Value);
                    newImage = filter.Apply(newImage);

                    //IterativeThreshold filter = new IterativeThreshold(Value2, Value);
                    //// apply the filter
                    // newImage = filter.Apply(newImage);
                }
                if (imgFilter == ImageFiliter.ThresholdWithCarry)
                {
                    IFilter filter = new ThresholdWithCarry();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.OrderedDithering)
                {
                    IFilter filter = new OrderedDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.BayerDithering)
                {
                    IFilter filter = new BayerDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.FloydSteinbergDithering)
                {
                    IFilter filter = new FloydSteinbergDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.BurkesDithering)
                {
                    IFilter filter = new BurkesDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.JarvisJudiceNinkeDithering)
                {
                    IFilter filter = new JarvisJudiceNinkeDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.SierraDithering)
                {
                    IFilter filter = new SierraDithering();
                    newImage = filter.Apply(newImage);
                }
                else if (imgFilter == ImageFiliter.StuckiDithering)
                {
                    IFilter filter = new StuckiDithering();
                    newImage = filter.Apply(newImage);

                }
                else if (imgFilter == ImageFiliter.Convolution)
                {
                    // create filter
                    //OtsuThreshold filter = new OtsuThreshold();
                    //// apply the filter
                    //filter.ApplyInPlace(newImage);

                    //// create filter
                    //IterativeThreshold filter = new IterativeThreshold(0);
                    //// apply the filter
                    //newImage = filter.Apply(newImage);

                    int[,] kernel = {
                            { -2, -1,  0 },
                            { -1,  1,  1 },
                            {  0,  1,  2 }
                                };
                    // create filter
                    Convolution filter = new Convolution(kernel);
                    // apply the filter
                    filter.ApplyInPlace(newImage);
                }
                newImage = BitmapTo1Bpp(newImage);
            }
            else newImage = BitmapTo1Bpp(bmp);
            //轉換成 1bit bps
            return newImage;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            IVideoSource videoSource1 = videoSourcePlayer1.VideoSource;
            Bitmap currentVideoFrame = videoSourcePlayer1.GetCurrentVideoFrame();
            pictureBox1.Image = currentVideoFrame;

            if (currentVideoFrame != null)
            {
                Crop filter1 = new Crop(new Rectangle(1, 1, 319, 479));
                Crop filter2 = new Crop(new Rectangle(321, 1, 639, 479));
                Bitmap leftimage = filter1.Apply(currentVideoFrame);
                Bitmap rightimage = filter2.Apply(currentVideoFrame);

                // get grayscale image
                IFilter grayscaleFilter = new GrayscaleRMY();
                leftimage = grayscaleFilter.Apply(leftimage);
                rightimage = grayscaleFilter.Apply(rightimage);

                // apply threshold filter
                Threshold th = new Threshold(trackBar1.Value);
                Bitmap filteredImage1 = th.Apply(leftimage);
                pictureBox2.Image = filteredImage1;
                Bitmap filteredImage2 = th.Apply(rightimage);
                pictureBox3.Image = filteredImage2;
                label6.Text = trackBar1.Value.ToString();

                ImageStatistics lftstat = new ImageStatistics(filteredImage1);
                int lftpxlcntwthoutblck = lftstat.PixelsCountWithoutBlack;
                ImageStatistics rghtstat = new ImageStatistics(filteredImage2);
                int rghtpxlcntwthoutblck = rghtstat.PixelsCountWithoutBlack;

                int val = trackBar1.Value;

                if (((lftpxlcntwthoutblck - rghtpxlcntwthoutblck) > val) || ((rghtpxlcntwthoutblck - lftpxlcntwthoutblck) > val))
                     {
                        if ((lftpxlcntwthoutblck-rghtpxlcntwthoutblck) >val)
                            {
                                //label4.Text = "left";
                                label4.Text = "right";
                             }
                         if ((rghtpxlcntwthoutblck-lftpxlcntwthoutblck) >val)
                            {
                                //label4.Text = "right";
                                label4.Text = "left";
                            }
                     }
                else if ((lftpxlcntwthoutblck == 0) && (rghtpxlcntwthoutblck == 0))
                {
                    label4.Text = "Stop!! No  space ahead";
                }
                else    {
                    label4.Text = "Forward";

                        }

               }
        }
Example #21
0
        /// <summary>
        /// 将采集到的图像进行分型,输出为最后结果
        /// </summary>
        /// <param name="bit"></param>
        /// <returns></returns>
        public string CalResult(Bitmap bit)
        {
            //用于记录原始的解析信息
            var str = "";
            try
            {
                //灰度化处理,人眼对绿色敏感度最高,蓝色敏感度最低,所以权重侧重绿色
                bit = new Grayscale(0.2125, 0.7154, 0.0721).Apply(bit);
                //BitmapData 可以提高效率,直接读取灰度值的方法耗时800ms,bitmapdata只需要10ms。
                var mapdata = BitToByte(bit);
                //行相加,用于寻找左右方向边框
                byte[] row = SumRow(mapdata, bit.Width, bit.Height);
                //列相加,用于寻找上下方向边框
                byte[] col = SumCol(mapdata, bit.Width, bit.Height);
                //得到边框位置,如果为白色试剂片,需重新设计算法
                int[] rowx = RowColBorder(row, 100, row.Max() / 2 + row.Min() / 2);
                int[] colx = RowColBorder(col, 100, col.Max() / 2 + col.Min() / 2);
                //考虑边缘阴影等,切除部分阴影
                rowx[0] += 40;
                rowx[1] -= 40;
                colx[0] += 80;
                colx[1] -= 80;
                //截取试剂条区域
                Rectangle rect = new Rectangle(new Point(rowx[0], colx[0]), new Size(rowx[1] - rowx[0], colx[1] - colx[0]));
                Bitmap b = new Bitmap(rowx[1] - rowx[0], colx[1] - colx[0], PixelFormat.Format32bppArgb);
                Graphics g = Graphics.FromImage(b);
                g.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel);
                g.Dispose();
                //灰度化处理
                b = new Grayscale(0.2125, 0.7154, 0.0721).Apply(b);
                //二值化处理
                b = new Threshold(180).Apply(b);
                //取得新的截取后区域的值
                mapdata = BitToByte(b);
                //进行行相加
                row = SumRow(mapdata, b.Width, b.Height);
                col = SumCol(mapdata, b.Width, b.Height);

                for (int i = 0; i < row.Length; i++)
                {
                    row[i] = (byte)(row[i] > 128 ? 255 : 0);
                }

                //寻找左右两条参考黑线
                int[] FirstEndX = LookFirstEndBlackLine(row);
                double startx = FirstEndX[0];
                double endx = FirstEndX[1];
                //24条线的线宽计算
                double index = (int)((endx - startx + 1) / 24.00 + 0.5);
                //黑白临界点位置
                List<int> result = new List<int>();
                //黑白线宽  交替
                List<double> result1 = new List<double>();

                int flag = 0;
                result.Add((int)startx);
                str = startx + ",";
                for (int i = (int)startx; i < endx + 1; i++)
                {
                    if (flag == 0 & row[i] == 255)
                    {
                        flag = 255;
                        result.Add(i);
                        result1.Add(i - result[result.Count - 2]);
                        str += i.ToString() + ",";
                    }
                    else if (flag == 255 & row[i] == 0)
                    {
                        flag = 0;
                        result.Add(i);
                        result1.Add(i - result[result.Count - 2]);
                        str += i.ToString() + ",";
                    }
                }
                result.Add((int)endx);
                result1.Add(endx - result[result.Count - 2]);
                str += endx.ToString();
                //如果有很窄的白线或者黑线不到1格,需要处理
                while ((int)(result1.Min() / index + 0.5) == 0)
                {
                    for (int i = 0; i < result1.Count; i++)
                    {
                        if (result1[i] == result1.Min())
                        {
                            if (i == 0)
                            {
                                result1[i] += result1[i + 1];
                                result1.RemoveAt(i + 1);
                                break;
                            }
                            else if (i == result1.Count - 1)
                            {
                                result1[i] += result1[i - 1];
                                result1.RemoveAt(i - 1);
                                break;
                            }
                            else
                            {
                                if (result1[i + 1] < index)
                                {
                                    result1[i] += result1[i + 1];
                                    result1.RemoveAt(i + 1);
                                    break;
                                }
                                else if (result1[i - 1] < index)
                                {
                                    result1[i] += result1[i - 1];
                                    result1.RemoveAt(i - 1);
                                    break;
                                }
                                else
                                {
                                    if ((int)result1[i - 1] % (int)index < (int)result1[i + 1] % (int)index)
                                    {
                                        result1[i - 1] += result1[i];
                                        result1.RemoveAt(i);
                                        break;
                                    }
                                    else
                                    {
                                        result1[i + 1] += result1[i];
                                        result1.RemoveAt(i);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < result1.Count; i++)
                {
                    result1[i] = (int)(((double)result1[i] / ((double)index) + 0.5));
                    str += result1[i].ToString() + "\r\n";
                }
                var result2 = "";
                char flag1 = '1';
                for (int i = result1.Count - 1; i > -1; i--)
                {
                    result2 += "".PadLeft((int)result1[i], flag1);
                    flag1 = flag1 == '1' ? '0' : '1';
                }
                if (result2.Length == 24)
                {
                    if (result2.Substring(0, 2) == "10" & result2.Substring(22, 2) == "01")
                    {
                        result2 = result2.Substring(2, 20);

                        int no = Convert.ToInt32(result2, 2);
                        result2 = result2.Reverse().ToString(); ;
                        result2 = no.ToString("X6");
                    }
                }
                return result2;
            }
            catch (Exception ee)
            {
                return ee.Message;
            }
        }
Example #22
0
 public static Bitmap ToBlackAndWhite(this Bitmap source)
 {
     Threshold filter = new Threshold(100);
     return filter.Apply(source);
 }
Example #23
0
        private void process_Click(object sender, EventArgs e)
        {
            //grayscale
            Grayscale filter1 = new Grayscale(0.2125, 0.7154, 0.0721);

            processed = filter1.Apply(processed);

            //threshold
            var filter2 = new AForge.Imaging.Filters.Threshold(175);

            processed = filter2.Apply(processed);

            // erosion
            Erosion filter3 = new Erosion();

            filter3.Apply(processed);

            // create filter
            BlobsFiltering filter = new BlobsFiltering();

            // configure filter
            filter.CoupledSizeFiltering = true;
            filter.MinWidth             = 25;
            filter.MinHeight            = 25;
            // apply the filter
            filter.ApplyInPlace(processed);

            Invert filterInvert = new Invert();

            // apply the filter
            filterInvert.ApplyInPlace(processed);


            BlobCounterBase bc = new BlobCounter();

            bc.FilterBlobs          = true;
            bc.MinWidth             = 30;   //give required value or ignore
            bc.MinHeight            = 30;   //give required value  or ignore
            bc.CoupledSizeFiltering = true; // if value are given and if you want both Width and Height to be applied as a constraint to identify blob, set it to true
            bc.ProcessImage(processed);
            Blob[] blobs = bc.GetObjectsInformation();

            int count = bc.ObjectsCount;

            // lock image to draw on it
            BitmapData data = processed.LockBits(
                new Rectangle(0, 0, processed.Width, processed.Height),
                ImageLockMode.ReadWrite, processed.PixelFormat);


            // process each blob
            foreach (Blob blob in blobs)
            {
                List <IntPoint> leftPoints, rightPoints, edgePoints;
                edgePoints = new List <IntPoint>();

                // get blob's edge points
                bc.GetBlobsLeftAndRightEdges(blob,
                                             out leftPoints, out rightPoints);

                edgePoints.AddRange(leftPoints);
                edgePoints.AddRange(rightPoints);

                IConvexHullAlgorithm hullFinder = new GrahamConvexHull();

                // blob's convex hull
                List <IntPoint> hull = hullFinder.FindHull(edgePoints);

                Drawing.Polygon(data, hull, Color.Yellow);

                if (blob.Area < 8000)
                {
                    five_cents++;
                }
                else if (blob.Area < 9000 && blob.Area > 8000)
                {
                    ten_cents++;
                }
                else if (blob.Area < 13000 && blob.Area > 11000)
                {
                    twentyfive_cents++;
                }
                else if (blob.Area < 17000 && blob.Area > 16000)
                {
                    one_peso++;
                }
                else
                {
                    five_peso++;
                }
            }

            processed.UnlockBits(data);


            pictureBox2.Image    = processed;
            pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;

            textBox1.Text += count;
            textBox2.Text += ((five_cents * .05) + (ten_cents * .10) + (twentyfive_cents * .25) + (one_peso * 1) + (five_peso * 5));
        }
Example #24
0
        static void Main(string[] args)
        {
            Threshold thresh = new Threshold(10);
            Median median = new Median(9);
            Erosion3x3 erode = new Erosion3x3();
            Dilatation3x3 dilate = new Dilatation3x3();
            GrahamConvexHull hullFinder = new GrahamConvexHull();
            ConnectedComponentsLabeling ccLabeler = new ConnectedComponentsLabeling();
            BorderFollowing contourFinder = new BorderFollowing();
            GrayscaleToRGB rgb = new GrayscaleToRGB();
            ConvexHullDefects defectFinder = new ConvexHullDefects(10);

            Bitmap img = (Bitmap)Bitmap.FromFile("hand3.jpg");

            Bitmap image = Grayscale.CommonAlgorithms.BT709.Apply(img);
            thresh.ApplyInPlace(image);
            //median.ApplyInPlace(image);
            erode.ApplyInPlace(image);
            dilate.ApplyInPlace(image);

            BlobCounter counter = new BlobCounter(image);
            counter.ObjectsOrder = ObjectsOrder.Area;

            Blob[] blobs = counter.GetObjectsInformation();

            if (blobs.Length > 0)
            {
                counter.ExtractBlobsImage(image, blobs[0], true);

                UnmanagedImage hand = blobs[0].Image;

                var contour = contourFinder.FindContour(hand);

                if (contour.Count() > 0)
                {
                    var initialHull = hullFinder.FindHull(contour);

                    var defects = defectFinder.FindDefects(contour, initialHull);

                    var filteredHull = initialHull.ClusterHullPoints().FilterLinearHullPoints();

                    var palmCenter = defects.Centroid(contour);

                    var wristPoints = filteredHull.SelectWristPoints(defects, contour);

                    Bitmap color = rgb.Apply(hand).ToManagedImage();

                    //BitmapData data = color.LockBits(new Rectangle(0, 0, color.Width, color.Height), ImageLockMode.ReadWrite, color.PixelFormat);
                    //Drawing.Polyline(data, contour, Color.Blue);
                    //Drawing.Polygon(data, filteredHull, Color.Red);
                    //color.UnlockBits(data);

                    Graphics gr = Graphics.FromImage(color);

                    gr.DrawPolygon(new Pen(Brushes.Red, 3), filteredHull.ToPtArray());
                    gr.DrawLines(new Pen(Brushes.Blue, 3), contour.ToPtArray());
                    gr.DrawEllipse(new Pen(Brushes.Red, 3), palmCenter.X - 10, palmCenter.Y - 10, 20, 20);

                    foreach (ConvexityDefect defect in defects)
                    {
                        gr.DrawEllipse(new Pen(Brushes.Green, 6), contour[defect.Point].X - 10, contour[defect.Point].Y - 10, 20, 20);
                    }

                    foreach (AForge.IntPoint pt in filteredHull)
                    {
                        gr.DrawEllipse(new Pen(Brushes.Yellow, 6), pt.X - 10, pt.Y - 10, 20, 20);
                    }

                    foreach (AForge.IntPoint pt in wristPoints)
                    {
                        gr.DrawEllipse(new Pen(Brushes.PowderBlue, 6), pt.X - 10, pt.Y - 10, 20, 20);
                    }

                    ImageBox.Show(color);
                }
            }
        }
        public void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // get new frame
            CheckForIllegalCrossThreadCalls = false;
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
            if (pictureBox1.Image == null)
            {
                bitmap.Save(@"modelo0.jpg");
                bgFrame = bitmap;
            }
            else
            {
                try
                {
                    bgFrame = (Bitmap)pictureBox1.Image.Clone();
                    //bitmap.Save(@"currImage.jpg");
                    currentFrame = (Bitmap)bitmap.Clone();

                    Bitmap gcurrent = Grayscale.CommonAlgorithms.BT709.Apply(bitmap);
                    Bitmap gbground = Grayscale.CommonAlgorithms.BT709.Apply(bgFrame);

                    Difference differenceFilter = new Difference();
                    differenceFilter.OverlayImage = gbground;
                    Bitmap currentImg = differenceFilter.Apply(gcurrent);

                    //bloqueo temporal de current image
                    BitmapData currentData = currentImg.LockBits(new Rectangle(0, 0, framesProcessing.fWidth,
                                        framesProcessing.fHeight), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

                    //**Thresholdfilter
                    Threshold thresholdFilter = new Threshold(15);
                    thresholdFilter.ApplyInPlace(currentData);
                    IFilter erosionFilter = new Erosion();
                    Bitmap tmp2 = erosionFilter.Apply(currentData);

                    currentImg.UnlockBits(currentData);
                    i = framesProcessing.CalculateWhitePixels(tmp2);

                    if (i > 300)
                    {
                        mov = mov2 = true;
                    }
                    else
                        mov = false;

                    pictureBox2.Image = currentImg;
                }
                catch{//MessageBox.Show(ex.Message.ToString());
                }

            }
            pictureBox1.Image = bitmap;
        }
        private Bitmap Threshold(Bitmap original, int value = 100)
        {
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
            Bitmap image = filter.Apply(original);
            Threshold filtera = new Threshold(value);

            return filtera.Apply(image);
        }
Example #27
0
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string filename = "C:\\Users\\darwesh\\Documents\\Visual Studio 2010\\WebSites\\WebSite1\\Images\\" + FileUpload1.FileName;
            string filedir  = "C:\\Users\\darwesh\\Documents\\Visual Studio 2010\\WebSites\\WebSite1\\";

            FileUpload1.SaveAs("C:\\Users\\darwesh\\Documents\\Visual Studio 2010\\WebSites\\WebSite1\\Images\\" + FileUpload1.FileName);
            pixels16 = new List <ushort>();
            Imagemri     im = new Imagemri();
            DicomDecoder dd = new DicomDecoder();
            dd.DicomFileName = filename;
            imageWidth       = dd.width;
            imageHeight      = dd.height;
            bitDepth         = dd.bitsAllocated;
            winCentre        = dd.windowCentre;
            winWidth         = dd.windowWidth;


            bool result = dd.dicomFileReadSuccess;
            if (result == true)
            {
                im.NewImage = true;



                if (bitDepth == 16)
                {
                    pixels16.Clear();

                    dd.GetPixels16(ref pixels16);
                    byte[]        buffer = new byte[pixels16.Count * 2];
                    byte[]        temp;
                    ByteConverter d = new ByteConverter();
                    int           j = 0;
                    for (int i = 0; i < pixels16.Count; i++)
                    {
                        temp        = System.BitConverter.GetBytes(pixels16[i]);
                        buffer[j++] = temp[0];
                        buffer[j++] = temp[1];
                    }

                    if (winCentre == 0 && winWidth == 0)
                    {
                        winWidth  = 4095;
                        winCentre = 4095 / 2;
                    }
                }

                im.SetParameters(ref pixels16, imageWidth, imageHeight, winWidth, winCentre, true);
                string index = "";
                foreach (string stt in dd.dicomInfo)
                {
                    if (stt.Contains("Patient's Weight"))
                    {
                        index = stt;
                    }
                }
                string wii = index.Split(':')[1];
                foreach (string stt in dd.dicomInfo)
                {
                    if (stt.Contains("Patient's Name"))
                    {
                        index = stt;
                    }
                }
                string pn = index.Split(':')[1];;
                AForge.Imaging.Filters.Grayscale g1 = new Grayscale(0.2125, 0.7154, 0.0721);

                Bitmap imagew       = g1.Apply(im.bmp);
                int    thresholding = (int)((dd.windowWidth - dd.windowCentre) * 255 / dd.windowWidth);
                AForge.Imaging.Filters.Threshold thf = new AForge.Imaging.Filters.Threshold(thresholding);
                Bitmap          ther        = thf.Apply(imagew);
                BlobCounter     blobCounter = new BlobCounter(ther);
                Blob[]          blobs       = blobCounter.GetObjects(ther, false);
                ImageStatistics img;
                AForge.Imaging.Filters.GrayscaleToRGB d1 = new GrayscaleToRGB();
                Bitmap   bm      = d1.Apply(imagew);
                Edges    s       = new Edges();
                Graphics gg      = Graphics.FromImage(bm);
                string   ss      = null;
                Bitmap   myImage = null;
                Blob     b;
                int      count = 0;
                string   locc  = "";



                foreach (Blob blob in blobs)
                {
                    img = new ImageStatistics(blob.Image);
                    double perc = ((double)img.PixelsCountWithoutBlack / (double)img.PixelsCount) * 100;

                    if (blob.Image.Size.Height > 20 && blob.Image.Size.Width > 20 && perc > 35)
                    {
                        b = blob;

                        ImageStatistics  st  = new ImageStatistics(b.Image);
                        Bitmap           pp  = s.Apply(b.Image);
                        ChannelFiltering c   = new ChannelFiltering(new IntRange(0, 255), new IntRange(0, 0), new IntRange(0, 0));
                        Bitmap           pp2 = d1.Apply(pp);
                        c.ApplyInPlace(pp2);
                        pp2.MakeTransparent(Color.Black);
                        gg.DrawImage(pp2, b.Rectangle);
                        gg.Flush();
                        myImage = im.bmp.Clone(b.Rectangle, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        ss      = ((double)(st.PixelsCountWithoutBlack) * (double)dd.pixelHeight * dd.pixelWidth).ToString();
                        locc    = (b.Rectangle.Location.X * dd.pixelWidth).ToString() + "mm," + (b.Rectangle.Location.Y * dd.pixelHeight).ToString() + "mm";

                        count++;
                    }
                }//end foreach


                bm.Save(filedir + FileUpload1.FileName + ".png", ImageFormat.Png);
                records r = new records();
                recordsTableAdapters.recordsTableAdapter ta = new recordsTableAdapters.recordsTableAdapter();
                ta.InsertRecord(pn, wii, FileUpload1.FileName, FileUpload1.FileName + ".png", "", ss, locc);
            }
        }
    }
Example #28
0
 public Bitmap BinarizeImage(int threshold)
 {
     Threshold filter = new Threshold(threshold);
     //ConvertTOGrayScale(0.2125, 0.7154, 0.0721);
     Bitmap convertedImage = filter.Apply(ImageBitmap);
     ImageBitmap = convertedImage;
     return convertedImage;
 }
        private Bitmap thresholdImage(Bitmap image, int thresholdVal)
        {
            Threshold thrshold = new Threshold();
            thrshold.ThresholdValue = thresholdVal;
            thrshold.ApplyInPlace(image);

            return image;
        }
Example #30
0
        private Bitmap imgCut(Bitmap cutthis)
        {
            Bitmap b = new Bitmap(15, 20, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(b);
            g.Clear(Color.White);
            g.DrawImage(cutthis, 0, 0);
            b = new Grayscale(0.299, 0.587, 0.114).Apply(b);
            b = new Sharpen().Apply(b);
            b = new Sharpen().Apply(b);
            b = new Threshold(50).Apply(b);

            return b;
        }
Example #31
0
        private void detectQuads(Bitmap bitmap)
        {
            // Greyscale
            filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap);

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

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

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

            BlobCounter blobCounter = new BlobCounter();

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

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            filteredBitmap.UnlockBits(bitmapData);

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Bitmap bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb);

            Graphics g = Graphics.FromImage(bm);
            g.DrawImage(filteredBitmap, 0, 0);

            Pen pen = new Pen(Color.Red, 5);
            List<IntPoint> cardPositions = new List<IntPoint>();

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

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

                    // Only return 4 corner rectanges
                    if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) &&  corners.Count == 4)
                    {
                        // Check if its sideways, if so rearrange the corners so it's veritcal
                        rearrangeCorners(corners);

                        // Prevent it from detecting the same card twice
                        foreach (IntPoint point in cardPositions)
                        {
                            if (corners[0].DistanceTo(point) < 40)
                                sameCard = true;
                        }

                        if (sameCard)
                            continue;

                        // Hack to prevent it from detecting smaller sections of the card instead of the whole card
                        if (GetArea(corners) < 20000)
                            continue;

                        cardPositions.Add(corners[0]);

                        g.DrawPolygon(pen, ToPointsArray(corners));

                        // Extract the card bitmap
                        QuadrilateralTransformation transformFilter = new QuadrilateralTransformation(corners, 211, 298);
                        cardBitmap = transformFilter.Apply(cameraBitmap);

                        List<IntPoint> artCorners = new List<IntPoint>();
                        artCorners.Add(new IntPoint(14, 35));
                        artCorners.Add(new IntPoint(193, 35));
                        artCorners.Add(new IntPoint(193, 168));
                        artCorners.Add(new IntPoint(14, 168));

                        // Extract the art bitmap
                        QuadrilateralTransformation cartArtFilter = new QuadrilateralTransformation(artCorners, 183, 133);
                        cardArtBitmap = cartArtFilter.Apply(cardBitmap);

                        MagicCard card = new MagicCard();
                        card.corners = corners;
                        card.cardBitmap = cardBitmap;
                        card.cardArtBitmap = cardArtBitmap;

                        magicCards.Add(card);
                    }
                }
            }

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

            filteredBitmap = bm;
        }
Example #32
0
 // =========================================================
 private void ThresholdFunct(ref Bitmap frame, int par_int, double par_d, int par_R, int par_G, int par_B)
 {
     frame = Grayscale.CommonAlgorithms.RMY.Apply(frame);
     Threshold filter = new Threshold(par_int);
     filter.ApplyInPlace(frame);
     GrayscaleToRGB toColFilter = new GrayscaleToRGB();
     frame = toColFilter.Apply(frame);
 }
 public static Bitmap Threshold(Bitmap page, int threshold)
 {
     page = page.To32bpp();
     Grayscale gs = new Grayscale(0.30, 0.59, 0.11);
     Threshold ts = new Threshold(threshold);
     Bitmap result = gs.Apply(page);
     return ts.Apply(result);
 }
Example #34
0
        public static IEnumerable<MagicCard> DetectCardArt(Bitmap cameraBitmap)
        {
            var ret = new List<MagicCard>();

            var filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(cameraBitmap);

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

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

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

            var blobCounter = new BlobCounter();

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

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

            var shapeChecker = new SimpleShapeChecker();
            var bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb);

            var cardPositions = new List<IntPoint>();
            foreach (var blob in blobs)
            {
                var edgePoints = blobCounter.GetBlobsEdgePoints(blob);

                List<IntPoint> corners;

                // only operate on 4 sided polygons
                if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                {
                    var subtype = shapeChecker.CheckPolygonSubType(corners);

                    if (corners.Count() != 4)
                        continue;

                    if (subtype != PolygonSubType.Parallelogram && subtype != PolygonSubType.Rectangle)
                        continue;

                    // if the image is sideways, rotate it so it'll match the DB card art
                    corners = Utilities.RotateCorners(corners).ToList();

                    if (Utilities.GetArea(corners) < 20000)
                        continue;

                    ret.Add( new MagicCard(cameraBitmap, corners));
                }
            }

            return ret;
        }
Example #35
0
        private void ReadAndDisplayDicomFile(string fileName, string fileNameOnly)
        {
            dd.DicomFileName = fileName;
            bool result = dd.dicomFileReadSuccess;

            if (result == true)
            {
                imageWidth  = dd.width;
                imageHeight = dd.height;
                bitDepth    = dd.bitsAllocated;
                winCentre   = dd.windowCentre;
                winWidth    = dd.windowWidth;


                StatusLabel1.Text  = fileName + ": " + imageWidth.ToString() + " X " + imageHeight.ToString();
                StatusLabel1.Text += "  " + bitDepth.ToString() + " bits per pixel";

                userControl11.NewImage = true;
                Text = "DICOM Image Viewer: " + fileNameOnly;


                if (bitDepth == 16)
                {
                    pixels16.Clear();
                    pixels8.Clear();
                    dd.GetPixels16(ref pixels16);
                    byte[]        buffer = new byte[pixels16.Count * 2];
                    byte[]        temp;
                    ByteConverter d = new ByteConverter();
                    int           j = 0;
                    for (int i = 0; i < pixels16.Count; i++)
                    {
                        temp        = System.BitConverter.GetBytes(pixels16[i]);
                        buffer[j++] = temp[0];
                        buffer[j++] = temp[1];
                    }

                    if (winCentre == 0 && winWidth == 0)
                    {
                        winWidth  = 4095;
                        winCentre = 4095 / 2;
                    }
                    string index = "";
                    foreach (string s in dd.dicomInfo)
                    {
                        if (s.Contains("Image Number"))
                        {
                            index = s;
                        }
                    }



                    userControl11.SetParameters(ref pixels16, imageWidth, imageHeight, winWidth, winCentre, true, this);


                    if (processI && int.Parse(index.Split(':')[1]) > 9)
                    {
                        AForge.Imaging.Filters.Grayscale            g1 = new Grayscale(0.2125, 0.7154, 0.0721);
                        AForge.Imaging.Filters.BrightnessCorrection bC = new AForge.Imaging.Filters.BrightnessCorrection(brightness);
                        bC.ApplyInPlace(userControl11.bmp);
                        Bitmap image = g1.Apply(userControl11.bmp);
                        thresholding = (int)((dd.windowWidth - dd.windowCentre) * 255 / dd.windowWidth) - trackBar2.Value;
                        label1.Text  = thresholding.ToString();
                        AForge.Imaging.Filters.Threshold thf = new AForge.Imaging.Filters.Threshold(thresholding);
                        Bitmap          ther        = thf.Apply(image);
                        BlobCounter     blobCounter = new BlobCounter(ther);
                        Blob[]          blobs       = blobCounter.GetObjects(ther, false);
                        ImageStatistics img;
                        AForge.Imaging.Filters.GrayscaleToRGB d1 = new GrayscaleToRGB();
                        Bitmap   bm      = d1.Apply(image);
                        Edges    s       = new Edges();
                        Graphics gg      = Graphics.FromImage(bm);
                        string   ss      = null;
                        Bitmap   myImage = null;
                        Blob     b;
                        int      count = 0;
                        listView1.Items.Clear();
                        mylesions.Clear();
                        Crop   cut;
                        Bitmap Ilesion = null;

                        //System.Threading.Tasks.Parallel.ForEach(blobs, blob =>
                        foreach (Blob blob in blobs)
                        {
                            img = new ImageStatistics(blob.Image);
                            double perc = ((double)img.PixelsCountWithoutBlack / (double)img.PixelsCount) * 100;
                            textBox2.Text = perc.ToString();
                            if (blob.Image.Size.Height > 20 && blob.Image.Size.Width > 20 && perc > 35)
                            {
                                b       = blob;
                                cut     = new Crop(b.Rectangle);
                                Ilesion = g1.Apply(cut.Apply(userControl11.bmp));

                                ImageStatistics st = new ImageStatistics(b.Image);

                                Bitmap           pp = s.Apply(b.Image);
                                ChannelFiltering c  = new ChannelFiltering(new IntRange(0, 255), new IntRange(0, 0), new IntRange(0, 0));

                                Bitmap pp2 = d1.Apply(pp);
                                c.ApplyInPlace(pp2);

                                pp2.MakeTransparent(Color.Black);



                                gg.DrawImage(pp2, b.Rectangle);
                                gg.Flush();

                                myImage = userControl11.bmp.Clone(b.Rectangle, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                                ss = ((double)(st.PixelsCountWithoutBlack) * (double)dd.pixelHeight * dd.pixelWidth).ToString();
                                ListViewItem lv = new ListViewItem(count.ToString());
                                lv.SubItems.Add(ss);
                                lv.SubItems.Add(b.Rectangle.Location.X.ToString() + "," + b.Rectangle.Location.Y.ToString());
                                listView1.Items.Add(lv);

                                Add    adder    = new Add(pp);
                                Bitmap undashes = (Bitmap)Ilesion.Clone();
                                adder.ApplyInPlace(Ilesion);
                                string locc = (b.Rectangle.Location.X * dd.pixelWidth).ToString() + "mm," + (b.Rectangle.Location.Y * dd.pixelHeight).ToString() + "mm";
                                mylesions.Add(new lesion((Bitmap)Ilesion.Clone(), ss, b.Rectangle.Location, locc, undashes));

                                count++;
                            }
                        }
                        textBox1.Text = "tumor size= " + ss + " mm² *" + dd.pixelDepth.ToString() + "mm";

                        // host.NewDocument(bmp);

                        // pictureBox2.Image = myImage;
                        pictureBox1.Image = bm;
                        pictureBox2.Image = Ilesion;
                    }
                    else
                    {
                        pictureBox1.Image = userControl11.bmp;
                    }
                    pictureBox1.Invalidate();
                }

                //userControl11.increasecontrast(200);
            }
            else
            {
                if (dd.dicmFound == false)
                {
                    MessageBox.Show("This does not seem to be a DICOM 3.0 file. Sorry, I can't open this.");
                }
                else if (dd.dicomDir == true)
                {
                    MessageBox.Show("This seems to be a DICOMDIR file, and does not contain an image.");
                }
                else
                {
                    MessageBox.Show("Sorry, I can't read a DICOM file with this Transfer Syntax\n" +
                                    "You may view the initial tags instead.");
                }



                //userControl11.SetParameters(ref pixels8, imageWidth, imageHeight,
                //    winWidth, winCentre, true, this);
            }
        }