using AI.Common.Interface; using AI.Customize.Tasks.SampleCustomizeTask; using CustomizeDiagnosisSDK.Enums; using CustomizeDiagnosisSDK.Interfaces; using CustomizeDiagnosisSDK.Models; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace CustomizeDiagnosisSDK { public class CustomizeDiagnosis { private static readonly List _relatedDllList = new List() { "AI.Customize.Tasks.SampleCustomizeTask.dll", }; private readonly ManualResetEvent _handlingImageEvent = new ManualResetEvent(true); private readonly object _detectObject = new object(); private SampleCustomizeTask _sampleCustomizeTask; private IImageProvider _usImageProvider; private EnumDetectMode _detectmode; /// /// 图片计数 /// private int _imageCounter; /// /// 帧率 /// private int _displayFps = -1; /// /// 每隔多少帧检测一次 /// private int _detectInterval; /// /// 计时用 /// private int _startTickCount = -1; /// /// 所有功能列表 /// public static List AllFunctions { get; } /// /// 检测模式 /// public EnumDetectMode DetectMode { get { return _detectmode; } set { if (_detectmode != value) { _detectmode = value; ResetParameters(); } } } /// /// 每秒检测次数 /// public int DetectTps { get; set; } /// /// 每次检测间隔时间 /// public int IntervalTime { get; set; } /// /// 模型文件夹路径 /// public string ModelFolder { get; private set; } /// /// Raised when the image evaluation is started. /// public event EventHandler StartEvaluation; /// /// Raised when the image evaluation is finished. /// public event EventHandler FinishEvaluation; /// /// Raised when event NotifyLog raised from AI diag system /// public event EventHandler NotifyLog; static CustomizeDiagnosis() { try { var sampleCustomizeTask = new SampleCustomizeTask(); var versionInfo = sampleCustomizeTask.GetInfo(); AllFunctions = new List { new FunctionInfo(EnumCustomizeDiagnosisFunction.CustomizeDiagnosis,true,Assembly.GetExecutingAssembly().GetName().Version.ToString(),null, new List { new EngineInfo(EnumCustomizeDiagnosisEngineName.CustomizeDiagnosisEngine,EnumCustomizeDiagnosisEngineType.CustomizeDiagnosisEngine,true,versionInfo.Version,versionInfo.Company,null, _relatedDllList), }), }; sampleCustomizeTask.Dispose(); } catch { } } /// /// 初始化并加载SampleCustomizeTask /// /// ImageProvider /// 检测模式 /// 每秒图片吞吐量 /// 间隔时间 /// 模型文件夹路径,默认路径为AIDiagnosisSDK.dll所在目录下的子文件夹Network public void Initialize(string modelFolder, IImageProvider usImageProvider, EnumDetectMode detectMode, int detectTps, int intervalTime) { _usImageProvider = usImageProvider; DetectMode = detectMode; ModelFolder = modelFolder; IntervalTime = intervalTime; DetectTps = detectTps; //Load SampleCustomizeTask. try { if (_sampleCustomizeTask == null) { _sampleCustomizeTask = new SampleCustomizeTask(); _sampleCustomizeTask.NotifyLog += OnNotifyLog; _sampleCustomizeTask.NotifyProcessFinish += OnNotifyProcessFinish; _sampleCustomizeTask.LoadInferNet(modelFolder); } } catch (Exception ex) { throw new Exception($"Load SampleCustomizeTask Failed!:{ex}"); } } /// /// Start the Image Provider /// public void Start() { ResetParameters(); if (_usImageProvider != null) { _usImageProvider.ImageProvided += OnUsImageProvided; _usImageProvider.Start(); } } /// /// Stop the Image Provider /// public void Stop() { if (_usImageProvider != null) { _usImageProvider.ImageProvided -= OnUsImageProvided; _usImageProvider.Stop(); } } /// /// Stop the Image Provider and Close the AutoVTI Diagnosis /// public void Close() { Stop(); _handlingImageEvent.WaitOne(); lock (_detectObject) { CloseDiagnosis(); } } /// /// 检测单张图片 /// public IDetectedObject[] DetectOneImage(ImageInputData imageData) { return HandleImage(false, imageData); } /// /// 检测单张图片 /// public string DetectOneImageAsync(ImageInputData imageData) { return HandleImageAsync(imageData); } private void OnUsImageProvided(object sender, ImageInputData imageData) { OnUsImageChanged(imageData); } private void OnUsImageChanged(ImageInputData imageData) { if (DetectMode == EnumDetectMode.TimesPerSecond)///检测模式:每秒检测几次 {//计算fps, 3秒检测一次 if (_startTickCount == -1) { _startTickCount = Environment.TickCount; HandleImage(true, imageData); } else { var fpscurrentTickCount = Environment.TickCount; var timespan = fpscurrentTickCount - _startTickCount; if (timespan >= 3000) { _displayFps = _imageCounter * 1000 / timespan; _detectInterval = (int)Math.Round((float)_displayFps / DetectTps); _imageCounter = 0; _startTickCount = Environment.TickCount; ; } if (_detectInterval > 0) { if (_imageCounter % _detectInterval == 0) { HandleImage(true, imageData); } } } _imageCounter++; if (_imageCounter > 1000000) { _imageCounter = 0; } } else///检测模式:间隔固定时间检测 { if (_startTickCount == -1) { _startTickCount = Environment.TickCount; HandleImage(true, imageData); } else { var currentTickCount = Environment.TickCount; if (IntervalTime <= currentTickCount - _startTickCount) { HandleImage(true, imageData); _startTickCount = Environment.TickCount; } } } } private IDetectedObject[] HandleImage(bool isImageProviderMode, ImageInputData imageData) { _handlingImageEvent.Reset(); IDetectedObject[] diagResult = default; try { if (isImageProviderMode) { StartEvaluation?.Invoke(this, EventArgs.Empty); } lock (_detectObject) { diagResult = _sampleCustomizeTask.ProcessOneImage(imageData); } if (isImageProviderMode) { FinishEvaluation?.Invoke(this, diagResult); } } catch (Exception ex) { NotifyLog?.Invoke(this, new LogEventArgs(EnumLogType.ErrorLog, ex.ToString())); } finally { _handlingImageEvent.Set(); } return diagResult; } private string HandleImageAsync(ImageInputData imageData) { _handlingImageEvent.Reset(); string resultId = null; try { lock (_detectObject) { resultId = _sampleCustomizeTask.AddProcessRequest(imageData); } } catch (Exception ex) { NotifyLog?.Invoke(this, new LogEventArgs(EnumLogType.ErrorLog, ex.ToString())); } return resultId; } private void OnNotifyProcessFinish(object sender, KeyValuePair e) { try { FinishEvaluation?.Invoke(e.Key, e.Value); } catch (Exception ex) { NotifyLog?.Invoke(this, new LogEventArgs(EnumLogType.ErrorLog, ex.ToString())); } finally { _handlingImageEvent.Set(); } } private void OnNotifyLog(object sender, LogEventArgs e) { NotifyLog?.Invoke(this, e); } private void ResetParameters() { _startTickCount = -1; _imageCounter = 0; _displayFps = -1; _detectInterval = 0; } private void CloseDiagnosis() { if (_sampleCustomizeTask != null) { _sampleCustomizeTask.Dispose(); _sampleCustomizeTask.NotifyLog -= OnNotifyLog; _sampleCustomizeTask.NotifyProcessFinish -= OnNotifyProcessFinish; _sampleCustomizeTask = null; } } } }