aisop/src/SopHelper.Engine/Camera/UvcCameraService.cs
sophelper 061b8cd3be feat(Engine): UVC 相机 + YOLO/MediaPipe 手部 ONNX 推理 + 抽帧管线
- 不引 YoloDotNet(GPL-3.0),自带 YOLOv8 letterbox + DFL 解码 + NMS
- MediaPipe 两阶段照搬参考项目解析:palm 192 → 方形裁剪 → landmark 224
- 相机 MSMF 优先/回退 DSHOW、DSHOW 进程级串行、不重复开同一索引、取帧后不补 Sleep
- 引擎层只用自有 DetRect,不绑定 SkiaSharp/OpenCvSharp/YoloDotNet 类型
2026-11-03 00:59:24 +08:00

289 lines
7.7 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 OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>
/// USB(UVC)相机实现。单相机最小版。
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
/// </summary>
public class UvcCameraService : ICameraService
{
/// <summary>
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
/// </summary>
private static readonly object DshowLock = new();
private readonly object _captureLock = new();
private VideoCapture? _capture;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private long _frameId;
/// <inheritdoc />
public bool IsConnected { get; private set; }
/// <inheritdoc />
public bool IsGrabbing { get; private set; }
/// <inheritdoc />
public event Action<CameraFrame>? FrameArrived;
/// <inheritdoc />
public event Action<bool>? ConnectionChanged;
/// <inheritdoc />
public event Action<string>? Error;
/// <summary>当前相机</summary>
public CameraInfo? Current { get; private set; }
/// <summary>实测帧率(每 2 秒刷新一次)</summary>
public double ActualFps { get; private set; }
/// <inheritdoc />
public Task<List<CameraInfo>> EnumerateAsync()
{
return Task.Run(() =>
{
var list = new List<CameraInfo>();
for (var i = 0; i <= 10; i++)
{
var index = i;
// 跳过本进程已占用的索引:对同一设备重复开 DSHOW 图会原生崩溃
lock (_captureLock)
{
if (_capture is not null && Current?.Index == index)
{
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}(当前已连接)" });
continue;
}
}
lock (DshowLock)
{
try
{
using var probe = new VideoCapture(index, VideoCaptureAPIs.DSHOW);
if (!probe.IsOpened()) continue;
var w = probe.Get(VideoCaptureProperties.FrameWidth);
var h = probe.Get(VideoCaptureProperties.FrameHeight);
if (w <= 0 || h <= 0) continue;
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}({w:F0}x{h:F0})" });
}
catch
{
// 探测失败的设备跳过即可
}
}
}
return list;
});
}
/// <inheritdoc />
public Task<bool> ConnectAsync(CameraInfo camera)
{
return Task.Run(() =>
{
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
_capture.Dispose();
_capture = null;
}
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
_capture = TryOpen(camera.Index, VideoCaptureAPIs.MSMF)
?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW);
if (_capture is null)
{
Error?.Invoke($"相机 {camera.Index} 打不开(MSMF 与 DSHOW 均失败)");
return false;
}
}
}
Current = camera;
IsConnected = true;
ConnectionChanged?.Invoke(true);
return true;
});
}
/// <inheritdoc />
public Task<bool> StartAsync()
{
return Task.Run(() =>
{
VideoCapture capture;
lock (_captureLock)
{
if (_capture is null) return false;
capture = _capture;
}
if (IsGrabbing) return true;
_cts = new CancellationTokenSource();
IsGrabbing = true;
_grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
return true;
});
}
/// <summary>
/// 采集循环
/// </summary>
private void GrabLoop(VideoCapture capture, CancellationToken token)
{
var fpsWatch = System.Diagnostics.Stopwatch.StartNew();
var framesInWindow = 0;
while (!token.IsCancellationRequested)
{
var frame = new Mat();
bool ok;
lock (_captureLock)
{
if (captureDisposed) break;
ok = capture.Read(frame);
}
if (!ok || frame.Empty())
{
frame.Dispose();
// 读不到帧时轻微退避,不空转
Thread.Sleep(20);
continue;
}
// ⚠ 成功取帧后不强制 Sleep:Read 本身按相机帧节拍阻塞,
// 补一个 Sleep(33) 会把采集帧率白扣一半(参考项目实测踩过)。
_frameId++;
framesInWindow++;
if (fpsWatch.ElapsedMilliseconds >= 2000)
{
ActualFps = framesInWindow * 1000.0 / fpsWatch.ElapsedMilliseconds;
fpsWatch.Restart();
framesInWindow = 0;
}
var cameraFrame = new CameraFrame
{
FrameId = _frameId,
Timestamp = DateTime.Now,
Bgr = frame,
};
try
{
FrameArrived?.Invoke(cameraFrame);
}
catch (Exception ex)
{
Error?.Invoke($"帧回调异常: {ex.Message}");
}
finally
{
cameraFrame.Dispose();
}
}
IsGrabbing = false;
}
private volatile bool captureDisposed;
/// <inheritdoc />
public void Stop()
{
_cts?.Cancel();
try
{
_grabTask?.Wait(TimeSpan.FromSeconds(2));
}
catch
{
// 取消异常忽略
}
_grabTask = null;
_cts?.Dispose();
_cts = null;
IsGrabbing = false;
}
/// <inheritdoc />
public void Disconnect()
{
Stop();
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
captureDisposed = true;
_capture.Dispose();
_capture = null;
captureDisposed = false;
}
}
// 给系统一点时间把原生图销毁干净,紧接的 ConnectAsync 才安全
Thread.Sleep(500);
}
IsConnected = false;
Current = null;
ConnectionChanged?.Invoke(false);
}
/// <inheritdoc />
public void Dispose()
{
Disconnect();
}
/// <summary>
/// 用指定后端尝试打开
/// </summary>
private static VideoCapture? TryOpen(int index, VideoCaptureAPIs api)
{
try
{
var capture = new VideoCapture(index, api);
if (!capture.IsOpened())
{
capture.Dispose();
return null;
}
return capture;
}
catch
{
return null;
}
}
}