189 lines
10 KiB
C#
189 lines
10 KiB
C#
using System.Collections.Concurrent;
|
||
using OpenCvSharp;
|
||
using SopHelper.Engine.Camera;
|
||
using SopHelper.Engine.Pipeline;
|
||
using SopHelper.Engine.Inference;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.Common;
|
||
|
||
// The first step must not enable hands merely because a later step uses them.
|
||
var engine = new SopEngine { VisionDecisionClient = new ImmediateDecision() };
|
||
var config = new SopConfig();
|
||
config.Sop.Settings.AutoResetOnComplete = false;
|
||
config.Sop.Regions["work"] = new RegionDef { X1=0, Y1=0, X2=100, Y2=100 };
|
||
config.Sop.Steps = [
|
||
new StepDef { Id=1, Detection=new StepCondition { Method=ConditionMethod.TimeElapsed, DurationMs=1, StableFrames=1 } },
|
||
new StepDef { Id=2, Detection=new StepCondition { Method=ConditionMethod.HandInRegion, Region="work", StableFrames=1 } },
|
||
new StepDef { Id=3, Detection=new StepCondition { Method=ConditionMethod.TimeElapsed, DurationMs=1, StableFrames=1 } }
|
||
];
|
||
foreach(var step in config.Sop.Steps)step.Description="测试步骤完成";
|
||
engine.Load(config);
|
||
if(engine.RequiresHandDetection)throw new Exception("Idle engine enabled hands");
|
||
engine.Start();
|
||
if(engine.RequiresHandDetection)throw new Exception("Future hand step enabled hands early");
|
||
var partFrame = new FrameResult { Detections=[new Detection { Label="part", Confidence=1 }] };
|
||
await Drive(partFrame);
|
||
if(!engine.RequiresHandDetection)throw new Exception("Entering hand step did not enable hands");
|
||
engine.TogglePause();
|
||
if(engine.RequiresHandDetection)throw new Exception("Paused step enabled hands");
|
||
engine.TogglePause();
|
||
if(!engine.RequiresHandDetection)throw new Exception("Resuming hand step did not enable hands");
|
||
await Drive(new FrameResult { Hands=[new Hand { Rect=new DetRect(10,10,20,20) }] });
|
||
if(engine.RequiresHandDetection)throw new Exception("Leaving hand step did not disable hands");
|
||
await Drive(partFrame);
|
||
if(engine.State!=EngineState.Completed||engine.RequiresHandDetection)throw new Exception("Completed engine enabled hands");
|
||
engine.Reset();
|
||
if(engine.RequiresHandDetection)throw new Exception("Reset kept previous hand requirement");
|
||
foreach(var method in new[]{ConditionMethod.HandInRegion,ConditionMethod.HandMove,ConditionMethod.HandLeaveRegion})
|
||
if(!ConditionMethod.RequiresHandDetection(method.ToUpperInvariant()))throw new Exception("Hand method not recognized: "+method);
|
||
Console.WriteLine("PASS: Hand inference follows only the current running step across transitions, pause, completion and reset");
|
||
|
||
async Task Drive(FrameResult frame)
|
||
{
|
||
var previous=engine.CurrentStep?.Id;
|
||
for(var i=0;i<100 && engine.CurrentStep?.Id==previous;i++) {engine.ProcessFrame(frame,()=>[1]);await Task.Delay(10);}
|
||
}
|
||
|
||
using var camera = new TestCamera();
|
||
using var pipeline = new DetectionPipeline(camera);
|
||
var results = new ConcurrentQueue<long>();
|
||
var imageResults = new ConcurrentQueue<long>();
|
||
pipeline.ResultFrameArrived += (result, image) =>
|
||
{
|
||
if (image.Empty() || result.Size != (image.Width, image.Height))
|
||
throw new Exception("Result image is invalid or does not match the inference dimensions");
|
||
imageResults.Enqueue(result.FrameId);
|
||
};
|
||
using var entered = new ManualResetEventSlim();
|
||
using var release = new ManualResetEventSlim();
|
||
pipeline.ResultArrived += frame =>
|
||
{
|
||
results.Enqueue(frame.FrameId);
|
||
if(frame.FrameId == 1) { entered.Set(); if(!release.Wait(TimeSpan.FromSeconds(5)))throw new Exception("Worker release timed out"); }
|
||
};
|
||
if(!await pipeline.StartAsync())throw new Exception("Start failed");
|
||
// 用程序集模拟存在但不可加载的模型,验证失败不会停止原来的帧处理。
|
||
var previousWarnings = pipeline.Warnings;
|
||
var invalidModel = typeof(DetectionPipeline).Assembly.Location;
|
||
var modelLoadRejected = false;
|
||
try
|
||
{
|
||
pipeline.LoadModels(new PipelineOptions { PalmModelPath = invalidModel, LandmarkModelPath = invalidModel, RequireGpu = true });
|
||
}
|
||
catch (Exception) { modelLoadRejected = true; }
|
||
if (!modelLoadRejected || !ReferenceEquals(previousWarnings, pipeline.Warnings))
|
||
throw new Exception("模型加载失败后应保留原管线状态");
|
||
try
|
||
{
|
||
await Task.Run(() => camera.Emit(1)).WaitAsync(TimeSpan.FromSeconds(2));
|
||
if(!entered.Wait(TimeSpan.FromSeconds(2)))throw new Exception("Worker did not process frame");
|
||
// Hold the consumer busy while acquisition delivers more frames and disposes their Mats.
|
||
await Task.Run(() => { for(var id=2;id<=10;id++)camera.Emit(id); }).WaitAsync(TimeSpan.FromSeconds(2));
|
||
Console.WriteLine("PASS: Busy inference does not block camera callbacks");
|
||
}
|
||
finally { release.Set(); }
|
||
for(var i=0;i<100&&results.Count<2;i++)await Task.Delay(10);
|
||
pipeline.Stop();
|
||
if(!results.SequenceEqual(new long[]{1,10}))throw new Exception("Stale inference frames were queued: "+string.Join(',',results));
|
||
Console.WriteLine("PASS: Only the latest pending frame is processed; camera-owned Mats may be disposed immediately");
|
||
camera.Emit(11);await Task.Delay(30);
|
||
if(results.Count!=2)throw new Exception("Stopped pipeline accepted a frame");
|
||
if(!await pipeline.StartAsync())throw new Exception("Restart failed");
|
||
camera.Emit(12);
|
||
for(var i=0;i<100&&results.Count<3;i++)await Task.Delay(10);
|
||
pipeline.Stop();
|
||
if(!results.SequenceEqual(new long[]{1,10,12}))throw new Exception("Restart left stale results");
|
||
if(!imageResults.SequenceEqual(results))throw new Exception("Result images do not match the processed frames");
|
||
Console.WriteLine("PASS: Each result carries its still-valid corresponding image");
|
||
Console.WriteLine("PASS: Stop drains the worker and restart accepts only new frames");
|
||
pipeline.LoadModels(new PipelineOptions { FrameStride = 2 });
|
||
await pipeline.StartAsync();camera.Emit(13);camera.Emit(14);
|
||
for(var i=0;i<100&&results.Count<4;i++)await Task.Delay(10);
|
||
pipeline.Stop();
|
||
if(results.Last()!=14||results.Count!=4)throw new Exception("Frame stride was not preserved");
|
||
Console.WriteLine("PASS: Frame stride is preserved by the asynchronous worker");
|
||
|
||
// 视频模式应排除相机帧,且解码方可以在提交后立即释放原图。
|
||
pipeline.StartVideoInput();
|
||
if (camera.IsGrabbing) throw new Exception("Video input started camera capture");
|
||
camera.Emit(15);
|
||
using (var video = new Mat(24, 40, MatType.CV_8UC3, Scalar.Black))
|
||
{
|
||
pipeline.SubmitVideoFrame(video, 16);
|
||
pipeline.SubmitVideoFrame(video, 17);
|
||
}
|
||
for (var i = 0; i < 100 && imageResults.Count < 5; i++) await Task.Delay(10);
|
||
pipeline.StopVideoInput();
|
||
if (results.Count != 5 || results.Last() != 17 || !imageResults.SequenceEqual(results))
|
||
throw new Exception("Video input did not isolate sources or preserve stride and frame ownership");
|
||
Console.WriteLine("PASS: Video input isolates sources and uses the regular inference worker");
|
||
|
||
// 1×5×1 的微型 ONNX 模型固定返回一个 box 检测框,用真实 ORT 会话验证门控及原图坐标。
|
||
var modelDirectory = Path.Combine("scratch", "test-results");
|
||
Directory.CreateDirectory(modelDirectory);
|
||
var objectModel = Path.GetFullPath(Path.Combine(modelDirectory, "pipeline-object-test.onnx"));
|
||
File.WriteAllBytes(objectModel, Convert.FromBase64String(
|
||
"CAg6lgEKQhIKZGV0ZWN0aW9ucyIIQ29uc3RhbnQqKgoFdmFsdWUqHggBCAUIARABShQAAIBBAACAQQAAQEEAAEBBZmZmP6ABBBIMdGVzdF9vYmplY3RzWiAKBmltYWdlcxIWChQIARIQCgIIAQoCCAMKAgggCgIIIGIgCgpkZXRlY3Rpb25zEhIKEAgBEgwKAggBCgIIBQoCCAFCAhANchEKBW5hbWVzEgh7MDogYm94fQ=="));
|
||
try
|
||
{
|
||
using var objectCamera = new TestCamera();
|
||
using var objectPipeline = new DetectionPipeline(objectCamera);
|
||
using var objectFrames = new BlockingCollection<FrameResult>();
|
||
objectPipeline.ResultArrived += objectFrames.Add;
|
||
objectPipeline.LoadModels(new PipelineOptions
|
||
{
|
||
PreferGpu = false,
|
||
ObjectModel = new YoloInferenceOptions(objectModel, [], 640, .8f),
|
||
});
|
||
if (objectPipeline.Warnings.Count != 0 || objectPipeline.ObjectBackend != "CPU")
|
||
throw new Exception("物品模型加载失败:" + string.Join(";", objectPipeline.Warnings));
|
||
var demand = 0;
|
||
objectPipeline.ShouldDetectObjects = () => Volatile.Read(ref demand) == 1;
|
||
objectPipeline.StartVideoInput();
|
||
using var image = new Mat(16, 32, MatType.CV_8UC3, Scalar.Black);
|
||
FrameResult ReadFrame(int id, int requested)
|
||
{
|
||
Volatile.Write(ref demand, requested);
|
||
objectPipeline.SubmitVideoFrame(image, id);
|
||
if (!objectFrames.TryTake(out var result, TimeSpan.FromSeconds(5)) || result.FrameId != id)
|
||
throw new Exception($"未收到物品检测测试帧 {id}");
|
||
return result;
|
||
}
|
||
var idle = ReadFrame(1, 0);
|
||
var detected = ReadFrame(2, 1);
|
||
var after = ReadFrame(3, 0);
|
||
objectPipeline.StopVideoInput();
|
||
if (idle.ObjectDetectionRan || after.ObjectDetectionRan || after.Detections.Count != 0)
|
||
throw new Exception("没有检测需求时不应执行 YOLO 或复用历史结果");
|
||
var item = detected.Detections.Single();
|
||
if (!detected.ObjectDetectionRan || item.Label != "box" || item.Rect.Center != (16f, 8f))
|
||
throw new Exception("物品检测结果未映射回当前帧的原图坐标");
|
||
Console.WriteLine("PASS: YOLO 仅在有需求时执行真实推理,结果属于当前帧并使用原图坐标");
|
||
}
|
||
finally { File.Delete(objectModel); }
|
||
|
||
internal sealed class TestCamera : ICameraService
|
||
{
|
||
public bool IsConnected => true;
|
||
public bool IsGrabbing {get;private set;}
|
||
public event Action<CameraFrame>? FrameArrived;
|
||
public event Action<bool>? ConnectionChanged {add{}remove{}}
|
||
public event Action<string>? Error {add{}remove{}}
|
||
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(new List<CameraInfo>());
|
||
public Task<bool> ConnectAsync(CameraInfo camera)=>Task.FromResult(true);
|
||
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
|
||
public void Emit(long id, Mat? source = null)
|
||
{
|
||
using var frame=new CameraFrame {FrameId=id,Timestamp=DateTime.Now,Bgr=source?.Clone() ?? new Mat(32,32,MatType.CV_8UC3,Scalar.Black)};
|
||
FrameArrived?.Invoke(frame);
|
||
}
|
||
public void Stop()=>IsGrabbing=false;
|
||
public void Disconnect()=>Stop();
|
||
public void Dispose()=>Stop();
|
||
}
|
||
|
||
internal sealed class ImmediateDecision : IVisionDecisionClient
|
||
{
|
||
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request,CancellationToken token)=>Task.FromResult(new VisionDecisionResult(true,1,"测试AI确认"));
|
||
}
|