diff --git a/README.md b/README.md index a8da659..602236d 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,18 @@ dotnet build SopHelper.slnx 没有模型也能起:缺哪个就在日志里报哪条警告,只有手部类和计时类条件能工作。 +运行时,检测到的手会直接标在视频画面上:21 个关键点与骨架连线,不显示手部外框或文字标签。 +标记与 ROI 共用原图坐标,随预览一起缩放;未检测到手或停止采集时清除。 +需要 `models/` 中的 palm 与 landmark 两份模型,缺失时日志会提示。 +默认支持同帧显示两只手。针对 palm 导出中内置的单手 NMS 限制,加载时仅在内存中 +适配候选输出数量,原始模型文件不变;相邻手部去重使用原始手掌框。 + +双手回归检查(提供一段同时包含左右手的视频,从项目根目录运行): + +```bash +dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4 +``` + ### 海康相机取视频 参考 `plcsharp` 的 `MvCameraControl` 接法,支持海康机器人 GigE / USB 工业相机。 diff --git a/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs b/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs new file mode 100644 index 0000000..8473042 --- /dev/null +++ b/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs @@ -0,0 +1,61 @@ +using System.Windows; +using System.Windows.Media; +using SopHelper.Engine.Common; + +namespace SopHelper.VVMs.SopPage; + +/// 按原图坐标绘制手部结果,与视频、ROI 一起缩放,不修改用于检测的图像。 +public sealed class HandOverlay : FrameworkElement +{ + 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), + ]; + + public static readonly DependencyProperty ResultProperty = DependencyProperty.Register( + nameof(Result), typeof(FrameResult), typeof(HandOverlay), + new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public FrameResult? Result + { + get => (FrameResult?)GetValue(ResultProperty); + set => SetValue(ResultProperty, value); + } + + protected override void OnRender(DrawingContext drawing) + { + base.OnRender(drawing); + var result = Result; + if (result is null || result.Size.W <= 0 || result.Size.H <= 0 || + ActualWidth <= 0 || ActualHeight <= 0) return; + + drawing.PushClip(new RectangleGeometry(new Rect(RenderSize))); + drawing.PushTransform(new ScaleTransform(ActualWidth / result.Size.W, ActualHeight / result.Size.H)); + // 按图像尺寸设置线宽,海康高分辨率图缩小预览后仍可看清。 + var unit = Math.Max(result.Size.W, result.Size.H) / 700.0; + foreach (var hand in result.Hands) + { + var brush = hand.HandType == HandType.Left ? Brushes.LimeGreen : Brushes.DeepSkyBlue; + var pen = new Pen(brush, unit * 2); + 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 start) && points.TryGetValue(to, out var end)) + drawing.DrawLine(pen, new Point(start.X, start.Y), new Point(end.X, end.Y)); + + foreach (var point in points.Values) + drawing.DrawEllipse(Brushes.Yellow, null, new Point(point.X, point.Y), unit * 3, unit * 3); + + + } + drawing.Pop(); + drawing.Pop(); + } +} diff --git a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml b/src/SopHelper.App/VVMs/SopPage/SopPage.xaml index 7e378c3..710d98a 100644 --- a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml +++ b/src/SopHelper.App/VVMs/SopPage/SopPage.xaml @@ -2,6 +2,7 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" + xmlns:local="clr-namespace:SopHelper.VVMs.SopPage" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}"> @@ -46,6 +47,8 @@ + + diff --git a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs index a320ce4..7758260 100644 --- a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs @@ -45,6 +45,7 @@ public class SopPageViewModel : ViewModelBase /// 最近一次处理过的帧(快照按钮存盘用,由推理线程写入) private FrameResult? _lastFrame; + private FrameResult? _handResult; private WriteableBitmap? _bitmap; private long _frameCount; private long _lastTickCount; @@ -162,6 +163,13 @@ public class SopPageViewModel : ViewModelBase set { SetProperty(ref _frame, value); } } + /// 最近一次手部检测结果,交给图像上方的绘制层。 + public FrameResult? HandResult + { + get => _handResult; + private set => SetProperty(ref _handResult, value); + } + /// 状态 public string StatusText { @@ -190,6 +198,7 @@ public class SopPageViewModel : ViewModelBase set { if (!SetProperty(ref _isRunning, value)) return; + if (!value) HandResult = null; RaisePropertyChanged(nameof(CanSelectCamera)); RaiseCommands(); } @@ -511,6 +520,7 @@ public class SopPageViewModel : ViewModelBase private void ApplyRecipe() { + HandResult = null; if (string.IsNullOrWhiteSpace(SelectedRecipe)) return; var path = Path.Combine(RecipeDirectory, SelectedRecipe); @@ -554,6 +564,9 @@ public class SopPageViewModel : ViewModelBase foreach (var warning in _pipeline.Warnings) Log("warn", warning); + + if (options.PalmModelPath is null || options.LandmarkModelPath is null) + Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件"); } /// @@ -570,6 +583,7 @@ public class SopPageViewModel : ViewModelBase private void OnResult(FrameResult result) { + if (_destroyed || !IsRunning) return; lock (_frameLock) { _lastFrame = result; @@ -577,6 +591,9 @@ public class SopPageViewModel : ViewModelBase _engine.ProcessFrame(result); + // 无手结果也要更新,立即清除上一帧手部标记。 + HandResult = result; + InferenceText = $"{result.InferenceMs:F1} ms"; } @@ -606,6 +623,7 @@ public class SopPageViewModel : ViewModelBase // ROI 覆盖层的坐标系就是帧像素坐标系,所以内层 Grid 尺寸必须跟着帧走 FrameWidth = src.Cols; FrameHeight = src.Rows; + if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null; } var bytes = new byte[src.Rows * src.Cols * src.Channels()]; diff --git a/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs b/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs index 31eb149..178bdb9 100644 --- a/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs +++ b/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs @@ -43,11 +43,13 @@ public class MediaPipeHandDetector : IDisposable if (!File.Exists(palmModelPath) || !File.Exists(landmarkModelPath)) return; + var palmModel = PalmModelLoader.Read(palmModelPath); + if (preferGpu) { try { - _palm = new InferenceSession(palmModelPath, Options(true)); + _palm = new InferenceSession(palmModel, Options(true)); _landmark = new InferenceSession(landmarkModelPath, Options(true)); UsingGpu = true; return; @@ -58,7 +60,7 @@ public class MediaPipeHandDetector : IDisposable } } - _palm = new InferenceSession(palmModelPath, Options(false)); + _palm = new InferenceSession(palmModel, Options(false)); _landmark = new InferenceSession(landmarkModelPath, Options(false)); UsingGpu = false; } @@ -86,7 +88,7 @@ public class MediaPipeHandDetector : IDisposable foreach (var palm in DetectPalms(bgr).OrderByDescending(p => p.Score)) { if (hands.Count >= _maxHands) break; - if (taken.Any(t => IoU(t, palm.Rect) > 0.3f)) continue; + if (taken.Any(t => IoU(t, palm.DetectionRect) > 0.3f)) continue; var crop = CropRotatedSquare(bgr, palm, out var map); if (crop is null || map is null) continue; @@ -97,7 +99,7 @@ public class MediaPipeHandDetector : IDisposable if (hand is null) continue; hands.Add(hand); - taken.Add(palm.Rect); + taken.Add(palm.DetectionRect); } } @@ -162,7 +164,8 @@ public class MediaPipeHandDetector : IDisposable var x2 = FromCanvas(boxesT[0, i, 2] * PalmInputSize, lb.PadX, lb.Scale); var y2 = FromCanvas(boxesT[0, i, 3] * PalmInputSize, lb.PadY, lb.Scale); - list.Add(new PalmRect((x1 + x2) / 2f, (y1 + y2) / 2f, Math.Max(x2 - x1, y2 - y1), 0, score)); + var side = Math.Max(x2 - x1, y2 - y1); + list.Add(new PalmRect((x1 + x2) / 2f, (y1 + y2) / 2f, side, 0, score, side)); } return list; @@ -171,7 +174,7 @@ public class MediaPipeHandDetector : IDisposable /// /// 单阶段导出专用解析:输出 [N,8] = [score, cx, cy, w, wrist_x, wrist_y, middle_x, middle_y], /// 全部相对 letterbox 画布归一化,score 已是 sigmoid 后的值。 - /// 照官方 demo:框边长 = w × 192 × 1.25;旋转角由手腕→中指根方向算出, + /// 框边长 = w × 192 × 2.5;旋转角由手腕→中指根方向算出, /// 把这只手"旋正"到指尖朝上再喂关键点模型。 /// private List ParseSingleStage(Tensor flat, Letterbox lb) @@ -204,7 +207,7 @@ public class MediaPipeHandDetector : IDisposable var cy = FromCanvas(cyCanvas, lb.PadY, lb.Scale); var side = (float)(sideCanvas / lb.Scale); - list.Add(new PalmRect(cx, cy, side, degree, score)); + list.Add(new PalmRect(cx, cy, side, degree, score, side / LandmarkScaleFactor)); } return list; @@ -474,9 +477,11 @@ public class MediaPipeHandDetector : IDisposable private sealed record Letterbox(double Scale, double PadX, double PadY); /// palm 结果(原图像素坐标 + 旋正角度) - private sealed record PalmRect(float CenterX, float CenterY, float Side, double Degree, float Score) + private sealed record PalmRect(float CenterX, float CenterY, float Side, double Degree, float Score, float DetectionSide) { public DetRect Rect => new(CenterX - Side / 2f, CenterY - Side / 2f, Side, Side); + // 去重用原始手掌框,不能用扩大 2.5 倍的关键点裁剪框,否则邻近双手会互相抑制。 + public DetRect DetectionRect => new(CenterX - DetectionSide / 2f, CenterY - DetectionSide / 2f, DetectionSide, DetectionSide); } /// 旋正裁剪的逆变换参数(画布坐标) diff --git a/src/SopHelper.Engine/Inference/PalmModelLoader.cs b/src/SopHelper.Engine/Inference/PalmModelLoader.cs new file mode 100644 index 0000000..bc320ef --- /dev/null +++ b/src/SopHelper.Engine/Inference/PalmModelLoader.cs @@ -0,0 +1,112 @@ +using System.Buffers.Binary; +using System.Text; + +namespace SopHelper.Engine.Inference; + +/// 适配把 NMS 最大输出数写死为 1 的 palm ONNX 导出,不修改磁盘上的模型。 +internal static class PalmModelLoader +{ + // ONNX 使用 protobuf。保留未改字段的原始字节,仅重写 NMS 的第三个输入并添加独立常量。 + // 原常量还被 Slice/Mul 共用,不能直接把其值从 1 改成 2。 + internal static byte[] Read(string path) + { + var original = File.ReadAllBytes(path); + var model = Parse(original); + var graphIndex = model.FindIndex(f => f.Number == 7 && f.Wire == 2); + if (graphIndex < 0) return original; + var graph = Parse(model[graphIndex].Payload); + var singleOutputConstants = graph.Where(f => f.Number == 5 && f.Wire == 2) + .Select(f => Parse(f.Payload)) + .Where(t => t.Any(f => f.Number == 2 && f.Wire == 0 && f.Payload.SequenceEqual(new byte[] { 7 })) && + t.Any(f => f.Number == 9 && f.Payload.Length == 8 && BinaryPrimitives.ReadInt64LittleEndian(f.Payload) == 1)) + .Select(t => Text(t, 8)).ToHashSet(); + var constantName = "sophelper_palm_nms_candidates"; + var names = graph.Where(f => f.Number == 5 && f.Wire == 2).Select(f => Text(Parse(f.Payload), 8)).ToHashSet(); + while (names.Contains(constantName)) constantName += "_"; + var changed = false; + for (var i = 0; i < graph.Count; i++) + { + if (graph[i].Number != 1 || graph[i].Wire != 2) continue; + var node = Parse(graph[i].Payload); + if (Text(node, 4) != "NonMaxSuppression") continue; + var inputs = node.Select((field, index) => (field, index)).Where(x => x.field.Number == 1).ToArray(); + if (inputs.Length < 3 || !singleOutputConstants.Contains(Encoding.UTF8.GetString(inputs[2].field.Payload))) continue; + node[inputs[2].index] = Bytes(1, Encoding.UTF8.GetBytes(constantName)); + graph[i] = Bytes(1, Serialize(node)); + changed = true; + } + if (!changed) return original; + var value = new byte[8]; + BinaryPrimitives.WriteInt64LittleEndian(value, 32); // 候选数;实际保留数量仍由 MaxHands 控制。 + graph.Add(Bytes(5, Serialize([ + new Field(1, 0, [1]), // TensorProto.dims = [1] + new Field(2, 0, [7]), // INT64 + Bytes(8, Encoding.UTF8.GetBytes(constantName)), + Bytes(9, value), + ]))); + model[graphIndex] = Bytes(7, Serialize(graph)); + return Serialize(model); + } + + private sealed record Field(int Number, int Wire, byte[] Payload); + private static Field Bytes(int number, byte[] value) => new(number, 2, value); + private static string Text(List fields, int number) => + Encoding.UTF8.GetString(fields.FirstOrDefault(f => f.Number == number && f.Wire == 2)?.Payload ?? []); + + private static ulong Varint(byte[] data, ref int offset) + { + ulong value = 0; + for (var shift = 0; shift < 64 && offset < data.Length; shift += 7) + { + var next = data[offset++]; + value |= (ulong)(next & 127) << shift; + if (next < 128) return value; + } + throw new InvalidDataException("无效的 ONNX protobuf varint"); + } + + private static List Parse(byte[] data) + { + var fields = new List(); + var offset = 0; + while (offset < data.Length) + { + var key = Varint(data, ref offset); + var wire = (int)(key & 7); + var start = offset; + int length; + if (wire == 0) { Varint(data, ref offset); length = offset - start; } + else + { + length = wire switch + { + 1 => 8, 5 => 4, 2 => checked((int)Varint(data, ref offset)), + _ => throw new InvalidDataException("不支持的 ONNX protobuf wire type"), + }; + start = offset; + if (length > data.Length - start) throw new InvalidDataException("ONNX 字段长度越界"); + offset += length; + } + fields.Add(new Field(checked((int)(key >> 3)), wire, data.AsSpan(start, length).ToArray())); + } + return fields; + } + + private static byte[] Serialize(List fields) + { + using var stream = new MemoryStream(); + foreach (var field in fields) + { + WriteVarint(stream, (ulong)((field.Number << 3) | field.Wire)); + if (field.Wire == 2) WriteVarint(stream, (ulong)field.Payload.Length); + stream.Write(field.Payload); + } + return stream.ToArray(); + } + + private static void WriteVarint(Stream stream, ulong value) + { + while (value >= 128) { stream.WriteByte((byte)((value & 127) | 128)); value >>= 7; } + stream.WriteByte((byte)value); + } +} diff --git a/tests/HandDetectionSmoke/HandDetectionSmoke.csproj b/tests/HandDetectionSmoke/HandDetectionSmoke.csproj new file mode 100644 index 0000000..a9ad8ab --- /dev/null +++ b/tests/HandDetectionSmoke/HandDetectionSmoke.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + enable + enable + x64 + + + + + diff --git a/tests/HandDetectionSmoke/Program.cs b/tests/HandDetectionSmoke/Program.cs new file mode 100644 index 0000000..5bdc5a1 --- /dev/null +++ b/tests/HandDetectionSmoke/Program.cs @@ -0,0 +1,38 @@ +using System.Security.Cryptography; +using OpenCvSharp; +using SopHelper.Engine.Common; +using SopHelper.Engine.Inference; + +if (args.Length == 0) + throw new ArgumentException("请提供含双手的视频路径;第二个参数可指定模型目录,默认 models"); +var modelDirectory = args.Length > 1 ? args[1] : "models"; +var palm = Path.Combine(modelDirectory, "palm_detection_full_Nx3x192x192_post.onnx"); +var landmark = Path.Combine(modelDirectory, "hand_landmark_sparse_Nx3x224x224.onnx"); +var before = SHA256.HashData(File.ReadAllBytes(palm)); +using var detector = new MediaPipeHandDetector(); +detector.Load(palm, landmark); +using var video = new VideoCapture(args[0]); +if (!video.IsOpened()) throw new InvalidOperationException("视频无法打开"); +using var frame = new Mat(); +var found = false; +for (var index = 0; index < 300 && video.Read(frame); index++) +{ + if (index % 5 != 0) continue; + var hands = detector.Detect(frame); + if (hands.Count < 2) continue; + if (hands.Any(h => h.Keypoints.Count != 21)) throw new Exception("关键点不完整"); + if (!hands.Any(h => h.HandType == HandType.Left) || !hands.Any(h => h.HandType == HandType.Right)) + continue; + Console.WriteLine($"PASS: 帧 {index} 同时检出左手和右手,均有 21 个关键点"); + detector.SetThresholds(0.5f, 0.5f, 1); + if (detector.Detect(frame).Count != 1) throw new Exception("MaxHands=1 未生效"); + detector.SetThresholds(0.5f, 0.5f, 2); + if (detector.Detect(frame).Count != 2) throw new Exception("MaxHands=2 未生效"); + Console.WriteLine("PASS: MaxHands=1/2 均生效"); + found = true; + break; +} +if (!found) throw new Exception("视频前 300 帧未同时检出左右手"); +if (!before.SequenceEqual(SHA256.HashData(File.ReadAllBytes(palm)))) + throw new Exception("适配不应修改磁盘上的 ONNX 文件"); +Console.WriteLine("PASS: 原始模型文件未改动");