修复模型尺寸不匹配导致手部与目标检测同时失效
This commit is contained in:
parent
60b093a13f
commit
e05fd2c483
@ -367,6 +367,7 @@ public sealed class MainViewModel : BindableBase
|
||||
using var result = JsonDocument.Parse(File.ReadAllText(file));
|
||||
LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
|
||||
if (result.RootElement.TryGetProperty("onnx", out var onnx)) LatestOnnx = onnx.GetString() ?? "";
|
||||
else if (File.Exists(Path.ChangeExtension(LatestWeights, ".onnx"))) LatestOnnx = Path.ChangeExtension(LatestWeights, ".onnx");
|
||||
TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
|
||||
if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
|
||||
}
|
||||
|
||||
@ -97,6 +97,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
_camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
|
||||
|
||||
_pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result));
|
||||
_pipeline.InferenceWarning += message => _dispatcher.BeginInvoke(() => Log("warn", message));
|
||||
|
||||
// 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
|
||||
_camera.FrameArrived += OnCameraFrame;
|
||||
@ -663,10 +664,16 @@ public class SopPageViewModel : ViewModelBase
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(manifest));
|
||||
var model = document.RootElement;
|
||||
if (!model.TryGetProperty("onnx", out var onnx)) return; // 兼容尚未导出的旧训练结果。
|
||||
var modelPath = model.TryGetProperty("onnx", out var onnx) ? onnx.GetString() : null;
|
||||
if (string.IsNullOrWhiteSpace(modelPath))
|
||||
{
|
||||
// 旧版本手动导出会生成与 PT 同名的 ONNX,但未记录路径。
|
||||
if (!model.TryGetProperty("weights", out var weights)) return;
|
||||
modelPath = Path.ChangeExtension(weights.GetString(), ".onnx");
|
||||
if (!File.Exists(modelPath)) return;
|
||||
}
|
||||
if (model.GetProperty("recipeName").GetString() != recipeName)
|
||||
throw new InvalidDataException("模型与当前配方不匹配");
|
||||
var modelPath = onnx.GetString();
|
||||
if (string.IsNullOrWhiteSpace(modelPath) || !Path.IsPathRooted(modelPath) || !File.Exists(modelPath))
|
||||
throw new FileNotFoundException("配方 ONNX 文件不存在", modelPath);
|
||||
var classes = model.GetProperty("classes").Deserialize<List<string>>() ?? [];
|
||||
|
||||
@ -67,6 +67,18 @@ public class YoloDetector : IDisposable
|
||||
_session = new InferenceSession(modelPath, cpuOptions);
|
||||
UsingGpu = false;
|
||||
}
|
||||
// 固定尺寸 ONNX 的真实输入优先于配方中可能过期的尺寸。
|
||||
var dimensions = _session.InputMetadata.First().Value.Dimensions;
|
||||
if (dimensions.Length != 4 || (dimensions[1] > 0 && dimensions[1] != 3))
|
||||
throw new InvalidDataException("YOLO 输入需要 NCHW 三通道图像");
|
||||
if (dimensions[2] > 0 && dimensions[3] > 0)
|
||||
{
|
||||
if (dimensions[2] != dimensions[3])
|
||||
throw new InvalidDataException("当前 YOLO 检测器仅支持正方形模型输入");
|
||||
_inputSize = dimensions[2];
|
||||
}
|
||||
else if (_inputSize < 1)
|
||||
throw new InvalidDataException("动态尺寸模型需要配置有效的输入尺寸");
|
||||
var metadata = _session.ModelMetadata.CustomMetadataMap;
|
||||
if (metadata.TryGetValue("names", out var names))
|
||||
{
|
||||
|
||||
@ -74,6 +74,7 @@ public class DetectionPipeline : IDisposable
|
||||
|
||||
/// <summary>结果帧(在管线线程上触发)</summary>
|
||||
public event Action<FrameResult>? ResultArrived;
|
||||
public event Action<string>? InferenceWarning;
|
||||
|
||||
/// <summary>
|
||||
/// 采集 → 推理 → 结果
|
||||
@ -120,8 +121,16 @@ public class DetectionPipeline : IDisposable
|
||||
{
|
||||
if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
|
||||
{
|
||||
_hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu, options.RequireGpu);
|
||||
if (_hand.GpuFallbackReason is not null) Warnings.Add($"手部 GPU 不可用,已回退 CPU:{_hand.GpuFallbackReason}");
|
||||
try
|
||||
{
|
||||
_hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu, options.RequireGpu);
|
||||
if (_hand.GpuFallbackReason is not null) Warnings.Add($"手部 GPU 不可用,已回退 CPU:{_hand.GpuFallbackReason}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Warnings.Add("手部模型加载失败:" + ex.Message);
|
||||
if (options.RequireGpu) throw;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -237,21 +246,15 @@ public class DetectionPipeline : IDisposable
|
||||
Size = (frame.Bgr.Width, frame.Bgr.Height),
|
||||
};
|
||||
|
||||
try
|
||||
if (_yolo.IsReady)
|
||||
{
|
||||
if (_yolo.IsReady)
|
||||
{
|
||||
result.Detections = _yolo.Detect(frame.Bgr);
|
||||
}
|
||||
|
||||
if (_hand.IsReady)
|
||||
{
|
||||
result.Hands = _hand.Detect(frame.Bgr);
|
||||
}
|
||||
try { result.Detections = _yolo.Detect(frame.Bgr); }
|
||||
catch (Exception ex) { ReportInferenceWarning("YOLO 推理异常:" + ex.Message); }
|
||||
}
|
||||
catch (Exception ex)
|
||||
if (_hand.IsReady)
|
||||
{
|
||||
Warnings.Add($"推理异常:{ex.Message}");
|
||||
try { result.Hands = _hand.Detect(frame.Bgr); }
|
||||
catch (Exception ex) { ReportInferenceWarning("手部推理异常:" + ex.Message); }
|
||||
}
|
||||
|
||||
watch.Stop();
|
||||
@ -267,6 +270,13 @@ public class DetectionPipeline : IDisposable
|
||||
if (!token.IsCancellationRequested) ResultArrived?.Invoke(result);
|
||||
}
|
||||
|
||||
private void ReportInferenceWarning(string message)
|
||||
{
|
||||
if (Warnings.Contains(message)) return;
|
||||
Warnings.Add(message);
|
||||
InferenceWarning?.Invoke(message);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
|
||||
@ -135,6 +135,9 @@ internal static class Smoke
|
||||
Check(engine.Config.Sop.Model is {InputSize:960} trained&&trained.Path==modelFile&&trained.Classes.SequenceEqual(new[]{"测试零件"}),"Applying a recipe selects its trained ONNX, class order and input size");
|
||||
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model?.Path!=modelFile,"Switching recipes does not reuse the previous recipe's ONNX");
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,weights=Path.ChangeExtension(modelFile,".pt"),classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model?.Path==modelFile,"Older training records discover an existing ONNX beside their checkpoint");
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName="another-recipe",onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Mismatched recipe metadata cannot replace the configured model");
|
||||
|
||||
@ -42,6 +42,41 @@ 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");
|
||||
|
||||
if (args.Length >= 3)
|
||||
{
|
||||
var palm = Path.Combine(args[1], "palm_detection_full_Nx3x192x192_post.onnx");
|
||||
var landmark = Path.Combine(args[1], "hand_landmark_sparse_Nx3x224x224.onnx");
|
||||
using var hand = new SopHelper.Engine.Inference.MediaPipeHandDetector();
|
||||
hand.Load(palm, landmark, preferGpu: false);
|
||||
using var video = new VideoCapture(args[2]);
|
||||
using var image = new Mat();
|
||||
var found = false;
|
||||
for (var i = 0; i < 300 && video.Read(image); i++)
|
||||
if (i % 5 == 0 && hand.Detect(image).Count > 0) { found = true; break; }
|
||||
if (!found) throw new Exception("No hand detected in regression video");
|
||||
pipeline.LoadModels(new PipelineOptions { YoloModelPath=args[0], PalmModelPath=palm, LandmarkModelPath=landmark, PreferGpu=false });
|
||||
var completion = new TaskCompletionSource<SopHelper.Engine.Common.FrameResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
pipeline.ResultArrived += result => completion.TrySetResult(result);
|
||||
await pipeline.StartAsync();camera.Emit(100,image);
|
||||
var frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
|
||||
if (frame.Hands.Count == 0 || pipeline.Warnings.Count != 0) throw new Exception("Combined YOLO/hand inference failed");
|
||||
Console.WriteLine("PASS: Real YOLO and hand models process the same frame despite an outdated configured input size");
|
||||
// Reproduce the original YOLO dimension exception after loading, to verify fault isolation.
|
||||
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
var yolo = typeof(DetectionPipeline).GetField("_yolo", flags)!.GetValue(pipeline)!;
|
||||
typeof(SopHelper.Engine.Inference.YoloDetector).GetField("_inputSize", flags)!.SetValue(yolo, 641);
|
||||
var warningCount = 0;pipeline.InferenceWarning += _ => warningCount++;
|
||||
for (var i=0;i<2;i++)
|
||||
{
|
||||
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
await pipeline.StartAsync();camera.Emit(101+i,image);
|
||||
frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
|
||||
if (frame.Hands.Count == 0) throw new Exception("YOLO failure prevented hand inference");
|
||||
}
|
||||
if (warningCount != 1 || !pipeline.Warnings.Single().StartsWith("YOLO 推理异常:")) throw new Exception("Inference warnings were lost or repeated per frame");
|
||||
Console.WriteLine("PASS: A reproducible YOLO runtime failure preserves real hand detection and reports one visible warning");
|
||||
}
|
||||
|
||||
internal sealed class TestCamera : ICameraService
|
||||
{
|
||||
public bool IsConnected => true;
|
||||
@ -52,9 +87,9 @@ internal sealed class TestCamera : ICameraService
|
||||
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)
|
||||
public void Emit(long id, Mat? source = null)
|
||||
{
|
||||
using var frame=new CameraFrame {FrameId=id,Timestamp=DateTime.Now,Bgr=new Mat(32,32,MatType.CV_8UC3,Scalar.Black)};
|
||||
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;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user