aisop/tests/HandDetectionSmoke/Program.cs

39 lines
2.0 KiB
C#

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(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: 原始模型文件未改动");