aisop/tests/HandDetectionSmoke/Program.cs

43 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Security.Cryptography;
using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
var positional = args.Where(a => !a.StartsWith("--")).ToArray();
if (positional.Length == 0)
throw new ArgumentException("请提供含双手的视频路径;第二个参数可指定模型目录,默认 models");
var modelDirectory = positional.Length > 1 ? positional[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, preferGpu: !args.Contains("--cpu"), requireGpu: args.Contains("--require-gpu"));
Console.WriteLine($"手部推理后端:{detector.Backend}");
if (detector.GpuFallbackReason is not null) Console.WriteLine($"GPU 回退原因:{detector.GpuFallbackReason}");
if (args.Contains("--require-gpu") && !detector.UsingGpu) throw new Exception("测试要求使用 GPU,但实际回退了 CPU");
using var video = new VideoCapture(positional[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(MediaPipeHandDetector.DefaultPalmThreshold, MediaPipeHandDetector.DefaultKeypointThreshold, 1);
if (detector.Detect(frame).Count != 1) throw new Exception("MaxHands=1 未生效");
detector.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold, MediaPipeHandDetector.DefaultKeypointThreshold, 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: 原始模型文件未改动");