移除YOLO运行管线与模型训练及物体规则设置入口
This commit is contained in:
parent
e7f5286f19
commit
6a18cb3256
@ -13,18 +13,24 @@ internal static class RuntimeCheck
|
||||
try
|
||||
{
|
||||
var root=AppContext.BaseDirectory;
|
||||
using var yolo=new YoloDetector();using var hand=new MediaPipeHandDetector();
|
||||
yolo.Load(Path.Combine(root,"models/yolo11n.onnx"),[],preferGpu:requireGpu,requireGpu:requireGpu);
|
||||
using var hand=new MediaPipeHandDetector();
|
||||
hand.Load(Path.Combine(root,"models/palm_detection_full_Nx3x192x192_post.onnx"),Path.Combine(root,"models/hand_landmark_sparse_Nx3x224x224.onnx"),requireGpu,requireGpu);
|
||||
if(!yolo.IsReady||!hand.IsReady)throw new InvalidOperationException("模型未加载");
|
||||
if(requireGpu && (!yolo.UsingGpu || !hand.UsingGpu))throw new InvalidOperationException("要求 GPU 推理,但模型未使用 GPU");
|
||||
using var frame=new Mat(480,640,MatType.CV_8UC3,Scalar.Black);yolo.Detect(frame);hand.Detect(frame);
|
||||
if(!hand.IsReady)throw new InvalidOperationException("手部模型未加载");
|
||||
if(requireGpu && !hand.UsingGpu)throw new InvalidOperationException("要求 GPU 推理,但手部模型未使用 GPU");
|
||||
using var frame=new Mat(480,640,MatType.CV_8UC3,Scalar.Black);hand.Detect(frame);
|
||||
var config=SopConfigLoader.Parse("sop:\n name: runtime-check\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: timer\n detection:\n method: time_elapsed\n duration_ms: 1\n");
|
||||
var engine=new SopEngine();engine.Load(config);engine.Start();Thread.Sleep(10);engine.ProcessFrame(new FrameResult());
|
||||
config.Sop.Steps[0].Description="测试步骤已经完成";
|
||||
var engine=new SopEngine { VisionDecisionClient=new CheckDecision() };engine.Load(config);engine.Start();
|
||||
for(var i=0;i<100&&engine.State!=EngineState.Completed;i++) {Thread.Sleep(10);engine.ProcessFrame(new FrameResult(),()=>[1]);}
|
||||
if(engine.State!=EngineState.Completed)throw new Exception("SOP 状态机测试失败");
|
||||
Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),classes=yolo.ClassNames.Count,hand=hand.IsReady,
|
||||
yoloBackend=yolo.Backend,handBackend=hand.Backend,sop=engine.State.ToString()}));return 0;
|
||||
Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),hand=hand.IsReady,
|
||||
handBackend=hand.Backend,sop=engine.State.ToString(),aiGate="simulated"}));return 0;
|
||||
}
|
||||
catch(Exception error){Console.Error.WriteLine(error);return 1;}
|
||||
}
|
||||
private sealed class CheckDecision : IVisionDecisionClient
|
||||
{
|
||||
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request,CancellationToken token)
|
||||
=> Task.FromResult(new VisionDecisionResult(true,1,"诊断模拟确认"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,10 +25,8 @@
|
||||
<AvaloniaResource Include="Assets/**" />
|
||||
<Content Include="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../configs/**/*" Link="configs/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../models/*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../models/palm*.onnx;../../models/hand_landmark*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../models/sam2.1_hiera_tiny.pt" Link="models/sam2.1_hiera_tiny.pt" CopyToOutputDirectory="PreserveNewest" Condition="Exists('../../models/sam2.1_hiera_tiny.pt')" />
|
||||
<Content Include="../../tools/yolo11n.pt" Link="tools/yolo11n.pt" CopyToOutputDirectory="PreserveNewest" Condition="Exists('../../tools/yolo11n.pt')" />
|
||||
<Content Include="../../yolo_models/*.onnx" Link="yolo_models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../tools/worker.py" Link="tools/worker.py" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../tools/requirements.txt" Link="tools/requirements.txt" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../tools/linux/Setup-Python.sh" Link="tools/Setup-Python.sh" CopyToOutputDirectory="PreserveNewest" />
|
||||
|
||||
@ -105,13 +105,10 @@ public class RecipeNode : EditorNode
|
||||
ConditionMethod.HandInRegion,
|
||||
ConditionMethod.HandLeaveRegion,
|
||||
ConditionMethod.HandMove,
|
||||
ConditionMethod.HandNearObject,
|
||||
ConditionMethod.ObjectPresent,
|
||||
ConditionMethod.ObjectInZone,
|
||||
];
|
||||
|
||||
Hands = ["any", "left", "right"];
|
||||
ViolationTypes = [ViolationType.Timeout, ViolationType.ObjectRemoved];
|
||||
ViolationTypes = [ViolationType.Timeout];
|
||||
|
||||
AddRegionCommand = new DelegateCommand(() => { AddRegion(); Changed?.Invoke(); });
|
||||
RemoveRegionCommand = new DelegateCommand<RegionNode>(node => { RemoveRegion(node); Changed?.Invoke(); }, node => node is not null);
|
||||
@ -511,9 +508,7 @@ public class RecipeNode : EditorNode
|
||||
config.Sop.Steps.Add(def);
|
||||
}
|
||||
|
||||
var model = new ModelDef { Path = Model.Path, InputSize = Model.InputSize };
|
||||
model.Classes.AddRange(Model.Classes.Items.Select(c => c.Text).Where(c => !string.IsNullOrWhiteSpace(c)));
|
||||
config.Sop.Model = model;
|
||||
config.Sop.Model = null;
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
@ -209,8 +209,6 @@
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<TextBlock Grid.Column="2" Text="目标类别" Margin="16,0,8,0" Classes="Field" />
|
||||
<ComboBox x:Name="TargetPartPicker" Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.PartNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.TargetObject, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
||||
</Grid>
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
@ -253,8 +251,6 @@
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="置信度" Classes="Field" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Detection.MinConfidence, Mode=TwoWay}" />
|
||||
<TextBlock Grid.Column="2" Text="稳定帧" Margin="16,0,8,0" Classes="Field" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Detection.StableFrames, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
@ -268,16 +264,6 @@
|
||||
</Grid>
|
||||
<TextBlock Text="持续计时 / 手从起点移到终点 无需累计稳定帧(自带时序或瞬时语义)" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
|
||||
</StackPanel>
|
||||
<DockPanel Margin="0,10,0,6">
|
||||
<Button DockPanel.Dock="Right" Content="加必留物品" Command="{Binding MustKeep.AddCommand}" Classes="Mini" />
|
||||
<TextBlock FontSize="13" Text="{Binding MustKeep.Title}" Classes="Title" />
|
||||
</DockPanel>
|
||||
<ItemsControl ItemsSource="{Binding MustKeep.Items}" />
|
||||
<DockPanel Margin="0,10,0,6">
|
||||
<Button DockPanel.Dock="Right" Content="加完成必需物品" Command="{Binding RequiredObjects.AddCommand}" Classes="Mini" />
|
||||
<TextBlock FontSize="13" Text="{Binding RequiredObjects.Title}" Classes="Title" />
|
||||
</DockPanel>
|
||||
<ItemsControl ItemsSource="{Binding RequiredObjects.Items}" />
|
||||
<DockPanel Margin="0,10,0,6">
|
||||
<Button DockPanel.Dock="Right" Content="加违规规则" Command="{Binding ViolationRules.AddCommand}" Classes="Mini" />
|
||||
<TextBlock FontSize="13" Text="{Binding ViolationRules.Title}" Classes="Title" />
|
||||
@ -386,6 +372,10 @@
|
||||
</TabItem>
|
||||
<TabItem Header="全局设置">
|
||||
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="留空保留相机当前曝光设置" />
|
||||
</StackPanel>
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@ -426,61 +416,6 @@
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</TabItem>
|
||||
<TabItem Header="零件列表">
|
||||
<ScrollViewer Margin="10">
|
||||
<StackPanel DataContext="{Binding Recipe.Parts}">
|
||||
<TextBlock Text="在此统一维护本配方的零件名称,标注和步骤中只选择已有零件。" Margin="0,0,0,8" TextWrapping="Wrap" />
|
||||
<TextBlock Text="已被步骤或标注项目引用的名称不能删除或改名;修改列表不会改变已训练模型的类别。" Margin="0,0,0,8" TextWrapping="Wrap" />
|
||||
<Button Content="添加零件" Command="{Binding AddCommand}" HorizontalAlignment="Left" Margin="0,0,0,8" />
|
||||
<ItemsControl ItemsSource="{Binding Items}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid ColumnDefinitions="*,Auto" Classes="Row">
|
||||
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Button Grid.Column="1" Content="删" Margin="6,0,0,0" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" Classes="Mini" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
<TabItem Header="检测模型">
|
||||
<StackPanel x:Name="ModelSettings" Margin="10" DataContext="{Binding Recipe}">
|
||||
<TextBlock Text="{Binding DataContext.ModelStatus, RelativeSource={RelativeSource AncestorType=UserControl}}" TextWrapping="Wrap" Margin="0,0,0,10" />
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding Settings.ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="海康相机曝光时间,10000 为 10 毫秒;留空保留相机设置。保存配方后保留,区域取图和 SOP 启动前应用。" />
|
||||
</StackPanel>
|
||||
<StackPanel DataContext="{Binding Model}">
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="配方模型" Classes="Field" />
|
||||
<TextBlock x:Name="RecipeModelPath" Grid.Column="1" Text="{Binding Path}" TextWrapping="Wrap" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="输入尺寸" Classes="Field" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding InputSize}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<StackPanel DataContext="{Binding Classes}">
|
||||
<TextBlock FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" Classes="Title" />
|
||||
<TextBlock Text="类别由模型确定,仅供查看。零件名称请在“零件列表”中维护。" TextWrapping="Wrap" Margin="0,0,0,6" />
|
||||
<ItemsControl ItemsSource="{Binding Items}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate><TextBlock Text="{Binding Text}" /></DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</TabItem>
|
||||
<TabItem Header="SOP流程视频">
|
||||
<Grid Margin="10" RowDefinitions="Auto,*">
|
||||
<TextBlock Text="录制完整标准操作流程,视频单独保存在当前配方的 sop_stand 目录。暂停期间不计时,累计录制最长5分钟。新配方请先保存。" TextWrapping="Wrap" Margin="0,0,0,10" />
|
||||
@ -521,12 +456,6 @@
|
||||
</Grid>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
<TabItem Header="零件标注与训练">
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
<TextBlock Text="标注和训练固定使用当前配方。新配方请先保存;修改零件列表后,请保存配方再开始训练。" TextWrapping="Wrap" Margin="10,8,10,0" />
|
||||
<ContentControl Grid.Row="1" Content="{Binding TrainingView}" IsVisible="{Binding HasSopRecording}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
<Grid Grid.Row="2" Margin="0,10,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
|
||||
@ -28,10 +28,6 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private readonly HashSet<EditorNode> _observedStepNodes = [];
|
||||
private string _saveStatus = "";
|
||||
private bool _closingDialog;
|
||||
private ModelDef? _managedModel;
|
||||
private string _modelStatus = "请先保存配方,再训练配方模型";
|
||||
public string ModelStatus { get => _modelStatus; private set => SetProperty(ref _modelStatus, value); }
|
||||
|
||||
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
|
||||
public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? "";
|
||||
private BitmapSource? _previewImage;
|
||||
@ -41,10 +37,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private CameraInfo? _cameraInfo;
|
||||
private Func<CameraInfo?>? _selectedCameraProvider;
|
||||
private Func<bool> _canUseCamera = () => true;
|
||||
private WorkerClient? _trainingWorker;
|
||||
private SopHelper.Training.TrainingPage? _trainingView;
|
||||
private Task? _shutdown;
|
||||
public SopHelper.Training.TrainingPage? TrainingView { get => _trainingView; private set => SetProperty(ref _trainingView, value); }
|
||||
private SopHelper.Training.CameraViewModel? _sopRecording;
|
||||
public SopHelper.Training.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
|
||||
public bool HasSopRecording => SopRecording is not null;
|
||||
@ -138,10 +131,6 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
|
||||
|
||||
Recipe = RecipeNode.From(config, fileName, _isNew);
|
||||
var partNames = PartCatalog.Read(config, string.IsNullOrEmpty(_path) ? null : Path.GetDirectoryName(_path));
|
||||
Recipe.Parts.Items.Clear();
|
||||
foreach (var name in partNames)
|
||||
Recipe.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = Recipe.Parts.RemoveCommand });
|
||||
Recipe.Changed += RefreshWarnings;
|
||||
InitializeRecipeTools();
|
||||
|
||||
@ -154,7 +143,6 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
/// <inheritdoc />
|
||||
public void OnDialogClosed()
|
||||
{
|
||||
if (TrainingView is not null) TrainingView.Model.PropertyChanged -= TrainingModelChanged;
|
||||
_ = ShutdownAsync();
|
||||
Recipe.Changed -= RefreshWarnings;
|
||||
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
|
||||
@ -169,25 +157,10 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
var recipeDirectory = Path.GetDirectoryName(_path)!;
|
||||
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
|
||||
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true, selectedCameraProvider: _selectedCameraProvider);
|
||||
_trainingWorker = new WorkerClient();
|
||||
var training = new SopHelper.Training.MainViewModel(_trainingWorker);
|
||||
training.BindRecipe(Path.GetFileNameWithoutExtension(_path));
|
||||
training.PropertyChanged += TrainingModelChanged;
|
||||
TrainingView = new SopHelper.Training.TrainingPage(training, null, embedded: true,
|
||||
selectedCameraProvider: _selectedCameraProvider,
|
||||
canOpenCamera: () => _canUseCamera() && !IsCapturing && SopRecording?.IsPreviewing != true);
|
||||
RaisePropertyChanged(nameof(HasSopRecording));
|
||||
}
|
||||
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
|
||||
private async Task ShutdownCoreAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (TrainingView is not null) { TrainingView.IsEnabled = false; await TrainingView.ShutdownAsync(); }
|
||||
}
|
||||
catch (Exception error) { SaveStatus = "关闭训练任务时出错:" + error.Message; }
|
||||
finally { _trainingWorker?.Dispose(); await ShutdownSopRecordingAsync(); }
|
||||
}
|
||||
private Task ShutdownCoreAsync() => ShutdownSopRecordingAsync();
|
||||
public async Task ShutdownSopRecordingAsync()
|
||||
{
|
||||
if (SopRecording is null) return;
|
||||
@ -220,21 +193,6 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
catch (Exception ex) { PreviewStatus = "打开图片失败:" + ex.Message; }
|
||||
}
|
||||
|
||||
private void TrainingModelChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(SopHelper.Training.MainViewModel.LatestOnnx) ||
|
||||
(e.PropertyName == nameof(SopHelper.Training.MainViewModel.IsBusy) && TrainingView?.Model.IsBusy == false)) RefreshWarnings();
|
||||
}
|
||||
private void RefreshManagedModel()
|
||||
{
|
||||
_managedModel = null;
|
||||
var status = "请先保存配方,再训练配方模型";
|
||||
if (!string.IsNullOrEmpty(_path))
|
||||
_managedModel = RecipeModelResolver.Load(Path.GetDirectoryName(_path)!, Path.GetFileNameWithoutExtension(_path), out status);
|
||||
ModelStatus = status;
|
||||
Recipe.Model.CopyFrom(_managedModel ?? new ModelDef());
|
||||
}
|
||||
|
||||
private async Task CaptureImageAsync()
|
||||
{
|
||||
if (IsCapturing || _camera is null || _cameraInfo is null) return;
|
||||
@ -307,22 +265,14 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
|
||||
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
RefreshManagedModel();
|
||||
var config = Recipe.ToConfig();
|
||||
config.Sop.Model = _managedModel is null ? null : new ModelDef
|
||||
{
|
||||
Path = Path.GetRelativePath(Path.GetDirectoryName(path)!, _managedModel.Path),
|
||||
InputSize = _managedModel.InputSize, Classes = _managedModel.Classes.ToList()
|
||||
};
|
||||
PartCatalog.Validate(config, Path.GetDirectoryName(path));
|
||||
config.Sop.Model = null;
|
||||
var saved = SopConfigLoader.Save(config, path);
|
||||
|
||||
_path = path;
|
||||
_isNew = false;
|
||||
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
|
||||
InitializeRecipeTools();
|
||||
RefreshManagedModel();
|
||||
TrainingView?.Model.RefreshPartNames();
|
||||
RaisePropertyChanged(nameof(FileNameText));
|
||||
RaisePropertyChanged(nameof(Title));
|
||||
|
||||
@ -365,11 +315,8 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
}
|
||||
Warnings.Clear();
|
||||
|
||||
RefreshManagedModel();
|
||||
var config = Recipe.ToConfig();
|
||||
config.Sop.Model = _managedModel;
|
||||
try { PartCatalog.Validate(config, string.IsNullOrEmpty(_path) ? null : Path.GetDirectoryName(_path)); }
|
||||
catch (InvalidDataException error) { Warnings.Add(error.Message); }
|
||||
config.Sop.Model = null;
|
||||
SopConfigLoader.Validate(config);
|
||||
|
||||
foreach (var warning in config.Warnings) Warnings.Add(warning);
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel Margin="10" MaxWidth="760" HorizontalAlignment="Stretch" Spacing="12">
|
||||
<TextBlock Text="运行设置" Classes="Title" />
|
||||
<TextBlock Text="配置相机、配方和检测参数,运行期间不可修改。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="配置相机、配方和手部采集参数,运行期间不可修改。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<Border Classes="panel">
|
||||
<StackPanel>
|
||||
<TextBlock Text="相机与配方" Classes="Title" />
|
||||
@ -39,16 +39,6 @@
|
||||
<Button Grid.Column="5" Content="删除" Margin="6,0,0,0" Padding="10,4" Command="{Binding DeleteRecipeCommand}" Foreground="{StaticResource Ng}" />
|
||||
</Grid>
|
||||
<Button Content="打开配方文件夹" Command="{Binding OpenRecipeFolderCommand}" Margin="0,8,0,0" HorizontalAlignment="Left" />
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="阈值" Width="40" />
|
||||
<Slider IsEnabled="{Binding CanSelectCamera}" Grid.Column="1" Minimum="0.1" Maximum="0.95" TickFrequency="0.05" IsSnapToTickEnabled="True" Value="{Binding Confidence}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding Confidence, StringFormat={}{0:F2}}" HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
|
||||
</Grid>
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@ -65,7 +55,7 @@
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="当前已应用配方" Classes="Title" />
|
||||
<TextBlock Text="{Binding ActiveRecipe}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="选择配方后点击“应用”;阈值和抽帧参数在下次开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="选择配方后点击“应用”;抽帧参数在下次开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<TextBlock Text="{Binding StatusText}" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
|
||||
@ -46,7 +46,6 @@
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<local:DetectionOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
|
||||
<local:HandOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
|
||||
</Grid>
|
||||
</Viewbox>
|
||||
|
||||
@ -244,7 +244,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
}
|
||||
|
||||
/// <summary>实际推理设备,CPU 回退时直接显示在运行界面。</summary>
|
||||
public string InferenceBackendText => $"手部:{_pipeline.HandBackend};目标:{_pipeline.YoloBackend}";
|
||||
private static string VisionProviderName => Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.ToLowerInvariant() switch { "laya" => "Laya", "chat-completions" => "视觉模型", _ => "D3-lite" };
|
||||
public string InferenceBackendText => $"手部:{_pipeline.HandBackend};步骤确认:{VisionProviderName}";
|
||||
|
||||
/// <summary>是否运行中</summary>
|
||||
public bool IsRunning
|
||||
@ -292,7 +293,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
set { SetProperty(ref _frameHeight, value); }
|
||||
}
|
||||
|
||||
/// <summary>置信度阈值(透传给 YOLO)</summary>
|
||||
/// <summary>旧版阈值字段(不参与当前推理)</summary>
|
||||
public double Confidence
|
||||
{
|
||||
get { return _confidence; }
|
||||
@ -726,8 +727,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
}
|
||||
}
|
||||
|
||||
// 阈值 / 抽帧从界面参数覆盖配方默认值
|
||||
_pipeline.SetThresholds((float)Confidence, 0.45f);
|
||||
// 抽帧从界面参数覆盖配方默认值
|
||||
_engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
|
||||
|
||||
if (!await _pipeline.StartAsync())
|
||||
@ -757,16 +757,12 @@ public class SopPageViewModel : ViewModelBase
|
||||
|
||||
var config = SopConfigLoader.Load(path);
|
||||
|
||||
LoadTrainedRecipeModel(config);
|
||||
config.Sop.Model = null;
|
||||
_engine.Load(config);
|
||||
|
||||
var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
|
||||
// 仅使用本配方训练发布的 ONNX。
|
||||
var options = new PipelineOptions
|
||||
{
|
||||
YoloModelPath = config.Sop.Model?.Path,
|
||||
YoloClasses = config.Sop.Model?.Classes ?? [],
|
||||
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
|
||||
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
|
||||
PalmModelPath = needsHands ? ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx") : null,
|
||||
LandmarkModelPath = needsHands ? ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx") : null,
|
||||
@ -777,7 +773,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
try { _pipeline.LoadModels(options); }
|
||||
finally { RaisePropertyChanged(nameof(InferenceBackendText)); }
|
||||
ActiveRecipe = SelectedRecipe;
|
||||
Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}");
|
||||
Log("info", $"推理设备:手部={_pipeline.HandBackend},步骤确认={VisionProviderName}");
|
||||
|
||||
ClearProcessImages();
|
||||
StepCards.Clear();
|
||||
@ -802,26 +798,6 @@ public class SopPageViewModel : ViewModelBase
|
||||
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
|
||||
}
|
||||
|
||||
private void LoadTrainedRecipeModel(SopConfig config)
|
||||
{
|
||||
var needsObjects = config.Sop.Steps.Any(s => s.Detection?.Method?.ToLowerInvariant() is
|
||||
ConditionMethod.ObjectPresent or ConditionMethod.ObjectInZone or ConditionMethod.HandNearObject
|
||||
|| s.MustKeep.Count > 0 || s.RequiredObjects.Count > 0);
|
||||
if (!needsObjects)
|
||||
{
|
||||
config.Sop.Model = null;
|
||||
config.Warnings.Clear(); SopConfigLoader.Validate(config);
|
||||
Log("info", "当前配方仅使用手部/计时和可选 AI 确认,不加载 YOLO 模型");
|
||||
return;
|
||||
}
|
||||
var recipeName = Path.GetFileNameWithoutExtension(SelectedRecipe);
|
||||
var directory = DesktopPlatform.Recipes.DirectoryFor(recipeName!);
|
||||
config.Sop.Model = SopHelper.Engine.Training.RecipeModelResolver.Load(directory, recipeName!, out var status);
|
||||
config.Warnings.Clear(); SopConfigLoader.Validate(config);
|
||||
Log(config.Sop.Model is null && File.Exists(Path.Combine(directory, "latest-model.json")) ? "warn" : "info",
|
||||
config.Sop.Model is { } model ? $"已加载配方训练模型:{model.Path}" : status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
|
||||
/// </summary>
|
||||
|
||||
@ -1,440 +0,0 @@
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Common;
|
||||
using YamlDotNet.Serialization;
|
||||
|
||||
namespace SopHelper.Engine.Inference;
|
||||
|
||||
/// <summary>
|
||||
/// YOLOv8 检测(纯 ONNX Runtime,自带 DFL 解码 + NMS,不依赖 YoloDotNet)。
|
||||
/// 不用 YoloDotNet 的理由:它是 GPL-3.0-only,会污染整个骨架的 MIT;且拖 SixLabors 全家。
|
||||
/// </summary>
|
||||
public class YoloDetector : IDisposable
|
||||
{
|
||||
private InferenceSession? _session;
|
||||
|
||||
private string[] _classNames = [];
|
||||
private float _confThreshold = 0.4f;
|
||||
private float _nmsThreshold = 0.45f;
|
||||
private int _inputSize = 640;
|
||||
|
||||
public IReadOnlyList<string> ClassNames => _classNames;
|
||||
|
||||
/// <summary>模型是否就绪</summary>
|
||||
public bool IsReady => _session is not null;
|
||||
|
||||
/// <summary>实际使用的设备</summary>
|
||||
public bool UsingGpu { get; private set; }
|
||||
private string _gpuBackend = "CPU";
|
||||
public string Backend => !IsReady ? "未加载" : UsingGpu ? _gpuBackend : "CPU";
|
||||
public string? GpuFallbackReason { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。
|
||||
/// </summary>
|
||||
public void Load(string modelPath, IReadOnlyList<string> classNames, int inputSize = 640, bool preferGpu = true, bool requireGpu = false)
|
||||
{
|
||||
Dispose();
|
||||
UsingGpu = false;
|
||||
GpuFallbackReason = null;
|
||||
if (requireGpu && !preferGpu) throw new ArgumentException("要求 GPU 推理时必须启用 preferGpu");
|
||||
if (!File.Exists(modelPath)) return;
|
||||
|
||||
_classNames = classNames.ToArray();
|
||||
_inputSize = inputSize;
|
||||
|
||||
if (preferGpu)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var options = InferenceSessionOptions.Create(true, "yolo", out _gpuBackend);
|
||||
_session = new InferenceSession(modelPath, options);
|
||||
UsingGpu = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
GpuFallbackReason = ex.Message;
|
||||
if (requireGpu) throw new InvalidOperationException("YOLO GPU 推理初始化失败:" + ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_session is null)
|
||||
{
|
||||
using var cpuOptions = InferenceSessionOptions.Create(false, "yolo", out _);
|
||||
_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))
|
||||
{
|
||||
var labels = new DeserializerBuilder().Build().Deserialize<Dictionary<int, string>>(names);
|
||||
if (labels is not null && labels.Count > 0)
|
||||
{
|
||||
if (!labels.Keys.Order().SequenceEqual(Enumerable.Range(0, labels.Count)))
|
||||
throw new InvalidDataException("模型类别索引必须从 0 连续编号");
|
||||
if (_classNames.Length == 0) _classNames = labels.OrderBy(p => p.Key).Select(p => p.Value).ToArray();
|
||||
else if (_classNames.Length != labels.Count)
|
||||
throw new InvalidDataException($"模型包含 {labels.Count} 个类别,配方却配置了 {_classNames.Length} 个,请使用与模型一致的类别表");
|
||||
}
|
||||
}
|
||||
if (_classNames.Length == 0) throw new InvalidDataException("模型没有类别名称,请填写类别表或使用含 names 元数据的 ONNX");
|
||||
}
|
||||
catch { Dispose(); throw; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 阈值
|
||||
/// </summary>
|
||||
public void SetThresholds(float conf, float nms)
|
||||
{
|
||||
_confThreshold = conf;
|
||||
_nmsThreshold = nms;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推理一帧(BGR)
|
||||
/// </summary>
|
||||
public List<Detection> Detect(Mat bgr)
|
||||
{
|
||||
var list = new List<Detection>();
|
||||
if (!IsReady) return list;
|
||||
|
||||
// letterbox:保持长宽比缩放,边缘补灰
|
||||
var inputSize = _inputSize;
|
||||
|
||||
var scale = Math.Min((double)inputSize / bgr.Width, (double)inputSize / bgr.Height);
|
||||
var newW = (int)Math.Round(bgr.Width * scale);
|
||||
var newH = (int)Math.Round(bgr.Height * scale);
|
||||
var padX = (inputSize - newW) / 2;
|
||||
var padY = (inputSize - newH) / 2;
|
||||
|
||||
using var rgb = new Mat();
|
||||
Cv2.CvtColor(bgr, rgb, ColorConversionCodes.BGR2RGB);
|
||||
|
||||
using var resized = new Mat();
|
||||
Cv2.Resize(rgb, resized, new Size(newW, newH));
|
||||
|
||||
using var canvas = new Mat(inputSize, inputSize, MatType.CV_8UC3, new Scalar(114, 114, 114));
|
||||
using (var roi = new Mat(canvas, new Rect(padX, padY, newW, newH)))
|
||||
{
|
||||
resized.CopyTo(roi);
|
||||
}
|
||||
|
||||
var tensor = TensorPreprocessing.FromRgb(canvas);
|
||||
|
||||
var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor(InputName(), tensor) };
|
||||
|
||||
using var results = _session!.Run(inputs);
|
||||
var output = results.FirstOrDefault();
|
||||
if (output is null) return list;
|
||||
|
||||
var t = output.AsTensor<float>();
|
||||
if (t is null) return list;
|
||||
|
||||
// 标准 YOLOv8 / YOLO11 导出:[1, 4+nc, anchors]。
|
||||
// 实测(yolo11n.onnx,api.github.com 取的 YoloSharp 那份):前 4 通道是**已解码的
|
||||
// cx,cy,w,h**(letterbox 空间像素,取值范围 3~637),DFL 已烘焙进图,
|
||||
// 再跑一次 16-bin 期望就是乱值。
|
||||
var decoded = t.Dimensions.Length == 3 && t.Dimensions[1] == 4 + _classNames.Length;
|
||||
|
||||
// 实测(yolo11n.onnx,YoloSharp 那份)类别块 min=0、max=0.61、8.8% 恰好为 0
|
||||
// → sigmoid 已烘进图里,类别通道本身就是概率;官方标准导出才是 logits(含大量负值)。
|
||||
// 判错会把背景 0.0 抬成 0.5 越过阈值——每帧两千多个框就是这么来的。
|
||||
var candidates = new List<Detection>();
|
||||
|
||||
if (decoded)
|
||||
{
|
||||
var isLogit = ClassChannelsAreLogits(t, 4);
|
||||
var anchorCount = t.Dimensions[2];
|
||||
|
||||
for (var a = 0; a < anchorCount; a++)
|
||||
{
|
||||
var best = 0;
|
||||
var bestRaw = float.MinValue;
|
||||
|
||||
for (var c = 0; c < _classNames.Length; c++)
|
||||
{
|
||||
var raw = t[0, 4 + c, a];
|
||||
if (raw > bestRaw)
|
||||
{
|
||||
bestRaw = raw;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
|
||||
var score = isLogit ? Sigmoid(bestRaw) : bestRaw;
|
||||
if (score < _confThreshold) continue;
|
||||
|
||||
// 实测:前 4 通道 = cx,cy,w,h(letterbox 空间像素),DFL 已烘焙,直接用
|
||||
var cx = t[0, 0, a];
|
||||
var cy = t[0, 1, a];
|
||||
var bw = t[0, 2, a];
|
||||
var bh = t[0, 3, a];
|
||||
|
||||
// letterbox → 原图
|
||||
candidates.Add(new Detection
|
||||
{
|
||||
Label = _classNames[best],
|
||||
Confidence = score,
|
||||
Rect = new DetRect(
|
||||
(float)((cx - bw / 2 - padX) / scale),
|
||||
(float)((cy - bh / 2 - padY) / scale),
|
||||
(float)(bw / scale),
|
||||
(float)(bh / scale)),
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (t.Dimensions.Length == 3 && t.Dimensions[1] == 64 + _classNames.Length)
|
||||
{
|
||||
// 未烘焙 DFL 的导出:[1, 4×16 + nc, anchors],前 64 行才是 4 组 16-bin 分布
|
||||
var isLogit = ClassChannelsAreLogits(t, 64);
|
||||
var anchorCount = t.Dimensions[2];
|
||||
|
||||
for (var a = 0; a < anchorCount; a++)
|
||||
{
|
||||
var best = 0;
|
||||
var bestRaw = float.MinValue;
|
||||
|
||||
for (var c = 0; c < _classNames.Length; c++)
|
||||
{
|
||||
var raw = t[0, 64 + c, a];
|
||||
if (raw > bestRaw)
|
||||
{
|
||||
bestRaw = raw;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
|
||||
var score = isLogit ? Sigmoid(bestRaw) : bestRaw;
|
||||
if (score < _confThreshold) continue;
|
||||
|
||||
var (cx, cy) = DflBox(t, a, anchorCount, inputSize, scale, padX, padY, out var w, out var h);
|
||||
|
||||
candidates.Add(new Detection
|
||||
{
|
||||
Label = _classNames[best],
|
||||
Confidence = score,
|
||||
Rect = new DetRect(cx - w / 2f, cy - h / 2f, w, h),
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (t.Dimensions.Length == 3 && t.Dimensions[2] == 6)
|
||||
{
|
||||
// YOLO26 / 端到端版:[1, N, 6] = [x1, y1, x2, y2, score, class]
|
||||
var n = t.Dimensions.Length >= 2 ? t.Dimensions[1] : 0;
|
||||
var cols = t.Dimensions.Length >= 3 ? t.Dimensions[2] : 0;
|
||||
if (cols < 6) return list;
|
||||
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var score = t[0, i, 4];
|
||||
if (score < _confThreshold) continue;
|
||||
|
||||
var cls = (int)t[0, i, 5];
|
||||
|
||||
var x1 = (float)((t[0, i, 0] - padX) / scale);
|
||||
var y1 = (float)((t[0, i, 1] - padY) / scale);
|
||||
var x2 = (float)((t[0, i, 2] - padX) / scale);
|
||||
var y2 = (float)((t[0, i, 3] - padY) / scale);
|
||||
|
||||
candidates.Add(new Detection
|
||||
{
|
||||
Label = cls >= 0 && cls < _classNames.Length ? _classNames[cls] : cls.ToString(),
|
||||
Confidence = score,
|
||||
Rect = new DetRect(x1, y1, x2 - x1, y2 - y1),
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidDataException($"不支持的检测输出 [{string.Join(",", t.Dimensions.ToArray())}],请检查类别表和 ONNX 导出设置");
|
||||
}
|
||||
|
||||
list.AddRange(Nms(candidates));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DFL(Distribution Focal Loss)解码:对 4 组 16 bin 做 softmax 取期望,得到边界框
|
||||
/// </summary>
|
||||
private static (float Cx, float Cy) DflBox(Tensor<float> t, int anchor, int anchorCount,
|
||||
int inputSize, double scale, int padX, int padY, out float w, out float h)
|
||||
{
|
||||
// YOLOv8 锚点是三层拼接(80×80 + 40×40 + 20×20 = 8400),不是单个方格网格。
|
||||
// 按 [8,16,32] 顺序逐层行优先消耗 anchor 索引,才能还原正确的 grid 与 stride。
|
||||
var (col, row, stride) = AnchorGrid(anchor, inputSize);
|
||||
|
||||
// 锚点中心(letterbox 空间)→ 减 padding 除 scale 回原图
|
||||
var anchorCx = (col + 0.5f) * stride;
|
||||
var anchorCy = (row + 0.5f) * stride;
|
||||
|
||||
static float DflBin(Tensor<float> tt, int channel, int a)
|
||||
{
|
||||
// 16 bin 的 softmax 期望
|
||||
var max = float.MinValue;
|
||||
for (var d = 0; d < 16; d++) max = Math.Max(max, tt[0, channel, a]);
|
||||
|
||||
var sum = 0.0;
|
||||
var exp = new double[16];
|
||||
for (var d = 0; d < 16; d++)
|
||||
{
|
||||
exp[d] = Math.Exp(tt[0, channel, a] - max);
|
||||
sum += exp[d];
|
||||
}
|
||||
|
||||
var expected = 0.0;
|
||||
for (var d = 0; d < 16; d++) expected += d * (exp[d] / sum);
|
||||
|
||||
return (float)expected;
|
||||
}
|
||||
|
||||
var lt = DflBin(t, 0, anchor);
|
||||
var tp = DflBin(t, 1, anchor);
|
||||
var rb = DflBin(t, 2, anchor);
|
||||
var db = DflBin(t, 3, anchor);
|
||||
|
||||
// DFL 距离以"特征图 stride"为单位,先在 letterbox 空间算出四边,再统一映射回原图
|
||||
var leftIn = anchorCx - lt * stride;
|
||||
var topIn = anchorCy - tp * stride;
|
||||
var rightIn = anchorCx + rb * stride;
|
||||
var bottomIn = anchorCy + db * stride;
|
||||
|
||||
var left = (float)((leftIn - padX) / scale);
|
||||
var top = (float)((topIn - padY) / scale);
|
||||
var right = (float)((rightIn - padX) / scale);
|
||||
var bottom = (float)((bottomIn - padY) / scale);
|
||||
|
||||
w = right - left;
|
||||
h = bottom - top;
|
||||
|
||||
return ((left + right) / 2f, (top + bottom) / 2f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 类别通道是 logits,必须先过 sigmoid 才能和置信度阈值比
|
||||
/// (之前 conf=68 那种数就是因为漏了这步,直接把 logits 当概率)
|
||||
/// </summary>
|
||||
private static float Sigmoid(float x) => (float)(1.0 / (1.0 + Math.Exp(-x)));
|
||||
|
||||
/// <summary>
|
||||
/// 把拼接后的锚点索引还原为 (列, 行, stride)。
|
||||
/// YOLOv8 检测头输出是 P3/P4/P5 三层按 [8,16,32] 顺序拼接,每层内部行优先。
|
||||
/// </summary>
|
||||
private static (int Col, int Row, int Stride) AnchorGrid(int anchor, int inputSize)
|
||||
{
|
||||
int[] strides = [8, 16, 32];
|
||||
|
||||
foreach (var stride in strides)
|
||||
{
|
||||
var grid = inputSize / stride;
|
||||
var count = grid * grid;
|
||||
|
||||
if (anchor >= count)
|
||||
{
|
||||
anchor -= count;
|
||||
continue;
|
||||
}
|
||||
|
||||
return (anchor % grid, anchor / grid, stride);
|
||||
}
|
||||
|
||||
// 索引超出总锚点数(理论上不会走到)
|
||||
return (0, 0, strides[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 类别块是 logits(要 sigmoid)还是已烘好的概率(不能再见 sigmoid):
|
||||
/// 只看类别块自己有没有负值(坐标行在暗帧上会出负值,不能拿来当判据)。
|
||||
/// </summary>
|
||||
private bool ClassChannelsAreLogits(Tensor<float> t, int classStart)
|
||||
{
|
||||
var anchors = t.Dimensions[2];
|
||||
|
||||
for (var a = 0; a < anchors; a++)
|
||||
{
|
||||
for (var c = 0; c < _classNames.Length; c++)
|
||||
if (t[0, classStart + c, a] < 0f) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NMS
|
||||
/// </summary>
|
||||
private List<Detection> Nms(List<Detection> list)
|
||||
{
|
||||
if (list.Count == 0) return list;
|
||||
|
||||
var keep = new List<Detection>();
|
||||
|
||||
foreach (var group in list.GroupBy(d => d.Label))
|
||||
{
|
||||
var sorted = group.OrderByDescending(d => d.Confidence).ToList();
|
||||
|
||||
while (sorted.Count > 0)
|
||||
{
|
||||
var best = sorted[0];
|
||||
keep.Add(best);
|
||||
sorted.RemoveAt(0);
|
||||
|
||||
sorted = sorted.Where(d => IoU(best.Rect, d.Rect) <= _nmsThreshold).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
return keep;
|
||||
}
|
||||
|
||||
private static float IoU(DetRect a, DetRect b)
|
||||
{
|
||||
var x1 = Math.Max(a.X, b.X);
|
||||
var y1 = Math.Max(a.Y, b.Y);
|
||||
var x2 = Math.Min(a.Right, b.Right);
|
||||
var y2 = Math.Min(a.Bottom, b.Bottom);
|
||||
|
||||
var inter = Math.Max(0, x2 - x1) * Math.Max(0, y2 - y1);
|
||||
var union = a.W * a.H + b.W * b.H - inter;
|
||||
|
||||
return union <= 0 ? 0 : inter / union;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取模型真实输入节点名(不写死 "input",各家导出不一样)
|
||||
/// </summary>
|
||||
private string InputName()
|
||||
{
|
||||
try
|
||||
{
|
||||
// InputMetadata 是字典,键就是节点名
|
||||
return _session!.InputMetadata.Keys.First();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "images";
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_session?.Dispose();
|
||||
_session = null;
|
||||
UsingGpu = false;
|
||||
}
|
||||
}
|
||||
@ -10,15 +10,6 @@ namespace SopHelper.Engine.Pipeline;
|
||||
/// </summary>
|
||||
public class PipelineOptions
|
||||
{
|
||||
/// <summary>YOLO 模型路径(可空:纯手部配方不需要)</summary>
|
||||
public string? YoloModelPath { get; set; }
|
||||
|
||||
/// <summary>类别名,顺序必须与训练一致</summary>
|
||||
public List<string> YoloClasses { get; set; } = [];
|
||||
|
||||
/// <summary>YOLO 输入尺寸</summary>
|
||||
public int YoloInputSize { get; set; } = 640;
|
||||
|
||||
/// <summary>MediaPipe 手掌模型(可空:不需要手部的配方不加载)</summary>
|
||||
public string? PalmModelPath { get; set; }
|
||||
|
||||
@ -46,7 +37,6 @@ public class PipelineOptions
|
||||
public class DetectionPipeline : IDisposable
|
||||
{
|
||||
private readonly ICameraService _camera;
|
||||
private readonly YoloDetector _yolo = new();
|
||||
private readonly MediaPipeHandDetector _hand = new();
|
||||
|
||||
private PipelineOptions _options = new();
|
||||
@ -70,7 +60,6 @@ public class DetectionPipeline : IDisposable
|
||||
public double AvgInferenceMs { get; private set; }
|
||||
|
||||
public string HandBackend => _hand.Backend;
|
||||
public string YoloBackend => _yolo.Backend;
|
||||
|
||||
/// <summary>每帧查询当前步骤是否需要手部;未设置时保持独立管线的默认检测行为。</summary>
|
||||
public Func<bool>? ShouldDetectHands { get; set; }
|
||||
@ -99,30 +88,8 @@ public class DetectionPipeline : IDisposable
|
||||
StopProcessing();
|
||||
_options = options;
|
||||
Warnings = [];
|
||||
_yolo.Dispose();
|
||||
_hand.Dispose();
|
||||
|
||||
if (options.YoloModelPath is not null)
|
||||
{
|
||||
if (File.Exists(options.YoloModelPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
_yolo.Load(options.YoloModelPath, options.YoloClasses, options.YoloInputSize, options.PreferGpu, options.RequireGpu);
|
||||
if (_yolo.GpuFallbackReason is not null) Warnings.Add($"YOLO GPU 不可用,已回退 CPU:{_yolo.GpuFallbackReason}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Warnings.Add("目标检测模型加载失败:" + ex.Message);
|
||||
if (options.RequireGpu) throw;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Warnings.Add($"YOLO 模型不存在:{options.YoloModelPath}(目标类条件不会判定)");
|
||||
}
|
||||
}
|
||||
|
||||
if (options.PalmModelPath is not null && options.LandmarkModelPath is not null)
|
||||
{
|
||||
if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
|
||||
@ -148,14 +115,6 @@ public class DetectionPipeline : IDisposable
|
||||
MediaPipeHandDetector.DefaultKeypointThreshold, Math.Max(1, options.MaxHands));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 阈值透传给检测器(界面上的 YOLO 阈值滑条走这里)
|
||||
/// </summary>
|
||||
public void SetThresholds(float yoloConf, float yoloNms)
|
||||
{
|
||||
_yolo.SetThresholds(yoloConf, yoloNms);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动(相机需已连接)
|
||||
/// </summary>
|
||||
@ -227,7 +186,7 @@ public class DetectionPipeline : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理一帧:按 stride 抽帧,跑 YOLO + 手部,合成 FrameResult
|
||||
/// 处理一帧:按 stride 抽帧,运行手部推理,合成 FrameResult
|
||||
/// </summary>
|
||||
private void OnFrame(CameraFrame frame)
|
||||
{
|
||||
@ -252,11 +211,6 @@ public class DetectionPipeline : IDisposable
|
||||
Size = (frame.Bgr.Width, frame.Bgr.Height),
|
||||
};
|
||||
|
||||
if (_yolo.IsReady)
|
||||
{
|
||||
try { result.Detections = _yolo.Detect(frame.Bgr); }
|
||||
catch (Exception ex) { ReportInferenceWarning("YOLO 推理异常:" + ex.Message); }
|
||||
}
|
||||
if (_hand.IsReady && (ShouldDetectHands?.Invoke() ?? true))
|
||||
{
|
||||
try { result.Hands = _hand.Detect(frame.Bgr); }
|
||||
@ -295,7 +249,6 @@ public class DetectionPipeline : IDisposable
|
||||
_camera.FrameArrived -= OnFrame;
|
||||
StopProcessing();
|
||||
_frameSignal.Dispose();
|
||||
_yolo.Dispose();
|
||||
_hand.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,8 +31,6 @@ public class ConditionEvaluator
|
||||
/// <summary>每只手最近访问过的区域(hand_move 的 from 证据)</summary>
|
||||
private readonly Dictionary<string, HashSet<string>> _handVisitedRegions = [];
|
||||
|
||||
/// <summary>每个物体最近访问过的区域(手搬运物体时,from 证据来自物体轨迹)</summary>
|
||||
private readonly Dictionary<string, HashSet<string>> _objectVisitedRegions = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>步骤进入时刻(time_elapsed 用)</summary>
|
||||
private readonly Dictionary<int, DateTime> _stepEnterTime = [];
|
||||
@ -62,7 +60,6 @@ public class ConditionEvaluator
|
||||
_stablePassCounts.Clear();
|
||||
_leaveRegionVisited.Clear();
|
||||
_handVisitedRegions.Clear();
|
||||
_objectVisitedRegions.Clear();
|
||||
_stepEnterTime.Clear();
|
||||
}
|
||||
|
||||
@ -90,7 +87,6 @@ public class ConditionEvaluator
|
||||
/// </summary>
|
||||
private ConditionResult EvaluateCondition(StepDef step, StepCondition condition, FrameResult frame)
|
||||
{
|
||||
var conf = condition.MinConfidence > 0 ? condition.MinConfidence : _settings.ConfidenceThreshold;
|
||||
var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
|
||||
|
||||
switch (condition.Method.ToLowerInvariant())
|
||||
@ -108,30 +104,6 @@ public class ConditionEvaluator
|
||||
: new ConditionResult { IsMet = false, Message = $"持续 {elapsed / 1000:F1}s,还差 {(need - elapsed) / 1000:F1}s" };
|
||||
}
|
||||
|
||||
case ConditionMethod.ObjectPresent:
|
||||
{
|
||||
var hit = FindDetection(frame, condition.TargetObject, conf);
|
||||
return hit is null
|
||||
? No($"未检出 {condition.TargetObject}")
|
||||
: Yes($"检出 {condition.TargetObject} {hit.Confidence:F2}");
|
||||
}
|
||||
|
||||
case ConditionMethod.ObjectInZone:
|
||||
{
|
||||
var region = Region(condition.Region);
|
||||
if (region is null) return No($"区域 {condition.Region} 不存在");
|
||||
|
||||
var hit = FindDetection(frame, condition.TargetObject, conf);
|
||||
|
||||
if (hit is null) return No($"未检出 {condition.TargetObject}");
|
||||
|
||||
var (cx, cy) = hit.Rect.Center;
|
||||
|
||||
return region.Value.Contains(cx, cy, tolerance)
|
||||
? Yes($"{condition.TargetObject} 已进入 {condition.Region}")
|
||||
: No($"{condition.TargetObject} 未在 {condition.Region} 内");
|
||||
}
|
||||
|
||||
case ConditionMethod.HandInRegion:
|
||||
{
|
||||
var region = Region(condition.Region);
|
||||
@ -167,21 +139,6 @@ public class ConditionEvaluator
|
||||
: No($"等待手先进入 {condition.Region}");
|
||||
}
|
||||
|
||||
case ConditionMethod.HandNearObject:
|
||||
{
|
||||
var hand = PickHand(frame, condition.Hand);
|
||||
if (hand is null) return No("未检出手");
|
||||
|
||||
var hit = FindDetection(frame, condition.TargetObject, conf);
|
||||
if (hit is null) return No($"未检出 {condition.TargetObject}");
|
||||
|
||||
var handRect = new DetRect(hand.Center.Item1 - 1, hand.Center.Item2 - 1, 2, 2);
|
||||
|
||||
return handRect.Intersects(hit.Rect, tolerance)
|
||||
? Yes($"手已靠近 {condition.TargetObject}")
|
||||
: No($"手尚未靠近 {condition.TargetObject}");
|
||||
}
|
||||
|
||||
case ConditionMethod.HandMove:
|
||||
{
|
||||
var from = Region(condition.FromRegion);
|
||||
@ -272,19 +229,6 @@ public class ConditionEvaluator
|
||||
}
|
||||
}
|
||||
|
||||
// 物体访问过哪些区域
|
||||
foreach (var det in frame.Detections)
|
||||
{
|
||||
if (!_objectVisitedRegions.TryGetValue(det.Label, out var set))
|
||||
_objectVisitedRegions[det.Label] = set = [];
|
||||
|
||||
var (cx, cy) = det.Rect.Center;
|
||||
|
||||
foreach (var (name, rect) in _regions)
|
||||
{
|
||||
if (rect.Contains(cx, cy, tolerance)) set.Add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -292,13 +236,6 @@ public class ConditionEvaluator
|
||||
/// </summary>
|
||||
private bool VisitedFrom(StepCondition condition, Hand hand)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(condition.TargetObject)
|
||||
&& _objectVisitedRegions.TryGetValue(condition.TargetObject, out var objectVisited)
|
||||
&& objectVisited.Contains(condition.FromRegion))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return _handVisitedRegions.TryGetValue(hand.HandType.ToString(), out var handVisited)
|
||||
&& handVisited.Contains(condition.FromRegion);
|
||||
}
|
||||
@ -318,17 +255,6 @@ public class ConditionEvaluator
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按类别找检测框(取置信度最高的那个)
|
||||
/// </summary>
|
||||
private static Detection? FindDetection(FrameResult frame, string label, float minConf)
|
||||
{
|
||||
return frame.Detections
|
||||
.Where(d => d.Label.Equals(label, StringComparison.OrdinalIgnoreCase) && d.Confidence >= minConf)
|
||||
.OrderByDescending(d => d.Confidence)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
private DetRect? Region(string name)
|
||||
{
|
||||
return _regions.TryGetValue(name, out var rect) ? rect : null;
|
||||
|
||||
@ -207,10 +207,10 @@ public static class ConditionMethod
|
||||
{
|
||||
/// <summary>该判定方法是否需要手部推理。</summary>
|
||||
public static bool RequiresHandDetection(string? method) => method?.ToLowerInvariant() is
|
||||
HandInRegion or HandLeaveRegion or HandMove or HandNearObject;
|
||||
HandInRegion or HandLeaveRegion or HandMove;
|
||||
|
||||
public static bool SupportsAiTrigger(string? method) => method?.ToLowerInvariant() is
|
||||
HandInRegion or HandLeaveRegion or HandMove;
|
||||
HandInRegion or HandLeaveRegion or HandMove or TimeElapsed;
|
||||
|
||||
/// <summary>目标出现在画面(1 次)</summary>
|
||||
public const string ObjectPresent = "object_present";
|
||||
|
||||
@ -81,14 +81,12 @@ public static partial class SopConfigLoader
|
||||
/// </summary>
|
||||
public static void Validate(SopConfig config)
|
||||
{
|
||||
config.Sop.Model = null; // 旧配方模型字段不再参与运行。
|
||||
var supported = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
ConditionMethod.ObjectPresent,
|
||||
ConditionMethod.ObjectInZone,
|
||||
ConditionMethod.HandInRegion,
|
||||
ConditionMethod.HandLeaveRegion,
|
||||
ConditionMethod.HandMove,
|
||||
ConditionMethod.HandNearObject,
|
||||
ConditionMethod.TimeElapsed,
|
||||
};
|
||||
|
||||
@ -122,7 +120,7 @@ public static partial class SopConfigLoader
|
||||
|| ai.RetryDelayMs < 0 || ai.TimeoutSeconds <= 0)
|
||||
config.Warnings.Add($"步骤 {step.Id} 的 AI 判据、置信度、重试间隔或超时配置无效");
|
||||
if (step.MustKeep.Count > 0 || step.RequiredObjects.Count > 0)
|
||||
config.Warnings.Add($"步骤 {step.Id} 使用 AI 确认时,请将物料要求写入 AI 完成判据,物体规则仍依赖 YOLO");
|
||||
config.Warnings.Add($"步骤 {step.Id} 使用 AI 确认时,请将物料要求写入 AI 完成判据,物体规则已移除");
|
||||
}
|
||||
var condition = step.Detection;
|
||||
if (condition is null)
|
||||
@ -134,7 +132,7 @@ public static partial class SopConfigLoader
|
||||
if (!supported.Contains(condition.Method))
|
||||
{
|
||||
config.Warnings.Add(
|
||||
$"步骤 {step.Id} 的方法 '{condition.Method}' 本骨架未实现(支持:{string.Join(", ", supported)}),该条件视为不满足");
|
||||
$"步骤 {step.Id} 的方法 '{condition.Method}' 已移除或不支持(请改用:{string.Join(", ", supported)}),该条件视为不满足");
|
||||
}
|
||||
|
||||
// 区域引用检查(区域没标定 → 现场就是不推进)
|
||||
@ -146,9 +144,6 @@ public static partial class SopConfigLoader
|
||||
config.Warnings.Add($"步骤 {step.Id} 引用了未定义的区域 '{name}'");
|
||||
}
|
||||
|
||||
if (NeedsModel(condition.Method) && string.IsNullOrWhiteSpace(config.Sop.Model?.Path))
|
||||
config.Warnings.Add($"步骤 {step.Id} 的方法 '{condition.Method}' 需要模型,配方模型尚未就绪,请先训练或重新导出");
|
||||
|
||||
foreach (var rule in step.ViolationRules)
|
||||
{
|
||||
if (rule.Type.Equals(ViolationType.Timeout, StringComparison.OrdinalIgnoreCase)
|
||||
@ -159,24 +154,5 @@ public static partial class SopConfigLoader
|
||||
}
|
||||
}
|
||||
|
||||
// 没有模型时,靠模型的条件全部无法判定
|
||||
if (string.IsNullOrWhiteSpace(config.Sop.Model?.Path))
|
||||
{
|
||||
var needsModel = config.Sop.Steps.Any(s => s.Detection is not null && NeedsModel(s.Detection.Method));
|
||||
if (needsModel)
|
||||
config.Warnings.Add("配方需要检测模型但尚未配置模型路径 —— 只有手部与计时类条件能工作");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该方法是否依赖 YOLO 模型。手部类(hand_in_region / hand_move)
|
||||
/// 与计时只用 MediaPipe,不在此列;hand_near_object 要比对物体,算依赖。
|
||||
/// </summary>
|
||||
private static bool NeedsModel(string method) => method.ToLowerInvariant() switch
|
||||
{
|
||||
ConditionMethod.ObjectPresent => true,
|
||||
ConditionMethod.ObjectInZone => true,
|
||||
ConditionMethod.HandNearObject => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
@ -227,8 +227,7 @@ public class SopEngine
|
||||
var result = EvaluateAiStep(step, frame, captureJpeg, captureDecisionImage, out evidence);
|
||||
|
||||
// 2. 违规:超时 / 必留物被拿走
|
||||
var violation = _violations.CheckTimeout(step, _stepEnteredAt)
|
||||
?? _violations.CheckMustKeep(step, frame);
|
||||
var violation = _violations.CheckTimeout(step, _stepEnteredAt);
|
||||
|
||||
if (violation is not null)
|
||||
{
|
||||
@ -256,6 +255,7 @@ public class SopEngine
|
||||
|
||||
// 3. 推进
|
||||
_index++;
|
||||
InvalidateDecision(); // 重试间隔和跟手位置只属于刚完成的步骤。
|
||||
|
||||
if (_index >= _ordered.Count)
|
||||
{
|
||||
|
||||
@ -87,7 +87,7 @@ internal static class Smoke
|
||||
navigation.SelectedIndex=1;await Task.Delay(100);
|
||||
var settings=window.GetVisualDescendants().OfType<SopHelper.VVMs.RuntimeSettings.RuntimeSettings>().Single();
|
||||
Check(ReferenceEquals(settings.DataContext,sop),"Settings and operator page share runtime state");
|
||||
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settings.GetVisualDescendants().OfType<Slider>().Count()==2,"Camera, recipe, threshold and stride editors are on settings page");
|
||||
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settings.GetVisualDescendants().OfType<Slider>().Count()==1,"Camera, recipe and stride editors are on settings page");
|
||||
await CheckRecipeSelection(window,navigation,sop);
|
||||
if(_recipeSelectionOnly){_exit=0;return;}
|
||||
// 后续断言针对 demo 的四步三域,不能依赖新增模板后的文件排序。
|
||||
@ -99,7 +99,7 @@ internal static class Smoke
|
||||
Check(sop.ActiveRecipe==applied,"Unapplied recipe selection does not change current recipe");
|
||||
navigation.SelectedIndex=0;await Task.Delay(80);
|
||||
Check(window.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Name=="InferenceBackend"&&t.Text==sop.InferenceBackendText)
|
||||
&&sop.InferenceBackendText.Contains("手部:")&&sop.InferenceBackendText.Contains("目标:"),
|
||||
&&sop.InferenceBackendText.Contains("手部:")&&sop.InferenceBackendText.Contains("步骤确认:"),
|
||||
"Operator page displays the actual inference backends, including CPU fallback");
|
||||
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text=="pending.yaml"),"Operator page updates to the selected recipe without applying or starting");
|
||||
sop.SelectedRecipe=selected;await Task.Delay(80);
|
||||
@ -143,144 +143,6 @@ internal static class Smoke
|
||||
var titlebarModal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();titlebarModal.Close();
|
||||
for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20);
|
||||
Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog");
|
||||
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
||||
var trainingDialog=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
||||
var trainingEditorVm=(RecipeEditorViewModel)trainingDialog.DataContext!;
|
||||
var outerTabs=trainingDialog.GetVisualDescendants().OfType<TabControl>().First();outerTabs.SelectedIndex=6;await Task.Delay(100);
|
||||
var trainingView=trainingDialog.GetVisualDescendants().OfType<TrainingPage>().Single();
|
||||
var trainer=trainingView.Model;
|
||||
Save(trainingDialog,"training");
|
||||
Check(ReferenceEquals(trainingView,trainingEditorVm.TrainingView)&&trainer.RecipeName==Path.GetFileNameWithoutExtension(sop.SelectedRecipe),"Training is embedded in the current recipe editor");
|
||||
Check(!trainingView.GetVisualDescendants().OfType<ComboBox>().Any(c=>ReferenceEquals(c.ItemsSource,trainer.Recipes)),"Embedded training has no recipe selector");
|
||||
var saveParameters=trainingView.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="保存参数");
|
||||
Check(ReferenceEquals(saveParameters.Command,trainer.SaveParametersCommand)&&trainer.Project is null&&saveParameters.Command!.CanExecute(null),"Save parameters is available without an annotation project");
|
||||
trainer.ExtractStride=3;trainer.MaxFrames=420;trainer.ExportEvery=2;trainer.ImageSize=960;trainer.Epochs=12;trainer.Batch=2;
|
||||
saveParameters.Command!.Execute(null);
|
||||
var restoredTrainer=new SopHelper.Training.MainViewModel(new WorkerClient());
|
||||
restoredTrainer.RecipeName=trainer.RecipeName;
|
||||
Check(restoredTrainer.ExtractStride==3&&restoredTrainer.MaxFrames==420&&restoredTrainer.ExportEvery==2&&restoredTrainer.ImageSize==960&&restoredTrainer.Epochs==12&&restoredTrainer.Batch==2,"Explicit save restores annotation and training parameters in a new view model");
|
||||
Check(trainer.Status=="参数已保存,下次打开时自动恢复"&&!trainer.IsBusy,"Saving confirms success without starting a worker task");
|
||||
await CheckTrainingImport(lifetime,trainingDialog,trainingView,trainer);
|
||||
var savedRecipe=trainer.RecipeName;
|
||||
restoredTrainer.RecipeName=savedRecipe;
|
||||
Check(restoredTrainer.ImageSize==960,"Reopening the same recipe restores its saved training parameters");
|
||||
restoredTrainer.RecipeName="另一配方";
|
||||
Check(restoredTrainer.ImageSize==640&&restoredTrainer.ExtractStride==1,"New recipes have independent default parameters");
|
||||
restoredTrainer.ImageSize=320;restoredTrainer.SaveParametersCommand.Execute();restoredTrainer.RecipeName=savedRecipe;
|
||||
Check(restoredTrainer.ImageSize==960&&restoredTrainer.ExtractStride==3,"Switching recipes restores each recipe's own parameters");
|
||||
var recipeId="onnx-smoke-"+Guid.NewGuid().ToString("N");
|
||||
var storage=new RecipeWorkspace(trainer.Root);
|
||||
var createEditor=new RecipeEditorViewModel();
|
||||
createEditor.OnDialogOpened(new DialogParameters{{"directory",storage.RecipesDirectory},{"new",true},{"config",new SopHelper.Engine.Sop.SopConfig()}});
|
||||
foreach(var invalid in new[]{"非法/配方","非法:配方","CON","配方.","配方 ",""})
|
||||
{
|
||||
createEditor.Recipe.Name=invalid;
|
||||
Check(createEditor.NameValidationMessage.Length>0&&!createEditor.SaveCommand.CanExecute(),"Invalid recipe name disables save and displays the reason: "+invalid);
|
||||
createEditor.SaveCommand.Execute();
|
||||
}
|
||||
createEditor.Recipe.Name="新建配方.v1";
|
||||
Check(createEditor.SaveCommand.CanExecute()&&createEditor.NameValidationMessage.Length==0,"A valid name immediately re-enables save");
|
||||
createEditor.SaveCommand.Execute();
|
||||
Check(File.Exists(storage.ConfigPath("新建配方.v1"))&&SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("新建配方.v1")).Sop.Name=="新建配方.v1","Recipe name, directory and filename match exactly, including dots");
|
||||
createEditor.OnDialogClosed();
|
||||
var recipeCamera=new CameraViewModel(new FakeCamera(),trainer.Root,savedRecipe);
|
||||
recipeCamera.SaveDirectory=Path.GetTempPath();
|
||||
Check(recipeCamera.SaveDirectory==Path.Combine(storage.DirectoryFor(savedRecipe),"recordings")&&!recipeCamera.BrowseCommand.CanExecute(),"Recipe recordings stay in the selected recipe directory");
|
||||
await recipeCamera.ShutdownAsync();
|
||||
var recipeFile=storage.ConfigPath(recipeId);
|
||||
var recipeWorkspace=storage.DirectoryFor(recipeId);
|
||||
Directory.CreateDirectory(recipeWorkspace);
|
||||
var modelFile=Path.Combine(recipeWorkspace,recipeId+".onnx");
|
||||
var externalModel=Path.Combine(trainer.Root,"external-model.onnx");
|
||||
var manifestFile=Path.Combine(recipeWorkspace,"latest-model.json");
|
||||
try
|
||||
{
|
||||
File.Copy(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"),recipeFile);
|
||||
// The model loader may reject this stub; this checks recipe routing and metadata independently.
|
||||
File.WriteAllBytes(modelFile,[]);
|
||||
var manualConfig=SopHelper.Engine.Sop.SopConfigLoader.Load(recipeFile);
|
||||
manualConfig.Sop.Model=new SopHelper.Engine.Sop.ModelDef{Path=modelFile,Classes=["manual"],InputSize=640};
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(manualConfig,recipeFile);
|
||||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"A manually configured model cannot replace a missing recipe training publication");
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
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 does not fall back to the configured model");
|
||||
File.WriteAllText(manifestFile,"{broken-json");
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Broken training publication does not fall back to a manually configured model");
|
||||
File.WriteAllBytes(externalModel,[]);
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=externalModel,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Model files outside the current recipe are rejected");
|
||||
File.Delete(modelFile);
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Missing published model cannot fall back to other models");
|
||||
}
|
||||
finally
|
||||
{
|
||||
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||||
File.Delete(recipeFile);File.Delete(modelFile);File.Delete(manifestFile);File.Delete(externalModel);Directory.Delete(recipeWorkspace);
|
||||
}
|
||||
var trainingTabs=trainingView.GetVisualDescendants().OfType<TabControl>().Single();
|
||||
trainingTabs.SelectedIndex=1;await Task.Delay(80);
|
||||
Check(trainingView.GetVisualDescendants().OfType<Button>().Any(b=>b.Content?.ToString()=="训练并更新配方模型"),"Recipe model update action is visible on the training tab");
|
||||
Save(trainingDialog,"training-recipe-model");
|
||||
trainingTabs.SelectedIndex=0;
|
||||
var temporary=Path.Combine(Path.GetTempPath(),"sophelper-avalonia-project-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(temporary);
|
||||
using(var trainingFrame=new Mat(480,640,MatType.CV_8UC3,new Scalar(30,60,90)))Cv2.ImWrite(Path.Combine(temporary,"frame.png"),trainingFrame);
|
||||
var project=new TrainingProject { FilePath=Path.Combine(temporary,"project.json"),Name="测试零件",Width=640,Height=480,
|
||||
Frames=[new FrameAnnotation {Index=0,Image="frame.png",Status="unlabeled"}] };
|
||||
project.Save();trainer.Load(project.FilePath);trainer.DrawBox([10,20,100,200]);trainer.ApproveCommand.Execute();
|
||||
Check(trainingView.GetVisualDescendants().OfType<AnnotationCanvas>().Single().TargetName==trainer.Label,"Annotation canvas uses the imported project's locked target name");
|
||||
Check(TrainingProject.Load(trainer.Project!.FilePath).Frames[0].Status=="reviewed"&&RecipeWorkspace.IsWithin(trainer.Project.FilePath,storage.DirectoryFor(savedRecipe)),"Opened annotation projects are copied into their recipe and review saves there");
|
||||
outerTabs.SelectedIndex=0;outerTabs.SelectedIndex=6;await Task.Delay(80);
|
||||
Check(ReferenceEquals(trainer,trainingEditorVm.TrainingView!.Model)&&trainer.CurrentBox is { Length:4 },"Switching editor tabs preserves annotation state");
|
||||
try{trainer.RecipeName="另一配方";throw new Exception("Locked recipe accepted a switch");}catch(InvalidOperationException){}
|
||||
Check(trainer.RecipeName==savedRecipe&&trainer.Project is not null,"Embedded training cannot switch away from the edited recipe");
|
||||
var foreign=new TrainingProject{FilePath=Path.Combine(temporary,"foreign.json"),Name="其他零件",RecipeName="另一配方",Width=100,Height=100,Frames=[new FrameAnnotation{Index=0,Image="frame.png"}]};foreign.Save();
|
||||
try{trainer.Load(foreign.FilePath);throw new Exception("Foreign recipe project was accepted");}catch(InvalidOperationException){}
|
||||
Check(trainer.CurrentBox is {Length:4},"Opening another recipe's project is rejected without altering current annotations");
|
||||
await CheckTrainingLayout(trainingDialog,trainingView,trainer);
|
||||
Save(trainingDialog,"training-project");
|
||||
trainer.DoctorCommand.Execute();
|
||||
for(var i=0;i<300&&trainer.IsBusy;i++)await Task.Delay(100);
|
||||
Check(!trainer.IsBusy&&trainer.Progress==100&&trainer.Logs.Contains("Python ")&&trainer.Logs.Contains("PyTorch"),"Training worker command completes using the repository Python runtime");
|
||||
trainer.DoctorCommand.Execute();Check(trainer.IsBusy,"A training worker operation is running before editor close");
|
||||
trainingEditorVm.CloseCommand.Execute();
|
||||
for(var i=0;i<200&&lifetime.Windows.Contains(trainingDialog);i++)await Task.Delay(20);
|
||||
Check(!lifetime.Windows.Contains(trainingDialog)&&!trainer.IsBusy&&File.Exists(trainer.Project!.FilePath),"Closing the editor cancels its worker and preserves saved annotations");
|
||||
var editorVm=new RecipeEditorViewModel();
|
||||
editorVm.OnDialogOpened(new DialogParameters { {"directory",storage.RecipesDirectory},
|
||||
{"config",SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("demo"))},
|
||||
{"path",storage.ConfigPath("demo")}, {"new",false} });
|
||||
var editor=new RecipeEditor { DataContext=editorVm };
|
||||
var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
|
||||
var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);
|
||||
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();
|
||||
Check(tabs.ItemCount==7,"Recipe tabs include parts, SOP recording and annotation/training");
|
||||
for(var i=0;i<tabs.ItemCount;i++){tabs.SelectedIndex=i;await Task.Delay(80);Save(dialog,"recipe-"+i);}
|
||||
Check(editorVm.Recipe.Steps.Count>0,"Original recipe ViewModel loads steps");
|
||||
Check(editorVm.Recipe.Steps[0].Detection?.Method=="hand_in_region","Recipe bindings preserve selected condition method");
|
||||
Check(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())==recipeBefore,"Opening all recipe tabs does not alter any recipe fields");
|
||||
var closingTrainer=editorVm.TrainingView!.Model;
|
||||
closingTrainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);
|
||||
closingTrainer.ImportCommand.Execute();await Task.Delay(40);
|
||||
Check(!closingTrainer.IsImporting,"Cancelling video selection finishes import without a part picker");
|
||||
dialog.Close();
|
||||
for(var i=0;i<100&&dialog.IsVisible;i++)await Task.Delay(20);
|
||||
Check(!dialog.IsVisible&&!closingTrainer.IsImporting,"Closing the editor after cancelled import releases resources");
|
||||
editorVm.OnDialogClosed();
|
||||
var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
|
||||
recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
|
||||
var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
|
||||
@ -329,7 +191,7 @@ internal static class Smoke
|
||||
drawing.Close();
|
||||
}
|
||||
Check(userCameraBefore is null ? !File.Exists(userCameraPath) : File.Exists(userCameraPath)&&userCameraBefore.SequenceEqual(File.ReadAllBytes(userCameraPath)),"Smoke tests leave the real user's camera preference unchanged");
|
||||
File.WriteAllText(Path.Combine(Output,"result.json"),JsonSerializer.Serialize(new {passed=true,pages=navigation.Pages.Select(p=>p.DisplayName),recipeTabs=tabs.ItemCount}));
|
||||
File.WriteAllText(Path.Combine(Output,"result.json"),JsonSerializer.Serialize(new {passed=true,pages=navigation.Pages.Select(p=>p.DisplayName)}));
|
||||
_exit=0;
|
||||
}
|
||||
catch(Exception ex){Console.Error.WriteLine(ex);}
|
||||
@ -787,6 +649,11 @@ internal static class Smoke
|
||||
try
|
||||
{
|
||||
Check(!editor.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成"),"AI confirmation no longer has an opt-out checkbox");
|
||||
var headers=editor.GetVisualDescendants().OfType<TabItem>().Select(t=>t.Header?.ToString()).ToArray();
|
||||
Check(headers.SequenceEqual(new[]{"步骤","区域","全局设置","SOP流程视频"}),"Recipe editor removes parts, detection-model and annotation/training settings");
|
||||
Check(editor.FindControl<ComboBox>("TargetPartPicker") is null,"Step editor removes YOLO target-class picker");
|
||||
Check(editorVm.Recipe.Methods.All(m=>!m.StartsWith("object_")&&m!="hand_near_object"),"Only hand and timer trigger methods are offered");
|
||||
Check(editor.FindControl<TextBox>("CameraExposureInput") is not null,"Camera exposure remains available in global settings");
|
||||
var picker=editor.FindControl<ComboBox>("AiImageRegionPicker")!;
|
||||
var modePicker=editor.FindControl<ComboBox>("AiImageModePicker")!;
|
||||
Check(modePicker.SelectedItem?.ToString()=="fixed_region","Legacy crop settings select fixed-region mode");
|
||||
@ -809,6 +676,14 @@ internal static class Smoke
|
||||
Save(dialog,"hand-ai-confirmation-settings");
|
||||
}
|
||||
finally{await editorVm.ShutdownAsync();dialog.Close();}
|
||||
var settingsView=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(sop);
|
||||
var settingsWindow=new Window{Content=settingsView,Width=900,Height=720};settingsWindow.Show();await Task.Delay(40);
|
||||
try
|
||||
{
|
||||
Check(settingsView.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settingsView.GetVisualDescendants().OfType<Slider>().Count()==1,"Runtime settings retain camera, recipe and stride while removing YOLO threshold");
|
||||
Save(settingsWindow,"runtime-settings-no-yolo");
|
||||
}
|
||||
finally{settingsWindow.Close();}
|
||||
sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
|
||||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||||
Check(engine.Config.Sop.Model is null,"Pure hand/AI recipe skips YOLO loading");
|
||||
|
||||
@ -6,36 +6,43 @@ 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();
|
||||
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.ObjectPresent, TargetObject="part", StableFrames=1 } },
|
||||
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.ObjectPresent, TargetObject="part", 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 }] };
|
||||
engine.ProcessFrame(partFrame);
|
||||
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");
|
||||
engine.ProcessFrame(new FrameResult { Hands=[new Hand { Rect=new DetRect(10,10,20,20) }] });
|
||||
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");
|
||||
engine.ProcessFrame(partFrame);
|
||||
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.HandNearObject})
|
||||
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>();
|
||||
@ -84,56 +91,6 @@ 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");
|
||||
var expectedDetections = frame.Detections.Select(d => (d.Label,d.Rect,d.Confidence)).ToArray();
|
||||
var detectHands = false;
|
||||
pipeline.ShouldDetectHands = () => detectHands;
|
||||
foreach (var enabled in new[]{false,true,false})
|
||||
{
|
||||
detectHands = enabled;
|
||||
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
await pipeline.StartAsync();camera.Emit(200,image);
|
||||
frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
|
||||
if((frame.Hands.Count>0)!=enabled)throw new Exception("Hand inference did not follow the current requirement");
|
||||
if(!frame.Detections.Select(d => (d.Label,d.Rect,d.Confidence)).SequenceEqual(expectedDetections))
|
||||
throw new Exception("Disabling hands affected object detection");
|
||||
}
|
||||
pipeline.ShouldDetectHands = null;
|
||||
Console.WriteLine("PASS: Real hand detection stops and resumes without stale hands while YOLO continues");
|
||||
// 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;
|
||||
@ -153,3 +110,8 @@ internal sealed class TestCamera : ICameraService
|
||||
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确认"));
|
||||
}
|
||||
|
||||
@ -81,7 +81,7 @@ internal static class PreviewSmoke
|
||||
Console.WriteLine(JsonSerializer.Serialize(new { renderer, camera = Camera is SyntheticCamera ? "synthetic" : "hikvision",
|
||||
width = sop.FrameWidth, height = sop.FrameHeight,
|
||||
previewUpdatesPerSecond = fps, acquisitionFps = (Interlocked.Read(ref _acquired) - produced) / seconds, status = sop.FpsText,
|
||||
handBackend = pipeline.HandBackend, yoloBackend = pipeline.YoloBackend, inferenceMs = pipeline.AvgInferenceMs }));
|
||||
handBackend = pipeline.HandBackend, inferenceMs = pipeline.AvgInferenceMs }));
|
||||
if (fps < (Camera is SyntheticCamera ? 28 : 1)) throw new Exception("Preview updates are below the expected rate");
|
||||
sop.StartStopCommand.Execute();
|
||||
for (var i = 0; i < 100 && sop.IsRunning; i++) await Task.Delay(50);
|
||||
|
||||
@ -3,7 +3,7 @@ using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Inference;
|
||||
|
||||
var method = typeof(YoloDetector).Assembly.GetType("SopHelper.Engine.Inference.TensorPreprocessing")!
|
||||
var method = typeof(MediaPipeHandDetector).Assembly.GetType("SopHelper.Engine.Inference.TensorPreprocessing")!
|
||||
.GetMethod("FromRgb", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
using var parent = new Mat(5, 7, MatType.CV_8UC3, new Scalar(99, 98, 97));
|
||||
using var roi = new Mat(parent, new Rect(1, 1, 3, 2));
|
||||
|
||||
@ -5,6 +5,17 @@ using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||||
Check(typeof(SopEngine).Assembly.GetType("SopHelper.Engine.Inference.YoloDetector") is null, "运行程序集必须移除 YOLO 检测器");
|
||||
var retired = SopConfigLoader.Parse("""
|
||||
sop:
|
||||
name: 旧物体规则
|
||||
model: { path: old.onnx, classes: [盒子] }
|
||||
steps:
|
||||
- id: 1
|
||||
description: 把盒子放好
|
||||
detection: { method: object_present, target_object: 盒子 }
|
||||
""");
|
||||
Check(retired.Sop.Model is null && retired.Warnings.Any(w=>w.Contains("已移除或不支持")), "旧模型绑定必须忽略,旧物体规则提示改用手部规则");
|
||||
var sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "hand-ai.yaml"));
|
||||
Check(sample.Warnings.Count == 0 && sample.Sop.Model is null && sample.Sop.Steps.All(s => s.AiConfirmation is not null), "示例配方必须有效且不依赖 YOLO");
|
||||
var d3Sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "d3-workflow.yaml"));
|
||||
|
||||
Loading…
Reference in New Issue
Block a user