Beispiel #1
0
 public BitmapSource Apply(BitmapSource image)
 {
     var grayScale = ToGrayScale(image);
     var filter = new Threshold(factor);
     var bmp = filter.Apply(grayScale);
     return bmp.ToBitmapImage();
 }
Beispiel #2
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;
 }
Beispiel #3
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);
     }
 }
        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;
        }
 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);
 }
Beispiel #7
0
        public static FoundColorSpaces Find(Bitmap bmp)
        {
            FoundColorSpaces ret = new FoundColorSpaces();

            ret.OriginalColorSpace = bmp;
            ret.GrayColorSpace = Grayscale.CommonAlgorithms.BT709.Apply(ret.OriginalColorSpace);

            CannyEdgeDetector edges = new CannyEdgeDetector();
            Threshold threshold = new Threshold();
            ret.Edges = threshold.Apply(edges.Apply(ret.GrayColorSpace));

            ret.BinaryColorSpace = threshold.Apply(ret.GrayColorSpace);

            //ret.CorrectedRGBColorSpace = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb); 

            return ret;
        }
Beispiel #8
0
        private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand)
        {
            Crop c = new Crop(rect);
            var handImage = c.Apply(mask);

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

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

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


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


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

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

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

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

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

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

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

                    pbHand.Image = leftHand;
                }
            }
        }
Beispiel #9
0
        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            Invert inv = new Invert();
            inv.ApplyInPlace(image);

            UnmanagedImage ui = UnmanagedImage.FromManagedImage(image);

            pictureBox1.Image = image;


            if (controller.Tracker.TrackingObject == null)
                return;

            if (controller.Tracker.TrackingObject.IsEmpty)
                return;

            var rect = controller.Tracker.TrackingObject.Rectangle;
            Crop crop = new Crop(rect);

            UnmanagedImage head = crop.Apply(ui);

            var points = new List<IntPoint>() { new IntPoint(head.Width / 2, head.Height / 2) };
            var pps = head.Collect16bppPixelValues(points);

            double mean = Accord.Statistics.Tools.Mean(pps);

            double cutoff = mean + 15;
            Threshold t = new Threshold((int)cutoff);
            var mask = t.Apply(ui);



            LevelsLinear16bpp levels = new LevelsLinear16bpp();
            levels.InGray = new IntRange((int)cutoff, 65535);
            levels.OutGray = new IntRange(0, 65535);
            levels.ApplyInPlace(ui);


            var mask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(mask.ToManagedImage());



            BlobCounter bc = new BlobCounter();
            bc.ObjectsOrder = ObjectsOrder.Area;
            bc.ProcessImage(mask8bit);
            var blobs = bc.GetObjectsInformation();

            inv.ApplyInPlace(image);
            Intersect intersect = new Intersect();
            intersect.UnmanagedOverlayImage = mask;
            mask = intersect.Apply(ui);

            List<Rectangle> rects = new List<Rectangle>();

            // Extract the uppermost largest blobs.
            for (int i = 0; i < blobs.Length; i++)
            {
                double dx = (blobs[i].Rectangle.Top - controller.Tracker.TrackingObject.Center.Y);
                double d = (dx * dx) / controller.Tracker.TrackingObject.Area;
                if (d < 2 && blobs[i].Area > 1000)
                    rects.Add(blobs[i].Rectangle);
            }

            rects.Sort(compare);

            if (rects.Count > 0)
            {
                captureHand(mask, rects[0], pbLeftArm, pbLeftHand);
            }
            if (rects.Count > 1)
            {
                captureHand(mask, rects[1], pbRightArm, pbRightHand);

            }

            RectanglesMarker marker = new RectanglesMarker(rects);
            marker.MarkerColor = Color.White;
            marker.ApplyInPlace(mask8bit);

            image = mask.ToManagedImage();
        }
 private Bitmap getThresholdedFrame(Bitmap grayscaledFrame)
 {
     Threshold filter = new Threshold(18);
     Bitmap thresholdedFrame = filter.Apply(grayscaledFrame);
     return thresholdedFrame;
 }
Beispiel #11
0
 public static Bitmap ToBlackAndWhite(this Bitmap source)
 {
     Threshold filter = new Threshold(100);
     return filter.Apply(source);
 }
Beispiel #12
0
        private Bitmap XXX(Bitmap bmpBefore, Bitmap bmpAfter)
        {
            var filter = new Grayscale(0.2125, 0.7154, 0.0721);
            bmpBefore = filter.Apply(bmpBefore);
            bmpAfter = filter.Apply(bmpAfter);

            // create filters
            var differenceFilter = new Difference();
            IFilter thresholdFilter = new Threshold(15);
            // set backgroud frame as an overlay for difference filter
            differenceFilter.OverlayImage = bmpBefore;
            // apply the filters
            Bitmap tmp1 = differenceFilter.Apply(bmpAfter);
            Bitmap tmp2 = thresholdFilter.Apply(tmp1);
            IFilter erosionFilter = new Erosion();
            // apply the filter
            Bitmap tmp3 = erosionFilter.Apply(tmp2);

            IFilter pixellateFilter = new Pixellate();
            // apply the filter
            Bitmap tmp4 = pixellateFilter.Apply(tmp3);

            return tmp4;
        }
