优化:直接仿射裁剪手部区域以消除大画布旋转开销

This commit is contained in:
tfarcraw 2026-11-08 22:21:04 +08:00
parent b0b8d30174
commit b61f14767b
3 changed files with 63 additions and 22 deletions

View File

@ -235,7 +235,7 @@ public class MediaPipeHandDetector : IDisposable
/// <summary>
/// 把 palm 框旋正并裁出正方形(边长 = 框边长),返回裁剪图与逆变换参数。
/// 官方做法:整图先垫大再绕框中心旋转,然后取正方形——保证区域完整落在画布内。
/// 将虚拟填充画布上的旋转与裁剪合为一次仿射变换,只生成手部区域。
/// </summary>
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<double>(0, 2) + pad * (m.At<double>(0, 0) + m.At<double>(0, 1)) - x);
m.Set(1, 2, m.At<double>(1, 2) + pad * (m.At<double>(1, 0) + m.At<double>(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;

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" /></ItemGroup>
</Project>

View File

@ -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<string, double> { ["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");
}