Compare commits

...

2 Commits

Author SHA1 Message Date
9a646dbb3c 线程阻塞 2025-09-25 17:21:54 +08:00
1b66fae16c s 2025-09-25 16:33:02 +08:00
2 changed files with 81 additions and 70 deletions

View File

@ -27,6 +27,7 @@ namespace Wpf_AiSportsMicrospace.Common
IPointTracker _rightTracker;
IPointTracker _leftElbow;
IPointTracker _rightElbow;
WebcamClient _webcamClient;
public SportOperate()
{
@ -42,8 +43,8 @@ namespace Wpf_AiSportsMicrospace.Common
}
public WebcamClient CreateRTSP()
{
WebcamClient webcamClient = WebcamClient.CreateRTSP("192.168.3.64", "admin", "yd708090", 554u);
return webcamClient;
_webcamClient = WebcamClient.CreateRTSP("192.168.3.64", "admin", "yd708090", 554u);
return _webcamClient;
}
/// <summary>

View File

@ -1,6 +1,7 @@

using Microsoft.ML.Runtime;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
@ -36,7 +37,8 @@ namespace Wpf_AiSportsMicrospace
private SportBase _sport;
private readonly SportDetectionQueue _detectQueue;
private WebcamClient _webcamClient;
private ConcurrentQueue<VideoFrame> _frameQueue = new();
private CancellationTokenSource _cts = new();
private SportOperate _sportOperate;
public Home()
@ -76,17 +78,36 @@ namespace Wpf_AiSportsMicrospace
_sportOperate = new SportOperate();
_webcamClient = _sportOperate.CreateRTSP();
//处理抽帧回调
_webcamClient.OnExtractFrame += this.OnFrameExtracted;
_webcamClient.StartExtract();//开始抽帧
_webcamClient.OnExtractFrame += frame =>
{
if (frame != null)
_frameQueue.Enqueue(frame);
};
_webcamClient.StartExtract();
StartFrameProcessing();
}
private void OnFrameExtracted(VideoFrame frame)
private void StartFrameProcessing()
{
if (frame == null) return;
// 抽帧和人体识别全部在后台线程
Task.Run(() =>
{
while (!_cts.Token.IsCancellationRequested)
{
if (_frameQueue.TryDequeue(out var frame))
{
ProcessFrame(frame);
}
else
{
Thread.Sleep(5);
}
}
}, _cts.Token);
}
private void ProcessFrame(VideoFrame frame)
{
try
{
@ -133,31 +154,20 @@ namespace Wpf_AiSportsMicrospace
if (liftHandAction == 1)
{
// 启动进度条动画;
SlideCoverFlow(coverFlow.StartSelectedProgress);
return;
Dispatcher.BeginInvoke(() => coverFlow.StartSelectedProgress());
}
}
catch (Exception ex)
{
Console.WriteLine("OnFrameExtracted error: " + ex.Message);
}
});
}
// 抽象 UI 更新到方法中
private void SlideCoverFlow(Action slideAction)
protected override void OnClosed(EventArgs e)
{
Application.Current?.Dispatcher?.BeginInvoke(new Action(() =>
{
try
{
slideAction?.Invoke();
}
catch (Exception ex)
{
Console.WriteLine("UI update error: " + ex.Message);
}
}), System.Windows.Threading.DispatcherPriority.Background);
base.OnClosed(e);
_cts.Cancel();
_webcamClient?.StopExtract();
}
}
}