From b61f14767bbf80dbd4bfff410685248a4b56f9be Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Sun, 8 Nov 2026 22:21:04 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E7=9B=B4=E6=8E=A5?=
=?UTF-8?q?=E4=BB=BF=E5=B0=84=E8=A3=81=E5=89=AA=E6=89=8B=E9=83=A8=E5=8C=BA?=
=?UTF-8?q?=E5=9F=9F=E4=BB=A5=E6=B6=88=E9=99=A4=E5=A4=A7=E7=94=BB=E5=B8=83?=
=?UTF-8?q?=E6=97=8B=E8=BD=AC=E5=BC=80=E9=94=80?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Inference/MediaPipeHandDetector.cs | 34 +++++---------
tests/HandCrop.Smoke/HandCrop.Smoke.csproj | 4 ++
tests/HandCrop.Smoke/Program.cs | 47 +++++++++++++++++++
3 files changed, 63 insertions(+), 22 deletions(-)
create mode 100644 tests/HandCrop.Smoke/HandCrop.Smoke.csproj
create mode 100644 tests/HandCrop.Smoke/Program.cs
diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs
index 8b21cea..83dfdc4 100644
--- a/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs
@@ -235,7 +235,7 @@ public class MediaPipeHandDetector : IDisposable
///
/// 把 palm 框旋正并裁出正方形(边长 = 框边长),返回裁剪图与逆变换参数。
- /// 官方做法:整图先垫大再绕框中心旋转,然后取正方形——保证区域完整落在画布内。
+ /// 将虚拟填充画布上的旋转与裁剪合为一次仿射变换,只生成手部区域。
///
private static Mat? CropRotatedSquare(Mat bgr, PalmRect palm, out CropMap? map)
{
@@ -246,33 +246,23 @@ public class MediaPipeHandDetector : IDisposable
var pad = (int)Math.Ceiling(Math.Sqrt((double)bgr.Width * bgr.Width + (double)bgr.Height * bgr.Height));
- using var canvas = new Mat(new Size(bgr.Width + 2L * pad, bgr.Height + 2L * pad), MatType.CV_8UC3, new Scalar(0, 0, 0));
- using (var roi = new Mat(canvas, new Rect(pad, pad, bgr.Width, bgr.Height)))
- {
- bgr.CopyTo(roi);
- }
-
+ var canvasWidth = checked(bgr.Width + 2 * pad);
+ var canvasHeight = checked(bgr.Height + 2 * pad);
+ if (side > canvasWidth || side > canvasHeight) return null;
var cx = palm.CenterX + pad;
var cy = palm.CenterY + pad;
-
- var rotated = new Mat();
+ var x = Math.Max(0, Math.Min((int)Math.Round(cx - side / 2.0), canvasWidth - side));
+ var y = Math.Max(0, Math.Min((int)Math.Round(cy - side / 2.0), canvasHeight - side));
+ var crop = new Mat();
using (var m = Cv2.GetRotationMatrix2D(new Point2f(cx, cy), (float)palm.Degree, 1.0))
{
- Cv2.WarpAffine(canvas, rotated, m, canvas.Size());
+ // 原矩阵的源坐标包含 pad;目标再减去裁剪原点。
+ m.Set(0, 2, m.At(0, 2) + pad * (m.At(0, 0) + m.At(0, 1)) - x);
+ m.Set(1, 2, m.At(1, 2) + pad * (m.At(1, 0) + m.At(1, 1)) - y);
+ try { Cv2.WarpAffine(bgr, crop, m, new Size(side, side), InterpolationFlags.Linear, BorderTypes.Constant, Scalar.Black); }
+ catch { crop.Dispose(); throw; }
}
- var x = Math.Max(0, Math.Min((int)Math.Round(cx - side / 2.0), rotated.Width - side));
- var y = Math.Max(0, Math.Min((int)Math.Round(cy - side / 2.0), rotated.Height - side));
-
- if (side > rotated.Width || side > rotated.Height)
- {
- rotated.Dispose();
- return null;
- }
-
- var crop = new Mat(rotated, new Rect(x, y, side, side)).Clone();
- rotated.Dispose();
-
// 裁剪左上角在旋转画布里的位置,以及逆变换需要的参数
map = new CropMap(pad, cx, cy, palm.Degree, x, y, side);
return crop;
diff --git a/tests/HandCrop.Smoke/HandCrop.Smoke.csproj b/tests/HandCrop.Smoke/HandCrop.Smoke.csproj
new file mode 100644
index 0000000..5716f4b
--- /dev/null
+++ b/tests/HandCrop.Smoke/HandCrop.Smoke.csproj
@@ -0,0 +1,4 @@
+
+ Exenet8.0enableenable
+
+
diff --git a/tests/HandCrop.Smoke/Program.cs b/tests/HandCrop.Smoke/Program.cs
new file mode 100644
index 0000000..fbbe8d9
--- /dev/null
+++ b/tests/HandCrop.Smoke/Program.cs
@@ -0,0 +1,47 @@
+using System.Diagnostics;
+using System.Reflection;
+using OpenCvSharp;
+using SopHelper.Engine.Inference;
+
+var method = typeof(MediaPipeHandDetector).GetMethod("CropRotatedSquare", BindingFlags.NonPublic | BindingFlags.Static)!;
+var palmType = typeof(MediaPipeHandDetector).GetNestedType("PalmRect", BindingFlags.NonPublic)!;
+using var image = new Mat(240, 320, MatType.CV_8UC3);
+Cv2.Randu(image, Scalar.All(0), Scalar.All(255));
+foreach (var angle in new[] { 0.0, 23.5, -75.0, 179.0 })
+foreach (var center in new[] { (160.2f, 119.4f), (10f, 5f), (-12f, 90f), (300f, 210f) })
+foreach (var side in new[] { 96, 221 }) Check(image, center.Item1, center.Item2, side, angle);
+using var large = new Mat(2048, 2448, MatType.CV_8UC3, new Scalar(31, 62, 93));
+Check(large, 400.3f, 300.7f, 640, 35);
+Console.WriteLine("PASS: 33 crops preserve full-canvas pixels and inverse coordinates, including rotations, borders, off-image centers and 5MP input");
+
+void Check(Mat source, float centerX, float centerY, int side, double angle)
+{
+ var pad = (int)Math.Ceiling(Math.Sqrt((double)source.Width * source.Width + (double)source.Height * source.Height));
+ var cx = centerX + pad;var cy = centerY + pad;
+ var watch = Stopwatch.StartNew();
+ // Independent reference: the previous full padded-canvas rotation followed by ROI extraction.
+ using var canvas = new Mat(source.Height + 2 * pad, source.Width + 2 * pad, MatType.CV_8UC3, Scalar.Black);
+ using (var roi = new Mat(canvas, new Rect(pad, pad, source.Width, source.Height))) source.CopyTo(roi);
+ using var rotation = Cv2.GetRotationMatrix2D(new Point2f(cx, cy), angle, 1);
+ using var rotated = new Mat();
+ Cv2.WarpAffine(canvas, rotated, rotation, canvas.Size());
+ var x = Math.Max(0, Math.Min((int)Math.Round(cx - side / 2.0), rotated.Width - side));
+ var y = Math.Max(0, Math.Min((int)Math.Round(cy - side / 2.0), rotated.Height - side));
+ using var expected = new Mat(rotated, new Rect(x, y, side, side));
+ var referenceMs = watch.Elapsed.TotalMilliseconds;
+ var palm = Activator.CreateInstance(palmType, centerX, centerY, (float)side, angle, 0.9f, side / 2.5f);
+ var args = new object?[] { source, palm, null };
+ watch.Restart();
+ using var actual = (Mat?)method.Invoke(null, args) ?? throw new Exception("Crop unexpectedly rejected");
+ var directMs = watch.Elapsed.TotalMilliseconds;
+ using var difference = new Mat();Cv2.Absdiff(expected, actual, difference);
+ var mean = Cv2.Mean(difference);
+ var max = Cv2.Norm(expected, actual, NormTypes.INF);
+ if (max > 8 || Math.Max(mean.Val0, Math.Max(mean.Val1, mean.Val2)) > 0.05)
+ throw new Exception($"Crop pixels changed: angle={angle}, center={centerX},{centerY}, side={side}, max={max}, mean={mean}");
+ var map = args[2] ?? throw new Exception("Missing inverse map");
+ var fields = new Dictionary { ["Pad"] = pad, ["Cx"] = cx, ["Cy"] = cy, ["Degree"] = angle, ["X"] = x, ["Y"] = y, ["Side"] = side };
+ foreach (var (name, value) in fields)
+ if (Convert.ToDouble(map.GetType().GetProperty(name)!.GetValue(map)) != value) throw new Exception("Inverse coordinate changed: " + name);
+ if (source.Width == 2448) Console.WriteLine($"5MP crop: reference={referenceMs:F2}ms direct={directMs:F2}ms");
+}