Beispiel #13
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));
        }
Beispiel #14
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);
            }
        }
    }
        public Bitmap Detect(Bitmap bitmap)
        {
            Bitmap grayscaleBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap);

            IFilter smoothingFilter = null;
            switch (_smoothMode)
            {
                case "None": smoothingFilter = null; break;
                case "Mean": smoothingFilter = new Mean(); break;
                case "Median": smoothingFilter = new Median(); break;
                case "Conservative": smoothingFilter = new ConservativeSmoothing(); break;
                case "Adaptive": smoothingFilter = new AdaptiveSmoothing(); break;
                case "Bilateral": smoothingFilter = new BilateralSmoothing(); break;
            }
            Bitmap smoothBitmap = smoothingFilter != null ? smoothingFilter.Apply(grayscaleBitmap) : grayscaleBitmap;

            IFilter edgeFilter = null;
            switch (_edgeMode)
            {
                case "Homogenity": edgeFilter = new HomogenityEdgeDetector(); break;
                case "Difference": edgeFilter = new DifferenceEdgeDetector(); break;
                case "Sobel": edgeFilter = new SobelEdgeDetector(); break;
                case "Canny": edgeFilter = new CannyEdgeDetector(); break;
            }
            Bitmap edgeBitmap = edgeFilter != null ? edgeFilter.Apply(smoothBitmap) : smoothBitmap;

            IFilter threshholdFilter = new Threshold(_threshold);
            Bitmap thresholdBitmap = _threshold == 0 ? edgeBitmap : threshholdFilter.Apply(edgeBitmap);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight = _minHeight;
            blobCounter.MinWidth = _minWidth;
            blobCounter.ProcessImage(thresholdBitmap);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            Bitmap outputBitmap = new Bitmap(thresholdBitmap.Width, thresholdBitmap.Height, PixelFormat.Format24bppRgb);
            Graphics bitmapGraphics = Graphics.FromImage(outputBitmap);
            Bitmap inputBitmap = null;
            switch (_drawMode)
            {
                case "Original": inputBitmap = bitmap; break;
                case "Grayscale": inputBitmap = grayscaleBitmap; break;
                case "Smooth": inputBitmap = smoothBitmap; break;
                case "Edge": inputBitmap = edgeBitmap; break;
                case "Threshold": inputBitmap = thresholdBitmap; break;
            }
            if (inputBitmap != null)
                bitmapGraphics.DrawImage(inputBitmap, 0, 0);

            Pen nonConvexPen = new Pen(Color.Red, 2);
            Pen nonRectPen = new Pen(Color.Orange, 2);
            Pen cardPen = new Pen(Color.Blue, 2);

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
            List<IntPoint> cardPositions = new List<IntPoint>();

            for (int i = 0; i < blobs.Length; i++)
            {
                List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                List<IntPoint> corners;

                if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                {
                    PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                    if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) && corners.Count == 4)
                    {
                        // Check if its sideways, if so rearrange the corners so it's vertical.
                        RearrangeCorners(corners);

                        // Prevent detecting the same card twice by comparing distance against other detected cards.
                        bool sameCard = false;
                        foreach (IntPoint point in cardPositions)
                        {
                            if (corners[0].DistanceTo(point) < _minDistance)
                            {
                                sameCard = true;
                                break;
                            }
                        }
                        if (sameCard)
                            continue;

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

                        cardPositions.Add(corners[0]);

                        bitmapGraphics.DrawPolygon(cardPen, ToPointsArray(corners));
                    }
                    else
                    {
                        foreach (IntPoint point in edgePoints.Take(300))
                        {
                            bitmapGraphics.DrawEllipse(nonRectPen, point.X, point.Y, 1, 1);
                        }
                    }
                }
                else
                {
                    foreach (IntPoint point in edgePoints.Take(300))
                    {
                        bitmapGraphics.DrawEllipse(nonConvexPen, point.X, point.Y, 1, 1);
                    }
                }
            }

            bitmapGraphics.Dispose();
            nonConvexPen.Dispose();
            nonRectPen.Dispose();
            cardPen.Dispose();

            return outputBitmap;
        }
Beispiel #16
0
        void VideoSourcePlayerNewFrame(object sender, ref Bitmap image)
        {
            lock (this)
            {
                Bitmap img_copy = new Bitmap(image);
                Grayscale gray_filter = new Grayscale(0.2125, 0.7154, 0.0721);
                img_copy = gray_filter.Apply(img_copy);
                Threshold thresh = new Threshold(thresh_val);
                img_copy = thresh.Apply(img_copy);
                BlobCounter bc = new BlobCounter();
                bc.FilterBlobs = true;
                bc.MinHeight = min_size_val;
                bc.MinWidth = min_size_val;
                bc.MaxHeight = min_size_val + 50;
                bc.MaxWidth = min_size_val + 50;
                bc.ProcessImage(img_copy);
                Rectangle[] rects = bc.GetObjectsRectangles();

                Graphics g = videoSourcePlayer.CreateGraphics();
                using (Pen p = new Pen(Color.Red))
                {
                    foreach (Rectangle r in rects)
                    {
                        g.DrawRectangle(p,r);
                        g.DrawString("a",new Font("Consolas",10),Brushes.Red,r.X,r.Y);
                    }
                }
                image = img_copy;
            }
        }
