diff --git a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs index a85b477..dd8b275 100644 --- a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs @@ -13,6 +13,13 @@ public sealed partial class CameraViewModel private string _flowTestStatus = "", _flowTestDetails = ""; private BitmapSource? _flowTestDecisionImage; private string _flowTestDecisionLabel = ""; + private IReadOnlyDictionary? _flowTestRegions; + public IReadOnlyDictionary? FlowTestRegions + { + get => _flowTestRegions; + private set { SetProperty(ref _flowTestRegions, value); RaisePropertyChanged(nameof(ShowFlowTestOverlay)); } + } + public bool ShowFlowTestOverlay => FlowTestRegions is not null && Playback.IsLoaded; public BitmapSource? FlowTestDecisionImage { get => _flowTestDecisionImage; @@ -47,6 +54,7 @@ public sealed partial class CameraViewModel { var test = new SopVideoFlowTest(FlowTestConfigProvider!()); _flowTest = test; + FlowTestRegions = test.Regions; IsTestingFlow = true; if (IsPreviewing) { @@ -71,7 +79,7 @@ public sealed partial class CameraViewModel test.Start(); FlowTestDetails = test.Details; FlowTestStatus = "正在播放标准视频并检测流程(使用当前编辑配置)"; - Playback.FrameProcessor = test.ProcessFrame; + Playback.FrameAnalyzer = test.AnalyzeFrame; await Playback.PlayAsync(StandardVideoPath); if (IsTestingFlow) Status = "正在测试流程;点击“停止播放”可停止测试"; } @@ -97,6 +105,7 @@ public sealed partial class CameraViewModel private void EndFlowTest(string reason) { Playback.FrameProcessor = null; + Playback.FrameAnalyzer = null; if (_flowTest is { } test) { FlowTestStatus = test.Finish(reason); diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index 6984a8a..7f9f4d0 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -103,7 +103,8 @@ public sealed partial class CameraViewModel : BindableBase if (e.PropertyName is nameof(Playback.Frame) or nameof(Playback.IsLoaded)) RaisePropertyChanged(nameof(DisplayImage)); if (e.PropertyName is nameof(Playback.IsPlaying) or nameof(Playback.IsLoaded) or nameof(Playback.IsAtEnd)) { RaisePropertyChanged(nameof(PlayVideoButtonText)); UpdateCommands(); } - if (e.PropertyName == nameof(Playback.IsLoaded)) RaisePropertyChanged(nameof(CanSeekVideo)); + if (e.PropertyName == nameof(Playback.IsLoaded)) + { RaisePropertyChanged(nameof(CanSeekVideo)); RaisePropertyChanged(nameof(ShowFlowTestOverlay)); } if (e.PropertyName == nameof(Playback.IsAtEnd) && Playback.IsAtEnd) { if (IsTestingFlow) _ = CompleteFlowTestAsync(); @@ -185,6 +186,7 @@ public sealed partial class CameraViewModel : BindableBase } private async Task ToggleVideoPlaybackAsync() { + FlowTestRegions = null; if (IsRecording) throw new InvalidOperationException("请先停止录像并保存,再播放视频"); if (Playback.IsPlaying) { Playback.Pause(); Status = "视频播放已暂停"; return; } if (IsPreviewing) diff --git a/src/SopHelper.Avalonia/Training/FlowTestRegionOverlay.cs b/src/SopHelper.Avalonia/Training/FlowTestRegionOverlay.cs new file mode 100644 index 0000000..6f34a06 --- /dev/null +++ b/src/SopHelper.Avalonia/Training/FlowTestRegionOverlay.cs @@ -0,0 +1,40 @@ +using System.Globalization; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.VisualTree; +using SopHelper.Engine.Sop; + +namespace SopHelper.Training; + +/// 放在原始像素尺寸的画布中,与视频和手部骨架一起等比缩放。 +public sealed class FlowTestRegionOverlay : Control +{ + public static readonly StyledProperty?> RegionsProperty = + AvaloniaProperty.Register?>(nameof(Regions)); + public IReadOnlyDictionary? Regions { get => GetValue(RegionsProperty); set => SetValue(RegionsProperty, value); } + static FlowTestRegionOverlay() => AffectsRender(RegionsProperty); + + public override void Render(DrawingContext drawing) + { + base.Render(drawing); + if (Regions is null || Bounds.Width <= 0 || Bounds.Height <= 0) return; + using var clip = drawing.PushClip(new Rect(Bounds.Size)); + var transform = this.TransformToVisual(TopLevel.GetTopLevel(this) ?? (Visual)this); + var scale = transform is { } matrix ? Math.Sqrt(matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12) : 1; + var unit = scale > 0 ? 1 / scale : 1; + foreach (var (key, region) in Regions) + { + if (region.X2 <= region.X1 || region.Y2 <= region.Y1) continue; + var rect = new Rect(region.X1, region.Y1, region.X2 - region.X1, region.Y2 - region.Y1).Intersect(new Rect(Bounds.Size)); + if (rect.Width <= 0 || rect.Height <= 0) continue; + var brush = new SolidColorBrush(Color.TryParse(region.Color, out var color) ? color : Colors.Orange); + drawing.DrawRectangle(null, new Pen(brush, 2 * unit), rect); + var label = new FormattedText(string.IsNullOrWhiteSpace(region.Name) ? key : region.Name, + CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei, Noto Sans CJK SC"), 12 * unit, brush); + var origin = new Point(rect.X, Math.Max(0, rect.Y - label.Height)); + drawing.DrawRectangle(Brushes.Black, null, new Rect(origin, new Size(label.Width, label.Height))); + drawing.DrawText(label, origin); + } + } +} diff --git a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs index 7fef933..f5937e5 100644 --- a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs +++ b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs @@ -3,6 +3,7 @@ using Avalonia.Threading; using OpenCvSharp; using Prism.Mvvm; using SopHelper.Presentation.Imaging; +using SopHelper.Engine.Common; namespace SopHelper.Training; @@ -40,6 +41,10 @@ public sealed class RecordedVideoPlayback : BindableBase public event Action? Failed; /// 在解码线程处理即将显示的原始帧;Mat 仅在回调期间有效。 public Action? FrameProcessor { get; set; } + public Func? FrameAnalyzer { get; set; } + private FrameResult? _analysis; + /// 与当前显示画面一起发布的检测结果,不能跨帧沿用。 + public FrameResult? Analysis { get => _analysis; private set => SetProperty(ref _analysis, value); } public RecordedVideoPlayback() { @@ -99,13 +104,13 @@ public sealed class RecordedVideoPlayback : BindableBase _readTask = null; _reading = false; var capture = _capture; _capture = null; if (capture is not null) await Task.Run(capture.Dispose); - Frame = null; IsLoaded = false; IsAtEnd = false; + Frame = null; Analysis = null; IsLoaded = false; IsAtEnd = false; _position = 0; _duration = 0; NotifyTime(); } public Task SeekAsync(double percent) { - if (!IsLoaded || FrameProcessor is not null || !double.IsFinite(percent)) return Task.CompletedTask; + if (!IsLoaded || FrameProcessor is not null || FrameAnalyzer is not null || !double.IsFinite(percent)) return Task.CompletedTask; _pendingSeek = Math.Clamp(percent, 0, 100); if (!_seeking) _seekTask = SeekPendingAsync(); return _seekTask; @@ -147,6 +152,7 @@ public sealed class RecordedVideoPlayback : BindableBase } _capture = opened.Capture; Frame = opened.Frame.Image; + Analysis = opened.Frame.Analysis; _position = percent == 100 ? _duration : opened.Frame.Seconds; IsAtEnd = percent == 100; if (IsAtEnd) Pause(); @@ -199,6 +205,7 @@ public sealed class RecordedVideoPlayback : BindableBase return; } Frame = decoded.Image; + Analysis = decoded.Analysis; _position = decoded.Seconds; NotifyTime(); } catch (Exception error) @@ -218,11 +225,12 @@ public sealed class RecordedVideoPlayback : BindableBase if (!capture.Read(frame) || frame.Empty()) return new(null, 0); var frameId = Math.Max(0, (long)capture.PosFrames - 1); FrameProcessor?.Invoke(frame, frameId, frameId / _fps); + var analysis = FrameAnalyzer?.Invoke(frame, frameId, frameId / _fps); var stride = checked((int)frame.Step()); var image = BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, null, frame.Data, checked(stride * frame.Height), stride); image.Freeze(); - return new(image, Math.Max(0, (capture.PosFrames - 1) / _fps)); + return new(image, Math.Max(0, (capture.PosFrames - 1) / _fps), analysis); } private void NotifyTime() @@ -231,5 +239,5 @@ public sealed class RecordedVideoPlayback : BindableBase try { RaisePropertyChanged(nameof(Progress)); RaisePropertyChanged(nameof(TimeText)); } finally { _reportingProgress = false; } } - private sealed record DecodedFrame(BitmapSource? Image, double Seconds); + private sealed record DecodedFrame(BitmapSource? Image, double Seconds, FrameResult? Analysis = null); } diff --git a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs index 6033c63..5b17806 100644 --- a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs @@ -22,6 +22,7 @@ public sealed class SopVideoFlowTest : IDisposable public event Action? Changed; public event Action? DecisionImageCaptured; public bool IsCompleted => _engine.State == EngineState.Completed; + public IReadOnlyDictionary Regions => _engine.Config.Sop.Regions; public string Details { get { lock (_gate) return string.Join(Environment.NewLine, _steps.Values.OrderBy(s => s.StepId) @@ -63,10 +64,16 @@ public sealed class SopVideoFlowTest : IDisposable public void ProcessFrame(Mat image, long frameId, double seconds) { - if (++_seen % _stride != 0 || IsCompleted) return; + _ = AnalyzeFrame(image, frameId, seconds); + } + + public FrameResult? AnalyzeFrame(Mat image, long frameId, double seconds) + { + if (++_seen % _stride != 0) return null; var result = new FrameResult { FrameId = frameId, Timestamp = DateTime.Now, Size = (image.Width, image.Height) }; - if (_engine.RequiresHandDetection) result.Hands = _hands.Detect(image); + if (_hands.IsReady) result.Hands = _hands.Detect(image); ProcessResult(result, image); + return result; } /// 使用与正式运行相同的原帧裁剪、手部门控和 AI 完成判定。 diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index 33855c7..e733726 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -1,4 +1,4 @@ - + @@ -419,9 +419,13 @@ - - - + + + + + + + diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs b/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs index 31f7ecd..65a6198 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs @@ -2,14 +2,18 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Media; using SopHelper.Engine.Common; +using System.Globalization; +using Avalonia.VisualTree; namespace SopHelper.VVMs.SopPage; public sealed class HandOverlay : Control { public static readonly StyledProperty ResultProperty=AvaloniaProperty.Register(nameof(Result)); public FrameResult? Result { get=>GetValue(ResultProperty);set=>SetValue(ResultProperty,value); } + public static readonly StyledProperty ShowBoundsProperty=AvaloniaProperty.Register(nameof(ShowBounds)); + public bool ShowBounds {get=>GetValue(ShowBoundsProperty);set=>SetValue(ShowBoundsProperty,value);} private static readonly (int From,int To)[] Bones=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(5,9),(9,10),(10,11),(11,12),(9,13),(13,14),(14,15),(15,16),(13,17),(0,17),(17,18),(18,19),(19,20)]; - static HandOverlay(){AffectsRender(ResultProperty);} + static HandOverlay(){AffectsRender(ResultProperty,ShowBoundsProperty);} public override void Render(DrawingContext drawing) { base.Render(drawing);var result=Result; @@ -17,10 +21,26 @@ public sealed class HandOverlay : Control using var clip=drawing.PushClip(new Rect(Bounds.Size)); using var scale=drawing.PushTransform(Matrix.CreateScale(Bounds.Width/result.Size.W,Bounds.Height/result.Size.H)); var unit=Math.Max(result.Size.W,result.Size.H)/700.0; + if(ShowBounds) + { + var transform=this.TransformToVisual(TopLevel.GetTopLevel(this)??(Visual)this); + var displayScale=transform is {} matrix?Math.Sqrt(matrix.M11*matrix.M11+matrix.M12*matrix.M12):1; + if(displayScale>0)unit=1/displayScale; + } foreach(var hand in result.Hands) { var brush=hand.HandType switch {HandType.Left=>Brushes.LimeGreen,HandType.Right=>Brushes.DeepSkyBlue,_=>Brushes.Gray}; var pen=new Pen(brush,unit*2); + var contact=hand.ContactRect; + if(ShowBounds && contact.W>0 && contact.H>0 && float.IsFinite(contact.X) && float.IsFinite(contact.Y) + && float.IsFinite(contact.Right) && float.IsFinite(contact.Bottom)) + { + drawing.DrawRectangle(null,pen,new Rect(contact.X,contact.Y,contact.W,contact.H)); + var name=hand.HandType switch {HandType.Left=>"左手",HandType.Right=>"右手",_=>"手(未分类)"}; + var label=new FormattedText(name,CultureInfo.CurrentCulture,FlowDirection.LeftToRight, + new Typeface("Microsoft YaHei, Noto Sans CJK SC"),12*unit,brush); + drawing.DrawText(label,new Point(Math.Max(0,contact.X),Math.Max(0,contact.Y-label.Height))); + } var points=hand.Keypoints.Where(p=>p.Index is >=0 and <=20 && p.Confidence>0 && float.IsFinite(p.X) && float.IsFinite(p.Y)).GroupBy(p=>p.Index).ToDictionary(g=>g.Key,g=>g.First()); foreach(var (from,to) in Bones) if(points.TryGetValue(from,out var a)&&points.TryGetValue(to,out var b))drawing.DrawLine(pen,new Point(a.X,a.Y),new Point(b.X,b.Y)); diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs index 1eb1abc..0a70fcb 100644 --- a/tests/VideoFlowTest.Smoke/Program.cs +++ b/tests/VideoFlowTest.Smoke/Program.cs @@ -12,13 +12,17 @@ using SopHelper.Engine.Sop; using SopHelper.Engine.Training; using SopHelper.Training; using SopHelper.VVMs.RecipeEditor; +using SopHelper.VVMs.SopPage; using Window = Avalonia.Controls.Window; internal static class Program { + private static string? _overlayPreviewPath; [STAThread] public static void Main(string[] args) { + var previewIndex = Array.IndexOf(args, "--overlay-preview"); + if (previewIndex >= 0 && previewIndex + 1 < args.Length) _overlayPreviewPath = args[previewIndex + 1]; var root = Path.Combine(Path.GetTempPath(), "video-flow-test-" + Guid.NewGuid().ToString("N")); var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"); Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root); @@ -106,6 +110,7 @@ internal static class Program CheckContinuousPlayback(model.StandardVideoPath); // Unsupported condition exercises playback and incomplete results without hardware/models/API. config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }]; + config.Sop.Regions["标定区"] = new() { X1 = 10, Y1 = 5, X2 = 50, Y2 = 40, Name = "标定区", Color = "#FF00FF" }; model.FlowTestConfigProvider = () => config; var view = new RecipeEditor { DataContext = vm }; var window = new Window { Content = view, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout(); @@ -118,15 +123,60 @@ internal static class Program Check(model.IsTestingFlow && model.Playback.IsPlaying && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Test button plays and displays the standard video without a camera"); Check(!model.TestFlowCommand.CanExecute() && !model.PlayVideoCommand.CanExecute() && !model.PreviewCommand.CanExecute() && !model.CanSeekVideo, "Test run prevents restart, playback switching, camera switching, and seeking"); Check(!view.FindControl("VideoSeekSlider")!.IsEnabled, "Actual seek slider is disabled during flow testing"); + var regionsOverlay = view.FindControl("FlowTestRegionsOverlay")!; + var handsOverlay = view.FindControl("FlowTestHandsOverlay")!; + Check(regionsOverlay.IsEffectivelyVisible && regionsOverlay.Regions!.ContainsKey("标定区") + && handsOverlay.IsEffectivelyVisible && handsOverlay.ShowBounds && !handsOverlay.IsHitTestVisible, + "Video test displays the recipe region layer and hand skeleton/contact bounds without intercepting input"); + var analyze = model.Playback.FrameAnalyzer!; + model.Playback.FrameAnalyzer = (image, id, seconds) => + { + var result = analyze(image, id, seconds)!; + result.Hands = id % 2 == 0 ? [new Hand { HandType = HandType.Left, Rect = new(20, 10, 20, 25), + Keypoints = Enumerable.Range(0, 21).Select(i => new HandPoint { Index = i, X = 20 + i % 5 * 3, Y = 10 + i / 5 * 5, Confidence = 1 }).ToList() }] : []; + return result; + }; + Until(() => model.Playback.Analysis is { FrameId: >= 2, Hands.Count: 1 }); + Check(ReferenceEquals(handsOverlay.Result, model.Playback.Analysis) && handsOverlay.Result!.Size == (64, 48), + "Hand overlay receives the analysis published with the displayed video frame"); + if (_overlayPreviewPath is not null) + { + window.UpdateLayout(); + using var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height)); + rendered.Render(window); rendered.Save(_overlayPreviewPath); + } + void CheckAlignment() + { + window.UpdateLayout(); + var host = (Grid)regionsOverlay.Parent!; + var videoImage = host.Children.OfType().Single(); + var start = videoImage.TranslatePoint(new Avalonia.Point(), window)!.Value; + var end = videoImage.TranslatePoint(new Avalonia.Point(videoImage.Bounds.Width, videoImage.Bounds.Height), window)!.Value; + foreach (var overlay in new Control[] { regionsOverlay, handsOverlay }) + { + var overlayStart = overlay.TranslatePoint(new Avalonia.Point(), window)!.Value; + var overlayEnd = overlay.TranslatePoint(new Avalonia.Point(overlay.Bounds.Width, overlay.Bounds.Height), window)!.Value; + Check(Math.Abs(start.X - overlayStart.X) < .01 && Math.Abs(start.Y - overlayStart.Y) < .01 + && Math.Abs(end.X - overlayEnd.X) < .01 && Math.Abs(end.Y - overlayEnd.Y) < .01, + "Region and hand layers exactly follow the image bounds through uniform scaling and letterboxing"); + } + Check(Math.Abs((end.X - start.X) / (end.Y - start.Y) - 64d / 48) < .001, "Overlay host preserves the original video aspect ratio"); + } + CheckAlignment(); + window.Width = 840; window.Height = 900; CheckAlignment(); + window.Width = 1040; window.Height = 760; + Until(() => model.Playback.Analysis is { FrameId: >= 3, Hands.Count: 0 }); + Check(handsOverlay.Result!.Hands.Count == 0, "A frame with no hands clears the previous skeleton instead of retaining old detections"); Until(() => !model.IsTestingFlow); Check(model.Playback.IsAtEnd && model.FlowTestStatus.Contains("流程未完成") && model.FlowTestDetails.Contains("待配置步骤"), "Video EOF reports incomplete flow and shows the step reason"); model.TestFlowCommand.Execute(); Until(() => !model.IsBusy); Check(model.Playback.Progress < 50, "Each test restarts the video from its beginning"); model.StopVideoCommand.Execute(); Until(() => !model.IsBusy); Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.FlowTestStatus.Contains("测试已停止"), "Stop playback also stops detection and preserves the test summary"); + Check(model.Playback.Analysis is null && !model.ShowFlowTestOverlay, "Stopping playback clears the hand analysis and hides test overlays"); model.TestFlowCommand.Execute(); Until(() => !model.IsBusy); Pump(vm.ShutdownAsync()); - Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.Playback.FrameProcessor is null, "Closing the editor releases playback and flow detection"); + Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.Playback.FrameProcessor is null && model.Playback.FrameAnalyzer is null, "Closing the editor releases playback and flow detection"); using (var exclusive = new FileStream(model.StandardVideoPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) Check(exclusive.Length > 0, "Closing flow test unlocks the video file"); window.Close(); vm.OnDialogClosed();