aisop/src/SopHelper.Linux/Program.cs

128 lines
6.9 KiB
C#

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Themes.Fluent;
using Avalonia.Styling;
using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
using System.Diagnostics;
using System.Text.Json;
namespace SopHelper.Linux;
internal static class Program
{
public static string Root => AppContext.BaseDirectory;
public static bool UiSmoke;
[STAThread]
public static int Main(string[] args)
{
Directory.SetCurrentDirectory(Root);
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS",
Environment.GetEnvironmentVariable("SOPHELPER_CPU_THREADS") ?? Math.Min(8, Environment.ProcessorCount).ToString());
if (args.Contains("--self-test")) return SelfTest.Run();
if (Array.IndexOf(args, "--video-test") is var videoIndex && videoIndex >= 0)
return videoIndex + 1 < args.Length ? SelfTest.Video(args[videoIndex + 1]) : 2;
UiSmoke = args.Contains("--ui-smoke");
return AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
.LogToTrace().StartWithClassicDesktopLifetime(args);
}
}
internal sealed class DesktopApp : Application
{
public override void Initialize()
{
RequestedThemeVariant = ThemeVariant.Dark;
Styles.Add(new FluentTheme());
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();
base.OnFrameworkInitializationCompleted();
}
}
internal static class SelfTest
{
public static int Video(string path)
{
try
{
using var yolo = new YoloDetector(); using var hand = new MediaPipeHandDetector();
yolo.Load("models/yolo11n.onnx", [], 640, false);
hand.Load("models/palm_detection_full_Nx3x192x192_post.onnx", "models/hand_landmark_sparse_Nx3x224x224.onnx", false);
using var capture = new VideoCapture(path); using var frame = new Mat();
if (!capture.IsOpened()) throw new IOException("测试视频无法打开");
var timings = new List<double>(); var maxHands = 0; var maxObjects = 0; var left = false; var right = false;
Directory.CreateDirectory("workspace");
for (var index = 0; index < 300 && capture.Read(frame); index++)
{
if (index % 5 != 0) continue;
var timer = Stopwatch.StartNew();
var result = new FrameResult { Detections = yolo.Detect(frame), Hands = hand.Detect(frame), Size = (frame.Width,frame.Height) };
timer.Stop(); timings.Add(timer.Elapsed.TotalMilliseconds);
maxObjects = Math.Max(maxObjects,result.Detections.Count);
left |= result.Hands.Any(h=>h.HandType==HandType.Left); right |= result.Hands.Any(h=>h.HandType==HandType.Right);
if (result.Hands.Any(h=>h.Keypoints.Count!=21)) throw new Exception("关键点输出不完整");
if (result.Hands.Count > maxHands)
{
maxHands = result.Hands.Count;
using var display = frame.Clone(); DetectionSession.Draw(display,result,new SopConfig());
Cv2.ImWrite("workspace/video-test-hands.jpg",display);
}
}
if (timings.Count == 0 || maxHands == 0) throw new Exception("测试视频没有产生手部结果");
var sorted=timings.Order().ToArray();
var json=JsonSerializer.Serialize(new { passed=true,frames=timings.Count,maxHands,left,right,maxObjects,
meanDetectionMs=timings.Average(), p95DetectionMs=sorted[(int)Math.Floor((sorted.Length-1)*.95)],
note="YOLO + actual hand pipeline including preprocessing and decoding; sampled video, no display or playback pacing" },new JsonSerializerOptions{WriteIndented=true});
File.WriteAllText("workspace/video-test.json",json); Console.WriteLine(json); return 0;
}
catch(Exception ex) { Console.Error.WriteLine(ex); return 1; }
}
public static int Run()
{
try
{
Directory.CreateDirectory("workspace");
using var yolo = new YoloDetector();
using var hand = new MediaPipeHandDetector();
yolo.Load("models/yolo11n.onnx", [], 640, false);
hand.Load("models/palm_detection_full_Nx3x192x192_post.onnx", "models/hand_landmark_sparse_Nx3x224x224.onnx", false);
if (!yolo.IsReady || !hand.IsReady) throw new Exception("模型未就绪");
using var frame = new Mat(480, 640, MatType.CV_8UC3, new Scalar(35, 28, 22));
Cv2.PutText(frame, "SopHelper Linux - SMOKE TEST", new OpenCvSharp.Point(35, 200), HersheyFonts.HersheySimplex, .8, Scalar.White, 2);
for (var i = 0; i < 3; i++) { yolo.Detect(frame); hand.Detect(frame); }
var timer = Stopwatch.StartNew();
for (var i = 0; i < 10; i++) { yolo.Detect(frame); hand.Detect(frame); }
timer.Stop();
var engine = new SopEngine();
var config = SopConfigLoader.Parse("sop:\n name: Linux smoke\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: Clock\n detection:\n method: time_elapsed\n duration_ms: 1\n");
engine.Load(config); engine.Start(); Thread.Sleep(10);
engine.ProcessFrame(new FrameResult { Size = (640, 480), Timestamp = DateTime.Now });
if (engine.State != EngineState.Completed) throw new Exception("SOP 状态机测试失败");
Cv2.ImWrite("workspace/smoke-frame.png", frame);
// A real video file exercises the same videoio backend used by the desktop player.
using (var writer = new VideoWriter("workspace/smoke-input.avi", FourCC.MJPG, 10, frame.Size()))
{
if (!writer.IsOpened()) throw new Exception("录像编码器不可用");
for (var i = 0; i < 30; i++) writer.Write(frame);
}
using var capture = new VideoCapture("workspace/smoke-input.avi");
using var read = new Mat();
if (!capture.Read(read) || read.Empty()) throw new Exception("视频读取失败");
var result = new { passed = true, opencv = Cv2.GetVersionString(), yoloClasses = yolo.ClassNames.Count,
backend = "CPU", threads = Environment.GetEnvironmentVariable("SOPHELPER_CPU_THREADS"),
meanBlankFrameMs = timer.Elapsed.TotalMilliseconds / 10, sop = engine.State.ToString(), video = "PASS" };
var json = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("workspace/self-test.json", json);
Console.WriteLine(json); return 0;
}
catch (Exception ex) { Console.Error.WriteLine(ex); return 1; }
}
}