Beispiel #17
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 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";

                        }

               }
        }
 /// <summary>
 /// processes Frame for Motion Detection based on frame comparison
 /// </summary>
 /// <param name="frame">
 /// Takes in 2 Bitmap parameters, currentFrame and backgroundFrame
 /// </param>
 /// <returns>
 /// frame in which motion is marked
 /// </returns>
 public Bitmap processFrame(params Bitmap[] frame)
 {
     Bitmap currentFrame = frame[0];
     // create grayscale filter (BT709)
     Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
     Bitmap GScurrentFrame = filter.Apply(currentFrame);
     if (this.backgroundFrame == null)
     {
         this.backgroundFrame = (Bitmap)GScurrentFrame.Clone();
         GScurrentFrame.Dispose();
         return currentFrame;
     }
     else
     {
         Difference differenceFilter = new Difference();
         IFilter thresholdFilter = new Threshold(15);
         // set backgroud frame as an overlay for difference filter
         differenceFilter.OverlayImage = backgroundFrame;
         Bitmap tmp = thresholdFilter.Apply(differenceFilter.Apply(GScurrentFrame));
         //reduce noise
         IFilter erosionFilter = new Erosion();
         Bitmap tmp1 = erosionFilter.Apply(tmp);
         tmp.Dispose();
         // Highlight Motions
         IFilter extractChannel = new ExtractChannel(RGB.G);
         Bitmap redChannel = extractChannel.Apply(currentFrame);
         Merge mergeFilter = new Merge();
         mergeFilter.OverlayImage = tmp1;
         Bitmap t3 = mergeFilter.Apply(redChannel);
         ReplaceChannel rc = new ReplaceChannel(RGB.G, t3);
         t3 = rc.Apply(currentFrame);
         this.backgroundFrame = (Bitmap)GScurrentFrame.Clone();
         redChannel.Dispose();
         tmp1.Dispose();
         GScurrentFrame.Dispose();
         return t3;
     }
 }
        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);
        }
Beispiel #21
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);
            }
        }
 /// <summary>
 /// Binarize image with threshold filter
 /// </summary>
 /// <param name="image"></param>
 /// <param name="threshold">threshold for binarization</param>
 public static Image Threshold(this Image image, byte threshold)
 {
     Threshold thresholdFilter = new Threshold(threshold);
     return thresholdFilter.Apply(BitmapGrayscale(image));
 }
        private void DetectMotion()
        {
            if ((_previousFrame != null) && (_currentFrame != null))
            {
                Grayscale grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                using (Bitmap frame1GS = grayscaleFilter.Apply(_previousFrame))
                {
                    using (Bitmap frame2GS = grayscaleFilter.Apply(_currentFrame))
                    {
                        Difference differenceFilter = new Difference();
                        IFilter thresholdFilter = new Threshold(15);
                        // set backgroud frame as an overlay for difference filter

                        differenceFilter.OverlayImage = (Bitmap)frame1GS;
                        // apply the filters

                        using (Bitmap tmp1 = differenceFilter.Apply((Bitmap)frame2GS))
                        {
                            using (Bitmap tmp2 = thresholdFilter.Apply(tmp1))
                            {

                                IFilter erosionFilter = new Erosion();
                                // apply the filter

                                using (Bitmap tmp3 = erosionFilter.Apply(tmp2))
                                {
                                    int whitePixelsCount = CalculateWhitePixels(tmp3);

                                    if (whitePixelsCount > 1000)
                                    {
                                        MotionDetectionEvent motionEvent = new MotionDetectionEvent()
                                        {
                                            CameraDevice = _camera,
                                            NumberOfPixelsDetected = whitePixelsCount,
                                            InputDevice = _camera
                                        };
                                        MotionDetectedEventArgs args = new MotionDetectedEventArgs(motionEvent);
                                        OnMotionDetected(args);
                                    }

                                    //// extract red channel from the original image

                                    //IFilter extrachChannel = new ExtractChannel(RGB.R);
                                    //Bitmap redChannel = extrachChannel.Apply(frame2);
                                    ////  merge red channel with motion regions

                                    //Merge mergeFilter = new Merge();
                                    //mergeFilter.OverlayImage = tmp3;
                                    //Bitmap tmp4 = mergeFilter.Apply(redChannel);
                                    //// replace red channel in the original image

                                    //ReplaceChannel replaceChannel = new ReplaceChannel(RGB.R, tmp4);
                                    //replaceChannel.ChannelImage = tmp4;
                                    //Bitmap tmp5 = replaceChannel.Apply(frame2);
                                }
                            }
                        }
                    }
                }
            }
        }