Filters' collection to apply to an image in sequence.

The class represents collection of filters, which need to be applied to an image in sequence. Using the class user may specify set of filters, which will be applied to source image one by one in the order user defines them.

The class itself does not define which pixel formats are accepted for the source image and which pixel formats may be produced by the filter. Format of acceptable source and possible output is defined by filters, which added to the sequence.

Sample usage:

// create filter, which is binarization sequence FiltersSequence filter = new FiltersSequence( new GrayscaleBT709( ), new Threshold( ) ); // apply the filter Bitmap newImage = filter.Apply( image );
Inheritance: System.Collections.CollectionBase, IFilter
示例#1
1
 private string reconhecerCaptcha(Image img)
 {
     Bitmap imagem = new Bitmap(img);
     imagem = imagem.Clone(new Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
     Erosion erosion = new Erosion();
     Dilatation dilatation = new Dilatation();
     Invert inverter = new Invert();
     ColorFiltering cor = new ColorFiltering();
     cor.Blue = new AForge.IntRange(200, 255);
     cor.Red = new AForge.IntRange(200, 255);
     cor.Green = new AForge.IntRange(200, 255);
     Opening open = new Opening();
     BlobsFiltering bc = new BlobsFiltering();
     Closing close = new Closing();
     GaussianSharpen gs = new GaussianSharpen();
     ContrastCorrection cc = new ContrastCorrection();
     bc.MinHeight = 10;
     FiltersSequence seq = new FiltersSequence(gs, inverter, open, inverter, bc, inverter, open, cc, cor, bc, inverter);
     pictureBox.Image = seq.Apply(imagem);
     string reconhecido = OCR((Bitmap)pictureBox.Image);
     return reconhecido;
 }
        /// <summary>
        /// Manipulate (and resize) an image
        /// </summary>
        /// <param name="source"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override Bitmap Manipulate(object source, ImageManipulationSettings parameters)
        {
            var image = Resize(source, parameters);

            var filters = new FiltersSequence();

            if (parameters.Gamma.HasValue)
                filters.Add(new GammaCorrection(parameters.Gamma.Value));

            if (parameters.Sharpen.HasValue)
                filters.Add(new Sharpen { Threshold = (int)parameters.Sharpen.Value });

            if (parameters.Hue.HasValue)
                filters.Add(new HueModifier((int)parameters.Hue.Value));

            if (parameters.Saturation.HasValue)
                filters.Add(new SaturationCorrection((float)parameters.Saturation.Value));

            if (parameters.Brightness.HasValue)
                filters.Add(new BrightnessCorrection((int)parameters.Brightness.Value));

            if (parameters.Contrast.HasValue)
                filters.Add(new ContrastCorrection((int)parameters.Contrast.Value));

            return filters.Count == 0
                ? image
                : filters.Apply(image);
        }
        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;
        }
        public CardRecognizer()
        {
            //Initialize common filter sequence , this sequence generally will be applied
            commonSeq = new FiltersSequence();
            commonSeq.Add(Grayscale.CommonAlgorithms.BT709);
            commonSeq.Add(new OtsuThreshold());
            commonSeq.Add(new DifferenceEdgeDetector());

            Stream strm;
            BinaryFormatter bformat;

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            strm = File.Open("NetworkLetra.net", FileMode.Open);
            bformat = new BinaryFormatter();

            NetworkLetra = (FeedforwardNetwork)bformat.Deserialize(strm);

            strm = File.Open("NetworkSuits.net", FileMode.Open);
            bformat = new BinaryFormatter();

            NetworkSuits = (FeedforwardNetwork) bformat.Deserialize(strm);

            strm = File.Open("NetworkNumero.net", FileMode.Open);
            bformat = new BinaryFormatter();

            NetworkNumero = (FeedforwardNetwork)bformat.Deserialize(strm);

            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
        }
示例#5
0
        /// <summary>
        /// Constructor
        /// </summary>
        public CardRecognizer()
        {
            //Initialize common filter sequence , this sequence generally will be applied
            commonSeq = new FiltersSequence();
            commonSeq.Add(Grayscale.CommonAlgorithms.BT709);
            commonSeq.Add(new BradleyLocalThresholding());
            commonSeq.Add(new DifferenceEdgeDetector());

            //Load Templates From Resources ,
            //Templates will be used for template matching
            j = miranda.ui.Properties.Resources.J;
            k = miranda.ui.Properties.Resources.K;
            q = miranda.ui.Properties.Resources.Q;
            clubs = miranda.ui.Properties.Resources.Clubs;
            diamonds = miranda.ui.Properties.Resources.Diamonds;
            spades = miranda.ui.Properties.Resources.Spades;
            hearts = miranda.ui.Properties.Resources.Hearts;

            try
            {
                _engine = new TesseractEngine(@"./tessdata", "rus", EngineMode.Default);
                //_engine.SetVariable("tessedit_char_whitelist", "$.,0123456789");
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                Ex.Report(ex);
            }
        }
