123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using System;
- using System.Collections.Generic;
- using Microsoft.ML.OnnxRuntime;
- using Microsoft.ML.OnnxRuntime.Tensors;
- using System.Runtime.InteropServices;
- using System.IO;
- namespace YOLODetectProcessLib
- {
- public class BreastLesionDetectImg
- {
- private IInferenceNetwork _inferNet;
- /// <summary>
- /// 通知订阅者,推理过程中发生了错误
- /// </summary>
- public event EventHandler<ErrorEventArgs> NotifyError;
- public BreastLesionDetectImg(int numCPU, string netDir)
- {
- try
- {
- _inferNet = new InferNetOnnxDetectBreastLesion();
- _inferNet.LoadNetwork(numCPU, netDir);
- }
- catch (Exception excep)
- {
- throw new Exception("Failed at Loading network:" + excep);
- }
- }
- /// <summary>
- /// 实现单幅图的乳腺病灶检测
- /// </summary>
- /// <param name="rawImg">rawImg格式图像</param>
- /// <param name="isCropped">是否已经裁切</param>
- /// <returns></returns>
- public List<DetectedBreastLesionResult> ProcessBreastLesionImg(RawImage rawImg, bool isCropped)
- {
- try
- {
- YOLODetectProcessLib.Rect cropRect = new YOLODetectProcessLib.Rect(0, 0, rawImg.Width, rawImg.Height); ;
- if (!isCropped)
- {
- if (!UsImageRegionSegUtils.CropWithCvCore(rawImg, out cropRect))
- {
- NotifyError?.Invoke(this, new ErrorEventArgs(new Exception("Failed at UsImageRegionSegUtils.CropWithCvCore")));
- }
- }
- //对一张图进行推理
- InferenceNetworkInputImage inferInput = new InferenceNetworkInputImage(rawImg, cropRect);
- var inferResult = _inferNet.Process(new InferenceNetworkInputImage[] { inferInput });
- if (inferResult == null)
- {
- NotifyError?.Invoke(this, new ErrorEventArgs(new Exception("Unexpected result size for the breast object detect model of one image.")));
- }
- if (inferResult.Length != 1)
- {
- NotifyError?.Invoke(this, new ErrorEventArgs(new Exception("Unexpected result size for the breast object detect model of one image.")));
- }
- if (inferResult[0].Length == 0)
- {
- return new List<DetectedBreastLesionResult>();
- }
- else
- {
- List<DetectedBreastLesionResult> results = new List<DetectedBreastLesionResult>();
- for (int ni = 0; ni < inferResult[0].Length; ni++)
- {
- results.Add(new DetectedBreastLesionResult(inferResult[0][ni].Label, inferResult[0][ni].Confidence, inferResult[0][ni].BoundingBox));
- }
- return results;
- }
- }
- catch (Exception excep)
- {
- NotifyError?.Invoke(this, new ErrorEventArgs(excep));
- return new List<DetectedBreastLesionResult>();
- }
- }
- /// <summary>
- /// 销毁
- /// </summary>
- public void Dispose()
- {
- DoDispose();
- GC.SuppressFinalize(this);
- }
- /// <summary>
- /// 析构函数
- /// </summary>
- ~BreastLesionDetectImg()
- {
- DoDispose();
- }
- private void DoDispose()
- {
- _inferNet?.Dispose();
- _inferNet = null;
- }
- }
- }
|