using Google.Protobuf; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using Tango.Core.Helpers; using Tango.Core.Threading; using Tango.PMR.TCC; namespace Tango.TCC.BL { public class CardDetector { private ColorDetector _colorDetector; private static byte[] _defaultTemplate; private static List _defaultBenchmarks; private byte[] _sourceBitmapBytes; private ActionTimer _releaseTimer; private bool _canDetect; public bool CanDetect { get { return _canDetect; } private set { _canDetect = value; } } public CardDetector() { _releaseTimer = new ActionTimer(TimeSpan.FromSeconds(5000)); if (_defaultTemplate == null) { _defaultTemplate = File.ReadAllBytes(AssemblyHelper.GetCurrentAssemblyFolder() + "\\TCC\\template.bmp"); _defaultBenchmarks = ColorDetector.LoadBenchmarks(AssemblyHelper.GetCurrentAssemblyFolder() + "\\TCC\\benchmarks_rgb_lab.csv").ToList(); } CanDetect = true; _colorDetector = new ColorDetector(); } public Task Detect(BitmapSource source, CardDetectionConfig config) { if (!CanDetect) { throw new InvalidOperationException("Cannot detect the card at this moment. Please wait for CanDetect to be true."); } CanDetect = false; _releaseTimer.ResetReplace(() => { CanDetect = true; }); var cloned = source.Clone(); cloned.Freeze(); return Task.Factory.StartNew(() => { CardDetectionResult detectionResult = new CardDetectionResult(); detectionResult.Source = cloned; _sourceBitmapBytes = cloned.ToBytes(PixelFormats.Rgb24); Tango.TCC.CardDetector.CardDetection detector = new TCC.CardDetector.CardDetection(); var result = detector.Detect(_sourceBitmapBytes, new TCC.CardDetector.CardDetectionConfig() { DesiredBitmapWidth = config.DesiredBitmapWidth, DesiredBitmapHeight = config.DesiredBitmapHeight, TemplateBitmap = config.TemplateBitmapBytes != null ? config.TemplateBitmapBytes : _defaultTemplate, SimilarityTolerance = config.SimilarityTolerance, HistogramMethod = (int)config.HistogramMethod, EnableDoubleChecking = config.EnableDoubleChecking, EnforceBarcodeDetection = config.EnforceBarcodeDetection, //PerformCLAHE = config.PerformCLAHE, }); detectionResult.Similarity = result.Similarity; detectionResult.Barcode = result.Barcode; if (result.IsDetected) { detectionResult.IsDetected = true; detectionResult.DetectedBitmap = result.DetectedBitmap.ToBitmapSource(); var input = new DetectionInput() { Bitmap = ByteString.CopyFrom(detectionResult.DetectedBitmap.ToBmpBytes()), Columns = config.Columns, Rows = config.Rows, TargetIndex = config.TargetIndex, RequestColorMatrix = true, }; if (config.Benchmarks.Count > 0) { input.Benchmarks.AddRange(config.Benchmarks); } else { input.Benchmarks.AddRange(_defaultBenchmarks); } detectionResult.ColorDetectionOutput = _colorDetector.Detect(input); } CanDetect = true; return detectionResult; }); } } }