示例#6
0
        public Bitmap Adelgazar()
        {
            Invert ivert = new Invert();
            imagen = ivert.Apply(imagen);

            FiltersSequence filterSequence = new FiltersSequence();

            filterSequence.Add(new HitAndMiss(
                new short[,] { { 0, 0, 0 },
                               { -1, 1, -1 },
                               { 1, 1, 1 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { -1, 0, 0 },
                               { 1, 1, 0 },
                               { -1, 1, -1 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { 1, -1, 0 },
                               { 1, 1, 0 },
                               { 1, -1, 0 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { -1, 1, -1 },
                               { 1, 1, 0 },
                               { -1, 0, 0 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { 1, 1, 1 },
                               { -1, 1, -1 },
                               { 0, 0, 0 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { -1, 1, -1 },
                               { 0, 1, 1 },
                               { 0, 0, -1 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { 0, -1, 1 },
                               { 0, 1, 1 },
                               { 0, -1, 1 } },
                HitAndMiss.Modes.Thinning));
            filterSequence.Add(new HitAndMiss(
                new short[,] { { 0, 0, -1 },
                               { 0, 1, 1 },
                               { -1, 1, -1 } },
                HitAndMiss.Modes.Thinning));

            FilterIterator filterIterator = new FilterIterator(filterSequence, 15);

            imagen = filterIterator.Apply(imagen);

            imagen = ivert.Apply(imagen);

            return imagen;
        }
示例#7
0
        public virtual void Initialize(Bitmap backgroundImage)
        {
            fSequence = new FiltersSequence();
            BlobCounter = new BlobCounter();

            BlobCounter.MinWidth = BlobCounter.MinHeight = Global.AppSettings.MinBlobSize;
            BlobCounter.MaxWidth = BlobCounter.MaxWidth = Global.AppSettings.MaxBlobSize;
            BlobCounter.FilterBlobs = Global.AppSettings.FilterBlobs;
            BlobCounter.ObjectsOrder = ObjectsOrder.None;

            Initialized = true;
        }
		/// <summary>
		/// Apply corrections and crop a specific part of an image in order to perform OCR
		/// </summary>
		/// <param name="SourceImage"></param>
		/// <param name="rect"></param>
		/// <returns></returns>
		public static Bitmap PreprocessOCR(Bitmap SourceImage, Rectangle rect)
        {
			try {
				// binarization filtering sequence
	            FiltersSequence filter = new FiltersSequence(
	                new Crop(rect),
	                new Median(),
	                new ContrastCorrection(),
	                //new Mean(),
	                new AForge.Imaging.Filters.Blur(),
	                new GrayscaleBT709(),
	                //new Threshold(),
	                new Threshold(),
	                new Invert()
	                
	            );
	
	
	            // load image
	            Bitmap image = SourceImage;
	
	            // format image
	            AForge.Imaging.Image.Clone(image,image.PixelFormat);
	//            AForge.Imaging.Image.FormatImage(ref image);
	
	            // lock the source image
	            BitmapData sourceData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);
	
	            // apply filters and binarize the image
	            UnmanagedImage binarySource = filter.Apply(new UnmanagedImage(sourceData));
	
	
	            Bitmap binarizedImage= binarySource.ToManagedImage();
	            
	
	            // unlock source image
	            image.UnlockBits(sourceData);
	
	            // dispose temporary binary source image
	            binarySource.Dispose();
	
	            return binarizedImage;
			} catch (Exception ex) {
				throw ex;
			}



        }//preprocess
示例#9
0
        /// <summary>
        /// Constructor
        /// </summary>
        public CardRecognizer()
        {
            //Initialize common filter sequence , this sequence generally will be applied
            commonSeq = new FiltersSequence();
            commonSeq.Add(Grayscale.CommonAlgorithms.BT709);
            commonSeq.Add(new BradleyLocalThresholding());
            commonSeq.Add(new DifferenceEdgeDetector());

            
            //Load Templates From Resources , 
            //Templates will be used for template matching

            LoadResources();
            
            
        }
示例#10
0
        private void thresholding()
        // Threshold Image
        {
            // Declare Image
            Bitmap bmp = new Bitmap(pictureBox1.Image);
            // create filters sequence
            FiltersSequence filter = new AForge.Imaging.Filters.FiltersSequence();

            // add filters to the sequence
            filter.Add(new Grayscale(0.299, 0.587, 0.114));
            filter.Add(new Threshold(128));

            // apply the filter sequence
            Bitmap newbmp = filter.Apply(bmp);

            pictureBox1.Image = newbmp;
        }
示例#11
0
        private Bitmap j, k, q; //Face Card Character Templates

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        public CardRecognizer()
        {
            //Initialize common filter sequence , this sequence generally will be applied
            commonSeq = new FiltersSequence();
            commonSeq.Add(Grayscale.CommonAlgorithms.BT709);
            commonSeq.Add(new BradleyLocalThresholding());
            commonSeq.Add(new DifferenceEdgeDetector());

            //Load Templates From Resources ,
            //Templates will be used for template matching
            j = PlayingCardRecognition.Properties.Resources.J;
            k = PlayingCardRecognition.Properties.Resources.K;
            q = PlayingCardRecognition.Properties.Resources.Q;
            clubs = PlayingCardRecognition.Properties.Resources.Clubs;
            diamonds = PlayingCardRecognition.Properties.Resources.Diamonds;
            spades = PlayingCardRecognition.Properties.Resources.Spades;
            hearts = PlayingCardRecognition.Properties.Resources.Hearts;
        }
示例#12
0
        public string RecognizeTextSmall(Bitmap source)
        {
            try
            {
                //var res = IsNotNumber(source);
                //if (res)
                //{
                //    return "none";
                //}

                var temp = source.Clone() as Bitmap; //Clone image to keep original image

                var seq = new FiltersSequence();

                //seq.Add(new Grayscale(0.7, 0.7, 0.7));
                seq.Add(Grayscale.CommonAlgorithms.BT709);
                //seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
                seq.Add(new Invert());
                //seq.Add(new ResizeBilinear(source.Width * 2, source.Height * 2));
                temp = seq.Apply(source); // Apply filters on source image

                //using (var engine = new TesseractEngine(@"./tessdata", "rus", EngineMode.Default))
                {

                    using (var page = _engine.Process(temp, PageSegMode.SingleLine))
                    {
                        var text = page.GetText();
                        var conf = page.GetMeanConfidence();

                        //Ex.Report(new Exception(text));
                        //if (conf < 0.5)
                        //    return "none";
                        return text;
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Ex.Report(e);
                return "";
            }
        }
        public virtual void GetLiveImage()
        {
            if (_operInProgress)
            {
               // Log.Error("OperInProgress");
                return;
            }

            if (DelayedStart)
            {
                //Log.Error("Start is delayed");
                return;
            }

            if (FreezeImage)
                return;

            _operInProgress = true;
            _totalframes++;
            if ((DateTime.Now - _framestart).TotalSeconds > 0)
                Fps = (int)(_totalframes / (DateTime.Now - _framestart).TotalSeconds);
            try
            {
                LiveViewData = LiveViewManager.GetLiveViewImage(CameraDevice);
            }
            catch (Exception ex)
            {
                Log.Error("Error geting lv", ex);
                _operInProgress = false;
                return;
            }

            if (LiveViewData == null)
            {
                _operInProgress = false;
                return;
            }

            if (!LiveViewData.IsLiveViewRunning && !IsFocusStackingRunning)
            {
                DelayedStart = true;
                _restartTimerStartTime = DateTime.Now;
                _restartTimer.Start();
                _operInProgress = false;
                return;
            }

            if (LiveViewData.ImageData == null)
            {
               // Log.Error("LV image data is null !");
                _operInProgress = false;
                return;
            }

            Recording = LiveViewData.MovieIsRecording;
            try
            {
                if (LiveViewData != null && LiveViewData.ImageData != null)
                {
                    MemoryStream stream = new MemoryStream(LiveViewData.ImageData,
                        LiveViewData.
                            ImageDataPosition,
                        LiveViewData.ImageData.
                            Length -
                        LiveViewData.
                            ImageDataPosition);
                    LevelAngle = (int)LiveViewData.LevelAngleRolling;
                    SoundL = LiveViewData.SoundL;
                    SoundR = LiveViewData.SoundR;
                    PeakSoundL = LiveViewData.PeakSoundL;
                    PeakSoundR = LiveViewData.PeakSoundR;
                    HaveSoundData = LiveViewData.HaveSoundData;
                    MovieTimeRemain = decimal.Round(LiveViewData.MovieTimeRemain, 2);

                    if (NoProcessing)
                    {
                        BitmapImage bi = new BitmapImage();
                        bi.BeginInit();
                        bi.CacheOption = BitmapCacheOption.OnLoad;
                        bi.StreamSource = stream;
                        bi.EndInit();
                        bi.Freeze();
                        Bitmap = bi;
                        ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = stream.ToArray();
                        _operInProgress = false;
                        return;
                    }

                    using (var res = new Bitmap(stream))
                    {
                        Bitmap bmp = res;
                        if (PreviewTime > 0 && (DateTime.Now - _photoCapturedTime).TotalSeconds <= PreviewTime)
                        {
                            var bitmap = ServiceProvider.Settings.SelectedBitmap.DisplayImage.Clone();
                            //var dw = (double)bmp.Width / bitmap.PixelWidth;
                            //bitmap = bitmap.Resize((int)(bitmap.PixelWidth * dw), (int)(bitmap.PixelHeight * dw),
                            //    WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                            // flip image only if the prview not fliped
                            if (FlipImage && !ServiceProvider.Settings.FlipPreview)
                                bitmap = bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                            bitmap.Freeze();
                            ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(bitmap);
                            Bitmap = bitmap;
                            return;
                        }
                        if (DetectMotion)
                        {
                            ProcessMotionDetection(bmp);
                        }

                        if (_totalframes % DesiredFrameRate == 0 && ShowHistogram)
                        {
                            ImageStatisticsHSL hslStatistics =
                                new ImageStatisticsHSL(bmp);
                            LuminanceHistogramPoints =
                                ConvertToPointCollection(
                                    hslStatistics.Luminance.Values);
                            ImageStatistics statistics = new ImageStatistics(bmp);
                            RedColorHistogramPoints = ConvertToPointCollection(
                                statistics.Red.Values);
                            GreenColorHistogramPoints = ConvertToPointCollection(
                                statistics.Green.Values);
                            BlueColorHistogramPoints = ConvertToPointCollection(
                                statistics.Blue.Values);
                        }

                        if (HighlightUnderExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(0, 5);
                            filtering.Red = new IntRange(0, 5);
                            filtering.Green = new IntRange(0, 5);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(Color.Blue);
                            filtering.ApplyInPlace(bmp);
                        }

                        if (HighlightOverExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(250, 255);
                            filtering.Red = new IntRange(250, 255);
                            filtering.Green = new IntRange(250, 255);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(Color.Red);
                            filtering.ApplyInPlace(bmp);
                        }

                        var preview = BitmapFactory.ConvertToPbgra32Format(
                            BitmapSourceConvert.ToBitmapSource(bmp));
                        DrawFocusPoint(preview, true);

                        if (Brightness != 0)
                        {
                            BrightnessCorrection filter = new BrightnessCorrection(Brightness);
                            bmp = filter.Apply(bmp);
                        }

                        Bitmap newbmp = bmp;
                        if (EdgeDetection)
                        {
                            var filter = new FiltersSequence(
                                Grayscale.CommonAlgorithms.BT709,
                                new HomogenityEdgeDetector()
                                );
                            newbmp = filter.Apply(bmp);
                        }

                        WriteableBitmap writeableBitmap;

                        if (BlackAndWhite)
                        {
                            Grayscale filter = new Grayscale(0.299, 0.587, 0.114);
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(
                                        filter.Apply(newbmp)));
                        }
                        else
                        {
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(newbmp));
                        }
                        DrawGrid(writeableBitmap);
                        switch (RotationIndex)
                        {
                            case 0:
                                Rotation = 0;
                                break;
                            case 1:
                                Rotation = 90;
                                break;
                            case 2:
                                Rotation = 180;
                                break;
                            case 3:
                                Rotation = 270;
                                break;
                            case 4:
                                Rotation = LiveViewData.Rotation;
                                break;
                        }

                        if (CameraDevice.LiveViewImageZoomRatio.Value == "All")
                        {
                            preview.Freeze();
                            Preview = preview;
                            if (ShowFocusRect)
                                DrawFocusPoint(writeableBitmap);
                        }

                        if (FlipImage)
                        {
                            writeableBitmap = writeableBitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                        }
                        if (CropRatio > 0)
                        {
                            CropOffsetX = (int) ((writeableBitmap.PixelWidth/2.0)*CropRatio/100);
                            CropOffsetY = (int) ((writeableBitmap.PixelHeight/2.0)*CropRatio/100);
                            writeableBitmap = writeableBitmap.Crop(CropOffsetX, CropOffsetY,
                                writeableBitmap.PixelWidth - (2*CropOffsetX),
                                writeableBitmap.PixelHeight - (2*CropOffsetY));
                        }
                        writeableBitmap.Freeze();
                        Bitmap = writeableBitmap;

                        //if (_totalframes%DesiredWebFrameRate == 0)
                        ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(writeableBitmap);
                    }
                    stream.Close();
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
                _operInProgress = false;
            }
            finally
            {
                _operInProgress = false;
            }
            _operInProgress = false;
        }
        public override void GetLiveImage()
        {
            try
            {
                LiveViewData = LiveViewManager.GetLiveViewImage(CameraDevice);
            }
            catch (Exception)
            {
                return;
            }

            if (LiveViewData == null || LiveViewData.ImageData == null)
                return;
            MemoryStream stream = new MemoryStream(LiveViewData.ImageData,
                                                   LiveViewData.ImageDataPosition,
                                                   LiveViewData.ImageData.Length -
                                                   LiveViewData.ImageDataPosition);
            using (var bmp = new Bitmap(stream))
            {
                Bitmap res = bmp;
                var preview = BitmapFactory.ConvertToPbgra32Format(BitmapSourceConvert.ToBitmapSource(res));
                var zoow = preview.Crop((int)(CentralPoint.X - (StarWindowSize / 2)), (int)(CentralPoint.Y - (StarWindowSize / 2)),
                        StarWindowSize, StarWindowSize);
                CalculateStarSize(zoow);
                zoow.Freeze();
                StarWindow = zoow;

                preview.Freeze();
                Preview = preview;


                if (Brightness != 0)
                {
                    BrightnessCorrection filter = new BrightnessCorrection(Brightness);
                    res = filter.Apply(res);
                }
                if (EdgeDetection)
                {
                    var filter = new FiltersSequence(
                        Grayscale.CommonAlgorithms.BT709,
                        new HomogenityEdgeDetector()
                        );
                    res = filter.Apply(res);
                }

                var _bitmap = BitmapFactory.ConvertToPbgra32Format(BitmapSourceConvert.ToBitmapSource(res));
                DrawGrid(_bitmap);

                if (ZoomFactor > 1)
                {
                    double d = _bitmap.PixelWidth/(double) ZoomFactor;
                    double h = _bitmap.PixelHeight/(double) ZoomFactor;
                    _bitmap = _bitmap.Crop((int) (CentralPoint.X - (d/2)), (int) (CentralPoint.Y - (h/2)),
                        (int) d, (int) h);
                }

                _bitmap.Freeze();
                Bitmap = _bitmap;
            }

        }
示例#15
0
 Bitmap preprocess(Bitmap bmp, FiltersSequence fs)
 {
     Bitmap tmp = bmp.Clone() as Bitmap;
     tmp = fs.Apply(bmp);
     return tmp;
 }
示例#16
0
        private void doAllImage()
        {
            DirectoryInfo dir = new DirectoryInfo("c:\\code");
            FileInfo[] files = dir.GetFiles("*.jpg");
            preprocessFilters = new FiltersSequence();
            preprocessFilters.Add(Grayscale.CommonAlgorithms.BT709);
            //preprocessFilters.Add(new BradleyLocalThresholding());
            preprocessFilters.Add(new OtsuThreshold());
            foreach (FileInfo file in files)
            {

                Bitmap map = new Bitmap(file.FullName);
                int noiseWidth = 5;
                Bitmap preImg = denoise(preprocess(map, preprocessFilters), new Size(noiseWidth, noiseWidth));
                preImg = denoise(preprocess(preImg, preprocessFilters), new Size(noiseWidth, 3));
                preImg = denoise(preprocess(preImg, preprocessFilters), new Size(3, noiseWidth));
                quganrao(preImg);
                //
                //to2(map);
                preImg.Save("c:\\code\\1\\" + file.Name);
            }
        }
示例#17
0
        /// <summary>
        /// processes Frame for Motion Detection based on background generation
        /// </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
            {
                Morph filterx = new Morph(GScurrentFrame);
                filterx.SourcePercent = 0.75;
                Bitmap tmp = filterx.Apply(backgroundFrame);
                // dispose old background
                backgroundFrame.Dispose();
                backgroundFrame = tmp;

                // create processing filters sequence
                FiltersSequence processingFilter = new FiltersSequence();
                processingFilter.Add(new Difference(backgroundFrame));
                processingFilter.Add(new Threshold(threshold_val));
                processingFilter.Add(new Opening());
                processingFilter.Add(new Edges());
                // apply the filter
                Bitmap tmp1 = processingFilter.Apply(GScurrentFrame);

                IFilter extractChannel = new ExtractChannel(RGB.R);
                Bitmap redChannel = extractChannel.Apply(currentFrame);
                Merge mergeFilter = new Merge();
                mergeFilter.OverlayImage = tmp1;
                Bitmap t3 = mergeFilter.Apply(redChannel);
                ReplaceChannel rc = new ReplaceChannel(RGB.R, t3);
                t3 = rc.Apply(currentFrame);
                redChannel.Dispose();
                tmp1.Dispose();
                GScurrentFrame.Dispose();
                return t3;
            }
        }
示例#18
0
        private IFilter GenerateFilters()
        {
            FiltersSequence filters = new FiltersSequence();
            foreach (TreeNode node in treeLayers.Nodes)
            {
                if (node.Level == 0 && node.Checked)
                {

                    foreach (TreeNode child in node.Nodes)
                    {
                        if (child.Checked)
                        {
                            HSLFiltering local_filter = new HSLFiltering(((LayerColor)child.Tag).hue_range, ((LayerColor)child.Tag).sat_range, ((LayerColor)child.Tag).lum_range);
                            local_filter.FillColor = ((LayerProperties)node.Tag).HSLReplacementColor;
                            local_filter.FillOutsideRange = false;
                            filters.Add(local_filter);
                        }
                    }

                }

            }
            return filters;
        }
示例#19
0
文件: Form1.cs 项目: bdus/AForge
        public Bitmap DealImg(System.Drawing.Image b)
        {
            try
            {
                /*var bnew = new Bitmap(b.Width, b.Height, PixelFormat.Format24bppRgb);

                Graphics g = Graphics.FromImage(bnew);
                g.DrawImage(b, 0, 0);
                g.Dispose();

                bnew = new Grayscale(0.2125, 0.7154, 0.0721).Apply(bnew);
                bnew = new BlobsFiltering(1, 1, b.Width, b.Height).Apply(bnew);
                bnew = new Sharpen().Apply(bnew);
                bnew = new Threshold(50).Apply(bnew);
                */
                //code above do not effect well here.

                Bitmap bnew = new Bitmap(b);
                Graphics g = Graphics.FromImage(bnew);
                g.DrawImage(b, 0, 0);
                g.Dispose();
                FiltersSequence seq = new FiltersSequence();
                seq.Add(Grayscale.CommonAlgorithms.BT709);
                seq.Add(new OtsuThreshold());
                bnew = seq.Apply(bnew);

                return bnew;
            }
            catch (Exception)
            {

                throw;
            }
            //return null;
        }
示例#20
0
        public Button RecognizeOneButton(Bitmap source, Rectangle rect, string filePath, int id)
        {
            var seq = new FiltersSequence();
            var card = new Button(source); //Create Card Object

            card.Rect = rect;

            seq.Clear();

            seq.Add(Grayscale.CommonAlgorithms.BT709);
            seq.Add(new OtsuThreshold());
            source = seq.Apply(source);

            card.Tip = ScanButtonTip(source); //Scan Rank of non-face card

            //if (card.Tip == ButtonTip.NOT_RECOGNIZED)
            //{
            //    if (!string.IsNullOrEmpty(filePath))
            //    {
            //        while (File.Exists(filePath + id + ".bmp"))
            //            id++;
            //        top.Save(filePath + id + ".bmp", ImageFormat.Bmp);
            //    }
            //}

            return card;
        }
示例#21
0
        //TODO not f*****g working
        public string RecognizeBet(Bitmap source)
        {
            try
            {
                //var res = IsNotNumber(source);
                //if (res)
                //{
                //    return "none";
                //}

                var temp = source.Clone() as Bitmap; //Clone image to keep original image

                //*
                var seq = new FiltersSequence();

                seq.Add(new Grayscale(0, 1, 0));
                //seq.Add(Grayscale.CommonAlgorithms.BT709);
                //seq.Add(new ResizeBilinear(source.Width * 2, source.Height * 2));
                //seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
                //seq.Add(new Threshold(50));
                //seq.Add(new Invert());

                temp = seq.Apply(source); // Apply filters on source image
                //*/

                //var extractor = new BlobCounter();
                //extractor.FilterBlobs = true;

                //extractor.MaxHeight = 15;
                //extractor.MinHeight = 0;
                ////extractor.MaxWidth = 10;
                ////extractor.MinWidth = 10;
                ////extractor.BackgroundThreshold = Color.Green;
                //extractor.ProcessImage(temp);

                //////Will be used transform(extract) cards on source image
                ////QuadrilateralTransformation quadTransformer = new QuadrilateralTransformation();

                //foreach (Blob blob in extractor.GetObjectsInformation())
                //{
                //    ////Get Edge points of card
                //    //List<IntPoint> edgePoints = extractor.GetBlobsEdgePoints(blob);
                //    ////Calculate/Find corners of card on source image from edge points
                //    //List<IntPoint> corners = PointsCloud.FindQuadrilateralCorners(edgePoints);

                //    //var cardImg = source.Clone(blob.Rectangle, PixelFormat.DontCare);
                //    var cardImg = temp.Clone(blob.Rectangle, PixelFormat.DontCare);
                //}
                //using (var engine = new TesseractEngine(@"./tessdata", "rus", EngineMode.Default))
                {
                    //_engine.SetVariable("tessedit_char_whitelist", "$.,0123456789");
                    using (var page = _engine.Process(temp))
                    {
                        var text = page.GetText();
                        var conf = page.GetMeanConfidence();

                        //Ex.Report(new Exception(text));
                        //if (conf < 0.8)
                        //    return "none";
                        return text;
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Ex.Report(e);
                return "";
            }
        }
示例#22
0
        /// <summary>
        /// Detects and recognizes cards from source image
        /// </summary>
        /// <param name="source">Source image to be scanned</param>
        /// <returns>Recognized Cards</returns>
        public CardCollection Recognize(Bitmap source, string filePath, int id,
            int minSize, Rectangle suitRect, Rectangle rankRect
            )
        {
            CardCollection collection = new CardCollection();  //Collection that will hold cards
            Bitmap temp = source.Clone() as Bitmap; //Clone image to keep original image

            FiltersSequence seq = new FiltersSequence();
            seq.Add(Grayscale.CommonAlgorithms.BT709);  //First add  grayScaling filter
            seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
            temp = seq.Apply(source); // Apply filters on source image

            //if (!string.IsNullOrEmpty(fileName))
            //{
            //    temp.Save(fileName, ImageFormat.Bmp);
            //}
            //Extract blobs from image whose size width and height larger than 150
            BlobCounter extractor = new BlobCounter();
            extractor.FilterBlobs = true;
            extractor.MinWidth = extractor.MinHeight = minSize;//TODO card size
            //extractor.MaxWidth = extractor.MaxHeight = 70;//TODO card size
            extractor.ProcessImage(temp);

            //Will be used transform(extract) cards on source image
            //QuadrilateralTransformation quadTransformer = new QuadrilateralTransformation();

            foreach (Blob blob in extractor.GetObjectsInformation())
            {
                var cardImg = source.Clone(blob.Rectangle, PixelFormat.DontCare);

                Card card = new Card(cardImg); //Create Card Object

                Bitmap suitBmp = card.GetPart(suitRect);
                char color = ScanColor(suitBmp); //Scan color

                seq.Clear();

                seq.Add(Grayscale.CommonAlgorithms.BT709);
                seq.Add(new OtsuThreshold());
                suitBmp = seq.Apply(suitBmp);

                card.Suit = ScanSuit(suitBmp, color); //Scan suit of face card

                Bitmap rankBmp = card.GetPart(rankRect);
                seq.Clear();

                seq.Add(Grayscale.CommonAlgorithms.BT709);
                seq.Add(new OtsuThreshold());
                rankBmp = seq.Apply(rankBmp);

                //var ext = new BlobsFiltering(0, 0, 40, 40);
                //ext.ApplyInPlace(rankBmp);
                card.Rank = ScanRank(rankBmp); //Scan Rank of non-face card

                //if (card.Rank == Rank.NOT_RECOGNIZED)
                //{
                //    if (!string.IsNullOrEmpty(filePath))
                //    {
                //        while (File.Exists(filePath + id + ".bmp"))
                //            id++;
                //        top.Save(filePath + id + ".bmp", ImageFormat.Bmp);
                //    }
                //}

                if(card.Rank != Rank.NOT_RECOGNIZED && card.Suit != Suit.NOT_RECOGNIZED)
                    collection.Add(card); //Add card to collection
            }

            collection.SortByRank();
            return collection;
        }
示例#23
0
 public static Image ToGrayScale(this Image original){
     var filtersSequence = new FiltersSequence{Grayscale.CommonAlgorithms.BT709};
     return filtersSequence.Apply((Bitmap) original);
 }
示例#24
0
        Bitmap processImageCenterline(string filename)
        {
            using (Bitmap SampleImage = (Bitmap)System.Drawing.Image.FromFile(filename))
            {
                // We must convert it to grayscale because
                // the filter accepts 8 bpp grayscale images
                Grayscale GF = new Grayscale(0.2125, 0.7154, 0.0721);
                using (Bitmap GSampleImage = GF.Apply(SampleImage))
                {
                    // Saving the grayscale image, so we could see it later
                    // Detecting image edges and saving the result
                    CannyEdgeDetector CED = new CannyEdgeDetector(0, 70);
                    //CED.ApplyInPlace(GSampleImage);
                    //BradleyLocalThresholding bwfilter = new BradleyLocalThresholding();
                    //bwfilter.ApplyInPlace(GSampleImage);
                    // create filter

                    // create filter sequence
                    FiltersSequence filterSequence = new FiltersSequence();

                    // Inverting image to get white image on black background
                    filterSequence.Add(new Invert());
                    filterSequence.Add(new SISThreshold());
                    // Finding skeleton
                    filterSequence.Add(new SimpleSkeletonization());
                    //clean image from scratches
                    short[,] se = new short[,] {
                                                { -1, -1, -1 },
                                                {  0,  1,  0 },
                                                { -1, -1, -1 }};

                    filterSequence.Add(new HitAndMiss(se, HitAndMiss.Modes.Thinning));
                    //filterSequence.Add(new Median( ));
                    //filterSequence.Add(new Dilatation());
                    filterSequence.Add(new Invert());
                    // apply the filter and rfeturn value
                    return filterSequence.Apply(GSampleImage);

                }

            }
        }
        public void ProcessLiveView(Bitmap bmp)
        {
            if (PreviewTime > 0 && (DateTime.Now - _photoCapturedTime).TotalSeconds <= PreviewTime)
            {
                var bitmap = ServiceProvider.Settings.SelectedBitmap.DisplayImage.Clone();
                // flip image only if the prview not fliped 
                if (FlipImage && !ServiceProvider.Settings.FlipPreview)
                    bitmap = bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                bitmap.Freeze();
                ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(bitmap);
                Bitmap = bitmap;
                return;
            }
            if (DetectMotion)
            {
                ProcessMotionDetection(bmp);
            }

            if (_totalframes%DesiredFrameRate == 0 && ShowHistogram)
            {
                ImageStatisticsHSL hslStatistics =
                    new ImageStatisticsHSL(bmp);
                LuminanceHistogramPoints =
                    ConvertToPointCollection(
                        hslStatistics.Luminance.Values);
                ImageStatistics statistics = new ImageStatistics(bmp);
                RedColorHistogramPoints = ConvertToPointCollection(
                    statistics.Red.Values);
                GreenColorHistogramPoints = ConvertToPointCollection(
                    statistics.Green.Values);
                BlueColorHistogramPoints = ConvertToPointCollection(
                    statistics.Blue.Values);
            }

            if (HighlightUnderExp)
            {
                ColorFiltering filtering = new ColorFiltering();
                filtering.Blue = new IntRange(0, 5);
                filtering.Red = new IntRange(0, 5);
                filtering.Green = new IntRange(0, 5);
                filtering.FillOutsideRange = false;
                filtering.FillColor = new RGB(Color.Blue);
                filtering.ApplyInPlace(bmp);
            }

            if (HighlightOverExp)
            {
                ColorFiltering filtering = new ColorFiltering();
                filtering.Blue = new IntRange(250, 255);
                filtering.Red = new IntRange(250, 255);
                filtering.Green = new IntRange(250, 255);
                filtering.FillOutsideRange = false;
                filtering.FillColor = new RGB(Color.Red);
                filtering.ApplyInPlace(bmp);
            }

            var preview = BitmapFactory.ConvertToPbgra32Format(
                BitmapSourceConvert.ToBitmapSource(bmp));
            DrawFocusPoint(preview, true);

            if (Brightness != 0)
            {
                BrightnessCorrection filter = new BrightnessCorrection(Brightness);
                bmp = filter.Apply(bmp);
            }


            Bitmap newbmp = bmp;
            if (EdgeDetection)
            {
                var filter = new FiltersSequence(
                    Grayscale.CommonAlgorithms.BT709,
                    new HomogenityEdgeDetector()
                    );
                newbmp = filter.Apply(bmp);
            }

            WriteableBitmap writeableBitmap;

            if (BlackAndWhite)
            {
                Grayscale filter = new Grayscale(0.299, 0.587, 0.114);
                writeableBitmap =
                    BitmapFactory.ConvertToPbgra32Format(
                        BitmapSourceConvert.ToBitmapSource(
                            filter.Apply(newbmp)));
            }
            else
            {
                writeableBitmap =
                    BitmapFactory.ConvertToPbgra32Format(
                        BitmapSourceConvert.ToBitmapSource(newbmp));
            }
            DrawGrid(writeableBitmap);
            switch (RotationIndex)
            {
                case 0:
                    Rotation = 0;
                    break;
                case 1:
                    Rotation = 90;
                    break;
                case 2:
                    Rotation = 180;
                    break;
                case 3:
                    Rotation = 270;
                    break;
                case 4:
                    Rotation = LiveViewData.Rotation;
                    break;
            }

            if (CameraDevice.LiveViewImageZoomRatio.Value == "All")
            {
                preview.Freeze();
                Preview = preview;
                if (ShowFocusRect)
                    DrawFocusPoint(writeableBitmap);
            }

            if (FlipImage)
            {
                writeableBitmap = writeableBitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
            }
            if (CropRatio > 0)
            {
                CropOffsetX = (int) ((writeableBitmap.PixelWidth/2.0)*CropRatio/100);
                CropOffsetY = (int) ((writeableBitmap.PixelHeight/2.0)*CropRatio/100);
                writeableBitmap = writeableBitmap.Crop(CropOffsetX, CropOffsetY,
                    writeableBitmap.PixelWidth - (2*CropOffsetX),
                    writeableBitmap.PixelHeight - (2*CropOffsetY));
            }
            writeableBitmap.Freeze();
            Bitmap = writeableBitmap;

            //if (_totalframes%DesiredWebFrameRate == 0)
            ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(writeableBitmap);
        }
示例#26
0
        /// <summary>
        /// Detects and recognizes cards from source image
        /// </summary>
        /// <param name="source">Source image to be scanned</param>
        /// <returns>Recognized Cards</returns>
        public List<Card> Recognize(Bitmap source)
        {
            List<Card> collection = new List<Card>();
            
            Bitmap temp = source.Clone(source.PixelFormat) as Bitmap; //Clone image to keep original image

            FiltersSequence seq = new FiltersSequence();
            seq.Add(Grayscale.CommonAlgorithms.BT709);  //First add  grayScaling filter
            seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
            temp = seq.Apply(source); // Apply filters on source image

            //Extract blobs from image whose size width and height larger than 150
            BlobCounter extractor = new BlobCounter();
            extractor.FilterBlobs = true;
            extractor.MinWidth = extractor.MinHeight = 150;
            extractor.MaxWidth = extractor.MaxHeight = 350;
            extractor.ProcessImage(temp);

            //Will be used transform(extract) cards on source image 
            QuadrilateralTransformation quadTransformer = new QuadrilateralTransformation();

            //Will be used resize(scaling) cards 
            ResizeBilinear resizer = new ResizeBilinear(CardWidth, CardHeight);

            foreach (Blob blob in extractor.GetObjectsInformation())
            {
                //Get Edge points of card
                List<IntPoint> edgePoints = extractor.GetBlobsEdgePoints(blob);
                //Calculate/Find corners of card on source image from edge points
                List<IntPoint> corners = PointsCloud.FindQuadrilateralCorners(edgePoints);

                quadTransformer.SourceQuadrilateral = corners; //Set corners for transforming card 
                quadTransformer.AutomaticSizeCalculaton = true;

                Bitmap cardImg = quadTransformer.Apply(source); //Extract(transform) card image

                if (cardImg.Width > cardImg.Height) //If card is positioned horizontally
                {
                    WriteableBitmap wbmp=(WriteableBitmap)cardImg;
                    wbmp = wbmp.Rotate(90);
                    cardImg = (Bitmap)wbmp; //Rotate
                }
                cardImg = resizer.Apply(cardImg); //Normalize card size

                Card card = new Card(cardImg, corners.ToArray()); //Create Card Object
                char color = ScanColor(card.GetTopLeftPart()); //Scan color
                bool faceCard = IsFaceCard(cardImg); //Determine type of card(face or not)

                if (!faceCard)
                {
                    card.Suit = ScanSuit(cardImg, color); //Scan Suit of non-face card
                    card.Rank = ScanRank(cardImg); //Scan Rank of non-face card
                }
                else
                {
                    Bitmap topLeft = card.GetTopLeftPart();

                    seq = null;
                    seq = new FiltersSequence();

                    seq.Add(Grayscale.CommonAlgorithms.BT709);
                    seq.Add(new BradleyLocalThresholding());
                    topLeft = seq.Apply(topLeft);
                    BlobsFiltering bFilter = new BlobsFiltering(5, 5, 150, 150);
                    bFilter.ApplyInPlace(topLeft); //Filter blobs that can not be a suit

                    //topLeft.Save("topleft.bmp", ImageFormat.Bmp);

                    card.Suit = ScanFaceSuit(topLeft, color); //Scan suit of face card
                    card.Rank = ScanFaceRank(topLeft); //Scan rank of face card
                }
                collection.Add(card); //Add card to collection
            }
            return collection;
        }
示例#27
0
        public bool ScanByTemplate(Bitmap source, Bitmap template)
        {
            var temp = source.Clone() as Bitmap; //Clone image to keep original image
            var tempTempl = template;

            var seq = new FiltersSequence();
            seq.Add(Grayscale.CommonAlgorithms.BT709);  //First add  grayScaling filter
            //seq.Add(new Threshold(200));
            seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
            temp = seq.Apply(source); // Apply filters on source image

            //tempTempl = seq.Apply(template); // Apply filters on source image

            var templateMatchin = new ExhaustiveTemplateMatching(0.9f);
            TemplateMatch[] templates;
            templates = templateMatchin.ProcessImage(temp, tempTempl);

            return templates.Length > 0;
        }
        /// <summary>
        /// Detects and recognizes cards from source image
        /// </summary>
        /// <param name="source">Source image to be scanned</param>
        /// <returns>Recognized Cards</returns>
        public CardCollection Recognize(Bitmap source)
        {
            CardCollection collection = new CardCollection();  //Collection that will hold cards
            Bitmap temp = source.Clone() as Bitmap; //Clone image to keep original image

            FiltersSequence seq = new FiltersSequence();
            seq.Add(Grayscale.CommonAlgorithms.BT709);  //First add  grayScaling filter
            seq.Add(new OtsuThreshold()); //Then add binarization(thresholding) filter
            temp = seq.Apply(source); // Apply filters on source image

            //Extract blobs from image whose size width and height larger than 150
            BlobCounter extractor = new BlobCounter();
            extractor.FilterBlobs = true;
            extractor.MinWidth = extractor.MinHeight = 150;
            extractor.MaxWidth = extractor.MaxHeight = 350;
            extractor.ProcessImage(temp);

            //Will be used transform(extract) cards on source image
            QuadrilateralTransformation quadTransformer = new QuadrilateralTransformation();

            //Will be used resize(scaling) cards
            ResizeBilinear resizer = new ResizeBilinear(CardWidth, CardHeight);

            foreach (Blob blob in extractor.GetObjectsInformation())
            {
                //Get Edge points of card
                List<IntPoint> edgePoints = extractor.GetBlobsEdgePoints(blob);
                //Calculate/Find corners of card on source image from edge points
                List<IntPoint> corners = PointsCloud.FindQuadrilateralCorners(edgePoints);

                quadTransformer.SourceQuadrilateral = corners; //Set corners for transforming card
                quadTransformer.AutomaticSizeCalculaton = true;

                Bitmap cardImg = quadTransformer.Apply(source); //Extract(transform) card image

                if (cardImg.Width > cardImg.Height) //If card is positioned horizontally
                    cardImg.RotateFlip(RotateFlipType.Rotate90FlipNone); //Rotate
                cardImg = resizer.Apply(cardImg); //Normalize card size

                Card card = new Card(cardImg, corners.ToArray()); //Create Card Object
                bool faceCard = IsFaceCard(cardImg); //Determine type of card(face or not)

                ResizeBicubic res;

                seq.Clear();
                seq.Add(Grayscale.CommonAlgorithms.BT709);
                seq.Add(new OtsuThreshold());

                Bitmap topLeftSuit = card.GetTopLeftSuitPart();
                Bitmap bmp = seq.Apply(topLeftSuit);

                bmp = CutWhiteSpaces(bmp);
                res = new ResizeBicubic(32, 40);
                bmp = res.Apply(bmp);

                Bitmap topLeftRank = card.GetTopLeftRankPart();
                Bitmap bmp2 = seq.Apply(topLeftRank);

                bmp2 = CutWhiteSpaces(bmp2);

                seq.Clear();
                seq.Add(new OtsuThreshold());
                bmp = seq.Apply(bmp);
                card.Suit = ScanSuit(bmp);

                if (!faceCard)
                {
                    res = new ResizeBicubic(26, 40);
                    bmp2 = res.Apply(bmp2);
                    seq.Clear();
                    seq.Add(new OtsuThreshold());
                    bmp2 = seq.Apply(bmp2);
                    card.Rank = ScanRank(bmp2);
                }
                else
                {
                    res = new ResizeBicubic(32, 40);
                    bmp2 = res.Apply(bmp2);
                    seq.Clear();
                    seq.Add(new OtsuThreshold());
                    bmp2 = seq.Apply(bmp2);
                    card.Rank = ScanFaceRank(bmp2);
                }
                collection.Add(card); //Add card to collection
            }
            return collection;
        }
示例#29
0
        private bool IsNotNumber(Bitmap source)
        {
            var template = Resources.PlayerEmpty;
            var temp = source.Clone() as Bitmap; //Clone image to keep original image

            var seq = new FiltersSequence();
            seq.Add(Grayscale.CommonAlgorithms.BT709);
            temp = seq.Apply(source); // Apply filters on source image

            var templ = seq.Apply(template);

            var templateMatchin = new ExhaustiveTemplateMatching(0.9f);
            TemplateMatch[] templates;
            if (
                temp.Width < template.Width
                ||
                temp.Height < template.Height
                )
                templates = templateMatchin.ProcessImage(templ, temp);
            else
                templates = templateMatchin.ProcessImage(temp, templ);

            var res = templates.Length > 0;

            template = Resources.PlayerMissing;
            templ = seq.Apply(template);

            templateMatchin = new ExhaustiveTemplateMatching(0.9f);
            TemplateMatch[] templates2;
            if (
                temp.Width < template.Width
                ||
                temp.Height < template.Height
                )
                templates2 = templateMatchin.ProcessImage(templ, temp);
            else
                templates2 = templateMatchin.ProcessImage(temp, templ);

            res |= templates2.Length > 0;
            return res;
        }
示例#30
0
 public static Image ToBlackAndWhite(this Image original){
     var filtersSequence = new FiltersSequence { Grayscale.CommonAlgorithms.BT709,new OtsuThreshold() };
     return filtersSequence.Apply((Bitmap)original);
 }
        public virtual void GetLiveImage()
        {
            if (_operInProgress)
                return;
            
            if (DelayedStart)
                return;

            _operInProgress = true;
            _totalframes++;
            if ((DateTime.Now - _framestart).TotalSeconds > 0)
                Fps = (int) (_totalframes/(DateTime.Now - _framestart).TotalSeconds);
            try
            {
                LiveViewData = LiveViewManager.GetLiveViewImage(CameraDevice);
            }
            catch (Exception)
            {
                _retries++;
                _operInProgress = false;
                return;
            }

            if (LiveViewData == null )
            {
                _retries++;
                _operInProgress = false;
                return;
            }

            if (!LiveViewData.IsLiveViewRunning)
            {
                DelayedStart = true;
                _restartTimerStartTime = DateTime.Now;
                _restartTimer. Start();
                _operInProgress = false;
                return;
            }

            if (LiveViewData.ImageData == null)
            {
                _retries++;
                _operInProgress = false;
                return;
            }

            Recording = LiveViewData.MovieIsRecording;
            try
            {
                WriteableBitmap preview;
                if (LiveViewData != null && LiveViewData.ImageData != null)
                {
                    MemoryStream stream = new MemoryStream(LiveViewData.ImageData,
                        LiveViewData.
                            ImageDataPosition,
                        LiveViewData.ImageData.
                            Length -
                        LiveViewData.
                            ImageDataPosition);

                    using (var res = new Bitmap(stream))
                    {
                        Bitmap bmp = res;
                        if (DetectMotion)
                        {
                            ProcessMotionDetection(bmp);
                        }

                        if (_totalframes % DesiredFrameRate == 0 && ShowHistogram)
                        {
                            ImageStatisticsHSL hslStatistics =
                                new ImageStatisticsHSL(bmp);
                            LuminanceHistogramPoints =
                                ConvertToPointCollection(
                                    hslStatistics.Luminance.Values);
                            ImageStatistics statistics = new ImageStatistics(bmp);
                            RedColorHistogramPoints = ConvertToPointCollection(
                                statistics.Red.Values);
                            GreenColorHistogramPoints = ConvertToPointCollection(
                                statistics.Green.Values);
                            BlueColorHistogramPoints = ConvertToPointCollection(
                                statistics.Blue.Values);
                        }

                        if (HighlightUnderExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(0, 5);
                            filtering.Red = new IntRange(0, 5);
                            filtering.Green = new IntRange(0, 5);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(System.Drawing.Color.Blue);
                            filtering.ApplyInPlace(bmp);
                        }

                        if (HighlightOverExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(250, 255);
                            filtering.Red = new IntRange(250, 255);
                            filtering.Green = new IntRange(250, 255);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(System.Drawing.Color.Red);
                            filtering.ApplyInPlace(bmp);
                        }

                        if (Brightness != 0)
                        {
                            BrightnessCorrection filter = new BrightnessCorrection(Brightness);
                            bmp = filter.Apply(bmp);
                        }

                        preview =
                            BitmapFactory.ConvertToPbgra32Format(
                                BitmapSourceConvert.ToBitmapSource(bmp));
                        DrawFocusPoint(preview);
                        Bitmap newbmp = bmp;
                        if (EdgeDetection)
                        {
                            var filter = new FiltersSequence(
                                Grayscale.CommonAlgorithms.BT709,
                                new HomogenityEdgeDetector()
                                );
                            newbmp = filter.Apply(bmp);
                        }

                        WriteableBitmap writeableBitmap;

                        if (BlackAndWhite)
                        {
                            Grayscale filter = new Grayscale(0.299, 0.587, 0.114);
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(
                                        filter.Apply(newbmp)));
                        }
                        else
                        {
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(newbmp));
                        }
                        DrawGrid(writeableBitmap);
                        if (RotationIndex != 0)
                        {
                            switch (RotationIndex)
                            {
                                case 1:
                                    writeableBitmap = writeableBitmap.Rotate(90);
                                    break;
                                case 2:
                                    writeableBitmap = writeableBitmap.Rotate(180);
                                    break;
                                case 3:
                                    writeableBitmap = writeableBitmap.Rotate(270);
                                    break;
                                case 4:
                                    if (LiveViewData.Rotation != 0)
                                        writeableBitmap =
                                            writeableBitmap.RotateFree(
                                                LiveViewData.Rotation, false);
                                    break;
                            }
                        }
                        if (CameraDevice.LiveViewImageZoomRatio.Value == "All")
                        {
                            preview.Freeze();
                            Preview = preview;
                            if (ShowFocusRect)
                                DrawFocusPoint(writeableBitmap);
                        }

                        writeableBitmap.Freeze();
                        Bitmap = writeableBitmap;

                        if (_totalframes%DesiredWebFrameRate == 0)
                            ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(writeableBitmap);
                    }
                    stream.Close();
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
                _retries++;
                _operInProgress = false;
            }
            _retries = 0;
            _operInProgress = false;
        }