From 48126f7f8068d25449ff1000702542a6f13ab0e4 Mon Sep 17 00:00:00 2001 From: ldh <17393183636@163.com> Date: Wed, 25 Nov 2026 13:35:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hardware-Vue/src/api/sample.ts | 42 +- Hardware-Vue/src/components/CameraPreview.vue | 37 +- .../src/components/ReportDocument.vue | 2326 +++++++++++++++++ Hardware-Vue/src/components/ReportModal.vue | 396 +++ Hardware-Vue/src/components/ScanVisual.vue | 2 +- Hardware-Vue/src/composables/useCountdown.ts | 3 + Hardware-Vue/src/styles/main.css | 32 + Hardware-Vue/src/views/ResultView.vue | 24 +- Hardware-Vue/src/views/SampleSetupView.vue | 113 +- Hardware-Vue/src/views/ScanPlanView.vue | 55 +- .../HardwareControl.Core.csproj | 12 +- .../HardwareService/ISampleAnalysisService.cs | 18 +- .../SampleAnalysisService.cs | 146 +- .../SampleAnalysis/BackgroundDiffSegmenter.cs | 283 -- .../SampleAnalysis/GpuAdapterEnumerator.cs | 170 ++ .../SampleAnalysis/OnnxSegmentationOptions.cs | 24 +- .../SampleAnalysis/SampleAnalysisModels.cs | 12 - .../SampleAnalysis/TargetOutlineAnalyzer.cs | 305 ++- .../Scanning/ScanWorkflowService.cs | 2 +- .../Controllers/SampleAnalysisController.cs | 43 +- HardwareWeb/HardwareWeb.csproj | 20 + HardwareWeb/Models/SampleAnalysisPayload.cs | 23 +- HardwareWeb/Program.cs | 16 +- .../Services/SampleAnalysisWarmupService.cs | 45 + HardwareWeb/appsettings.json | 4 +- 25 files changed, 3471 insertions(+), 682 deletions(-) create mode 100644 Hardware-Vue/src/components/ReportDocument.vue create mode 100644 Hardware-Vue/src/components/ReportModal.vue delete mode 100644 HardwareControl.Core/SampleAnalysis/BackgroundDiffSegmenter.cs create mode 100644 HardwareControl.Core/SampleAnalysis/GpuAdapterEnumerator.cs create mode 100644 HardwareWeb/Services/SampleAnalysisWarmupService.cs diff --git a/Hardware-Vue/src/api/sample.ts b/Hardware-Vue/src/api/sample.ts index 4c9cc49..cb47f16 100644 --- a/Hardware-Vue/src/api/sample.ts +++ b/Hardware-Vue/src/api/sample.ts @@ -1,17 +1,9 @@ /** * 靶样轮廓识别与采样点规划接口封装。 * 后端实现见 HardwareWeb/Controllers/SampleAnalysisController.cs: - * POST /api/sample/baseline -> { width, height, capturedAt } - * POST /api/sample/target -> { width, height, capturedAt } * POST /api/sample/analyze -> { imageBase64, mimeType, width, height, samplingPointCount, samplingPoints } */ -export interface SampleFrameResult { - width: number - height: number - capturedAt: string -} - export interface SamplePoint { x: number y: number @@ -28,7 +20,9 @@ export interface SampleAnalysisResult { const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '') const DEFAULT_TIMEOUT = 15000 -const ANALYZE_TIMEOUT = 30000 +// 轮廓识别的等待时间优先取系统参数 camera_Identification_outtime, +// 读取失败时使用该默认值。 +const DEFAULT_ANALYZE_TIMEOUT = 60000 export class SampleApiError extends Error { readonly status: number @@ -74,7 +68,9 @@ async function request( } catch (error) { if (error instanceof SampleApiError) throw error if (error instanceof DOMException && error.name === 'AbortError') { - throw new SampleApiError('图像分析服务响应超时') + throw new SampleApiError( + `图像分析服务响应超时(等待上限 ${Math.round(timeout / 1000)} 秒)`, + ) } throw new SampleApiError( error instanceof Error ? error.message : '无法连接图像分析服务', @@ -84,21 +80,27 @@ async function request( } } -/** 相机画面稳定后采集基准画面。 */ -export function captureSampleBaseline(): Promise { - return request('/api/sample/baseline', { method: 'POST' }) -} - -/** 放置靶样并点击开始检测时采集第二张画面。 */ -export function captureSampleTarget(): Promise { - return request('/api/sample/target', { method: 'POST' }) +/** 读取系统参数 camera_Identification_outtime 换算的等待超时(毫秒)。 */ +export async function getAnalyzeTimeoutMs(): Promise { + try { + const result = await request<{ timeoutSeconds: number }>( + '/api/sample/analyze-timeout', + ) + return result.timeoutSeconds > 0 + ? result.timeoutSeconds * 1000 + : DEFAULT_ANALYZE_TIMEOUT + } catch { + return DEFAULT_ANALYZE_TIMEOUT + } } /** 提取靶样轮廓、绘制采样点并返回处理后的图像。 */ -export function analyzeSample(): Promise { +export function analyzeSample( + timeout = DEFAULT_ANALYZE_TIMEOUT, +): Promise { return request( '/api/sample/analyze', { method: 'POST' }, - ANALYZE_TIMEOUT, + timeout, ) } diff --git a/Hardware-Vue/src/components/CameraPreview.vue b/Hardware-Vue/src/components/CameraPreview.vue index 1d55b59..b0bce1b 100644 --- a/Hardware-Vue/src/components/CameraPreview.vue +++ b/Hardware-Vue/src/components/CameraPreview.vue @@ -1,21 +1,14 @@ + + + + diff --git a/Hardware-Vue/src/components/ReportModal.vue b/Hardware-Vue/src/components/ReportModal.vue new file mode 100644 index 0000000..e394145 --- /dev/null +++ b/Hardware-Vue/src/components/ReportModal.vue @@ -0,0 +1,396 @@ + + + + + diff --git a/Hardware-Vue/src/components/ScanVisual.vue b/Hardware-Vue/src/components/ScanVisual.vue index 961c891..3cd7ee9 100644 --- a/Hardware-Vue/src/components/ScanVisual.vue +++ b/Hardware-Vue/src/components/ScanVisual.vue @@ -170,7 +170,7 @@ const markers = [ text-anchor="middle" opacity="0.95" > - 样品图片识别动画 + 样品图片识别中... void, enabled = true, + isPaused: () => boolean = () => false, ) { const remaining = ref(seconds) @@ -15,6 +16,8 @@ export function useCountdown( if (!enabled) return timer = window.setInterval(() => { + if (isPaused()) return + remaining.value = Math.max(0, remaining.value - 1) if (remaining.value === 0 && !finished) { diff --git a/Hardware-Vue/src/styles/main.css b/Hardware-Vue/src/styles/main.css index f5ae3b4..67f37cd 100644 --- a/Hardware-Vue/src/styles/main.css +++ b/Hardware-Vue/src/styles/main.css @@ -179,6 +179,38 @@ ol { transform: translateY(-6px); } +/* 报告导出:屏幕预览使用 #app 内的弹窗,打印时仅保留 A4 报告 DOM。 */ +.report-print-root { + display: none; +} + +@media print { + @page { + size: A4; + margin: 0; + } + + html, + body { + width: 210mm; + height: auto; + overflow: visible; + background: #fff; + } + + #app { + display: none !important; + } + + .toast { + display: none !important; + } + + .report-print-root { + display: block !important; + } +} + @media (prefers-reduced-motion: reduce) { *, *::before, diff --git a/Hardware-Vue/src/views/ResultView.vue b/Hardware-Vue/src/views/ResultView.vue index 2fae75e..1d9d161 100644 --- a/Hardware-Vue/src/views/ResultView.vue +++ b/Hardware-Vue/src/views/ResultView.vue @@ -3,6 +3,7 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue' import { useRoute, useRouter } from 'vue-router' import AppStage from '@/components/AppStage.vue' import PageHeader from '@/components/PageHeader.vue' +import ReportModal from '@/components/ReportModal.vue' import SpectrumChart from '@/components/SpectrumChart.vue' import { getLatestScan, getScan, type ScanRun } from '@/api/scan' import { useCountdown } from '@/composables/useCountdown' @@ -18,6 +19,7 @@ const run = ref(null) const loading = ref(true) const loadError = ref('') const selectedIndex = ref(0) +const reportOpen = ref(false) const viewport = ref(null) const imageWidth = ref(0) @@ -34,7 +36,12 @@ function goHistory() { void router.replace({ name: 'history' }) } -const { remaining } = useCountdown(60, goHome, !isHistoryMode) +const { remaining } = useCountdown( + 60, + goHome, + !isHistoryMode, + () => reportOpen.value, +) const targetScanId = computed(() => { const raw = isHistoryMode ? route.params.scanId : route.query.scanId @@ -159,7 +166,12 @@ async function loadResult() { } function exportReport() { - showToast('报告导出功能正在研发中') + if (!run.value) { + showToast('暂无可导出的检测结果') + return + } + + reportOpen.value = true } onMounted(async () => { @@ -377,6 +389,14 @@ onBeforeUnmount(() => { + + diff --git a/Hardware-Vue/src/views/SampleSetupView.vue b/Hardware-Vue/src/views/SampleSetupView.vue index 2ca4de4..13e9d1c 100644 --- a/Hardware-Vue/src/views/SampleSetupView.vue +++ b/Hardware-Vue/src/views/SampleSetupView.vue @@ -1,19 +1,15 @@ @@ -108,7 +57,7 @@ async function startDetection() {
- + @@ -524,52 +468,17 @@ async function startDetection() { } .guide-actions { - display: grid; - flex: none; - grid-template-columns: minmax(0, 1fr) 320px; - align-items: center; - gap: 18px; - height: 78px; -} - -.capture-status { display: flex; - align-items: center; - gap: 12px; - height: 78px; - padding: 0 24px; - border: 1px solid rgba(130, 175, 255, 0.16); - border-radius: 14px; - background: rgba(10, 24, 48, 0.55); - color: rgba(178, 202, 232, 0.7); - font-size: 17px; - letter-spacing: 1px; - backdrop-filter: blur(12px); -} - -.capture-status__dot { flex: none; - width: 9px; - height: 9px; - border-radius: 50%; - background: #ffd86a; - box-shadow: 0 0 10px rgba(255, 216, 106, 0.8); -} - -.capture-status.is-ready { - border-color: rgba(92, 227, 214, 0.3); - background: rgba(14, 46, 56, 0.5); - color: #8ff5e7; -} - -.capture-status.is-ready .capture-status__dot { - background: #74f4c5; - box-shadow: 0 0 10px rgba(116, 244, 197, 0.9); + justify-content: flex-end; + align-items: center; + height: 78px; } .action-button { display: grid; place-items: center; + width: 320px; height: 78px; border-radius: 14px; font-size: 30px; diff --git a/Hardware-Vue/src/views/ScanPlanView.vue b/Hardware-Vue/src/views/ScanPlanView.vue index 892dca6..b99f124 100644 --- a/Hardware-Vue/src/views/ScanPlanView.vue +++ b/Hardware-Vue/src/views/ScanPlanView.vue @@ -6,7 +6,7 @@ import PageHeader from '@/components/PageHeader.vue' import ScanVisual from '@/components/ScanVisual.vue' import ProgressStrip from '@/components/ProgressStrip.vue' import StatusFooter from '@/components/StatusFooter.vue' -import { analyzeSample, type SampleAnalysisResult } from '@/api/sample' +import { analyzeSample, getAnalyzeTimeoutMs, type SampleAnalysisResult } from '@/api/sample' import { startScan } from '@/api/scan' import { useStageHub } from '@/composables/useStageHub' import { showToast } from '@/composables/useToast' @@ -23,7 +23,11 @@ const scanStarting = ref(false) const { position: stagePosition, connect: connectStageHub } = useStageHub() -let progressTimer: number | undefined +// 首次分析没有历史耗时可参考,按经验值预估;后续使用上一次的真实耗时。 +const FALLBACK_ANALYSIS_DURATION_MS = 20000 + +let progressFrame: number | undefined +let lastAnalysisDurationMs = 0 const resultImageUrl = computed(() => result.value @@ -74,38 +78,61 @@ const footerItems = computed(() => { }) function stopProgress() { - if (progressTimer !== undefined) { - window.clearInterval(progressTimer) - progressTimer = undefined + if (progressFrame !== undefined) { + window.cancelAnimationFrame(progressFrame) + progressFrame = undefined } } -function startProgress() { +/** + * 按真实耗时推进进度:在预估的分析时长内匀速走到 99%, + * 超过预估时长后继续缓慢爬升,分析结束后再置为 100%, + * 避免像以往那样提前卡在固定百分比上空等。 + */ +function startProgress(durationMs: number) { stopProgress() progress.value = 0 - progressTimer = window.setInterval(() => { - if (progress.value >= 90) return - progress.value = Math.min(90, progress.value + (progress.value < 60 ? 4 : 1.5)) - }, 120) + const total = Math.max(1000, durationMs) + const startedAt = performance.now() + + const tick = (now: number) => { + const ratio = (now - startedAt) / total + progress.value = ratio <= 1 + ? ratio * 99 + : 99 + 0.9 * (1 - Math.exp(-(ratio - 1) * 2)) + progressFrame = window.requestAnimationFrame(tick) + } + + progressFrame = window.requestAnimationFrame(tick) } async function runAnalysis() { status.value = 'processing' result.value = null errorMessage.value = '' - startProgress() + progress.value = 0 try { - result.value = await analyzeSample() + const timeout = await getAnalyzeTimeoutMs() + const expectedDuration = Math.min( + timeout, + lastAnalysisDurationMs || FALLBACK_ANALYSIS_DURATION_MS, + ) + startProgress(expectedDuration) + + const startedAt = performance.now() + result.value = await analyzeSample(timeout) + lastAnalysisDurationMs = performance.now() - startedAt + + stopProgress() progress.value = 100 status.value = 'done' } catch (error) { + stopProgress() status.value = 'error' errorMessage.value = error instanceof Error ? error.message : '靶样轮廓分析失败' - } finally { - stopProgress() } } diff --git a/HardwareControl.Core/HardwareControl.Core.csproj b/HardwareControl.Core/HardwareControl.Core.csproj index ede7dd6..c9be027 100644 --- a/HardwareControl.Core/HardwareControl.Core.csproj +++ b/HardwareControl.Core/HardwareControl.Core.csproj @@ -4,6 +4,11 @@ net8.0 enable enable + + x64 @@ -11,7 +16,12 @@ - + + diff --git a/HardwareControl.Core/HardwareService/ISampleAnalysisService.cs b/HardwareControl.Core/HardwareService/ISampleAnalysisService.cs index 527769d..db62ea8 100644 --- a/HardwareControl.Core/HardwareService/ISampleAnalysisService.cs +++ b/HardwareControl.Core/HardwareService/ISampleAnalysisService.cs @@ -3,19 +3,23 @@ using HardwareControl.Core.SampleAnalysis; namespace HardwareControl.Core.HardwareServiceImpl.HardwareService { /// - /// 靶样轮廓与采样点分析服务:基准画面、靶样画面采集与分析。 + /// 靶样轮廓与采样点分析服务:抓取相机当前画面并分析。 /// public interface ISampleAnalysisService { - /// 连续抓取多帧并取中值作为基准背景画面。 - Task CaptureBaselineAsync(CancellationToken ct = default); + /// 抓取相机当前画面,提取轮廓并生成采样点。 + SampleAnalysisResult Analyze(); /// - /// 关闭红外测距光源后抓取当前最新画面作为靶样画面(需先采集基准画面)。 + /// 获取最近一次轮廓分析结果供扫描流程复用; + /// 尚未分析过时立即执行一次分析。 /// - Task CaptureTargetAsync(CancellationToken ct = default); + SampleAnalysisResult GetLatestAnalysis(); - /// 基于基准画面和靶样画面提取轮廓并生成采样点。 - SampleAnalysisResult Analyze(); + /// + /// 前端等待轮廓识别结果的超时时间(秒), + /// 取自系统参数 camera_Identification_outtime。 + /// + int GetIdentificationTimeoutSeconds(); } } diff --git a/HardwareControl.Core/HardwareServiceImpl/SampleAnalysisService.cs b/HardwareControl.Core/HardwareServiceImpl/SampleAnalysisService.cs index a07ced6..1ae7dbe 100644 --- a/HardwareControl.Core/HardwareServiceImpl/SampleAnalysisService.cs +++ b/HardwareControl.Core/HardwareServiceImpl/SampleAnalysisService.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Globalization; using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareControl.Core.SampleAnalysis; @@ -8,16 +9,20 @@ using Microsoft.Extensions.Logging; namespace HardwareControl.Core.HardwareServiceImpl { /// - /// 采集基准画面 / 靶样画面并调用 ONNX 模型分析。 - /// 作为单例使用,保存本次检测的画面。 + /// 抓取相机当前画面并调用 ONNX 模型分析。 + /// 作为单例使用,保存最近一次分析结果供扫描流程复用。 /// public sealed class SampleAnalysisService : ISampleAnalysisService { private const string SamplingPointConfigName = "camera_sampling_point"; private const string SamplingRadiusConfigName = "camera_sampling_radius"; private const string CameraScaleConfigName = "camera_scale"; + private const string IdentificationTimeoutConfigName = "camera_Identification_outtime"; private const int DefaultSamplingPointCount = 5; private const int MaxSamplingPointCount = 100; + private const int DefaultIdentificationTimeoutSeconds = 60; + private const int MinIdentificationTimeoutSeconds = 5; + private const int MaxIdentificationTimeoutSeconds = 300; private readonly IUsbCameraService _camera; private readonly ISystemConfigService _systemConfig; @@ -25,8 +30,6 @@ namespace HardwareControl.Core.HardwareServiceImpl private readonly ILogger _logger; private readonly object _gate = new(); - private IReadOnlyList? _baseline; - private CameraFrameSnapshot? _target; private SampleAnalysisResult? _lastAnalysis; public SampleAnalysisService( @@ -41,75 +44,9 @@ namespace HardwareControl.Core.HardwareServiceImpl _logger = logger; } - public Task CaptureBaselineAsync( - CancellationToken ct = default) - { - ct.ThrowIfCancellationRequested(); - - var frame = CaptureLatestFrame(); - - lock (_gate) - { - _baseline = new[] { frame }; - _target = null; - _lastAnalysis = null; - } - - _logger.LogInformation( - "基准画面已采集:{Width}x{Height}", frame.Width, frame.Height); - - return Task.FromResult( - new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt)); - } - - public Task CaptureTargetAsync( - CancellationToken ct = default) - { - ct.ThrowIfCancellationRequested(); - - var frame = CaptureLatestFrame(); - - lock (_gate) - { - if (_baseline is null || _baseline.Count == 0) - { - throw new HardwareException( - HardwareErrorKind.InvalidState, - "尚未采集基准画面,请等待相机画面稳定后再试"); - } - - _target = frame; - _lastAnalysis = null; - } - - _logger.LogInformation( - "靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height); - - return Task.FromResult( - new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt)); - } - public SampleAnalysisResult Analyze() { - IReadOnlyList baseline; - CameraFrameSnapshot target; - - lock (_gate) - { - baseline = _baseline ?? throw new HardwareException( - HardwareErrorKind.InvalidState, - "尚未采集基准画面,请返回样品放置界面重新检测"); - - target = _target ?? throw new HardwareException( - HardwareErrorKind.InvalidState, - "尚未采集靶样画面,请返回样品放置界面重新检测"); - - // 同一组画面重复调用 Analyze 时直接返回缓存,避免重复执行 ONNX 推理。 - if (_lastAnalysis is not null) - { - return _lastAnalysis; - } - } + var target = CaptureLatestFrame(); var pointCount = GetSamplingPointCount(); var samplingRadiusPixels = GetSamplingRadiusPixels(); @@ -121,32 +58,83 @@ namespace HardwareControl.Core.HardwareServiceImpl ? $"{samplingRadiusPixels.Value:F1}px" : "不限制"); + var watch = Stopwatch.StartNew(); var result = _analyzer.Analyze( - baseline, target, pointCount, samplingRadiusPixels); + target, pointCount, samplingRadiusPixels); + watch.Stop(); _logger.LogInformation( - "靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个", + "靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个,总耗时 {Elapsed} ms", result.Width, result.Height, - result.SamplingPointCount); + result.SamplingPointCount, + watch.ElapsedMilliseconds); lock (_gate) { - // 分析期间如果靶样画面已被重新采集,则不缓存本次结果。 - if (ReferenceEquals(_target, target)) - { - _lastAnalysis = result; - } + _lastAnalysis = result; } return result; } + public SampleAnalysisResult GetLatestAnalysis() + { + lock (_gate) + { + if (_lastAnalysis is not null) + { + return _lastAnalysis; + } + } + + return Analyze(); + } + private CameraFrameSnapshot CaptureLatestFrame() => _camera.GetLatestFrame() ?? throw new HardwareException( HardwareErrorKind.NotConnected, "相机尚未产生画面,请确认相机已连接"); + /// + /// 读取系统参数 camera_Identification_outtime(秒), + /// 作为前端等待轮廓识别结果的超时时间;未配置或无效时使用默认值。 + /// + public int GetIdentificationTimeoutSeconds() + { + try + { + var config = _systemConfig + .GetAll() + .FirstOrDefault(c => string.Equals( + c.ConfigName, + IdentificationTimeoutConfigName, + StringComparison.OrdinalIgnoreCase)); + + if (double.TryParse( + config?.ConfigValue, + NumberStyles.Float, + CultureInfo.InvariantCulture, + out var seconds) && + seconds > 0) + { + return (int)Math.Clamp( + Math.Round(seconds), + MinIdentificationTimeoutSeconds, + MaxIdentificationTimeoutSeconds); + } + } + catch (Exception ex) + { + _logger.LogWarning( + ex, + "读取系统参数 {ConfigName} 失败,使用默认识别超时时间", + IdentificationTimeoutConfigName); + } + + return DefaultIdentificationTimeoutSeconds; + } + private int GetSamplingPointCount() { try diff --git a/HardwareControl.Core/SampleAnalysis/BackgroundDiffSegmenter.cs b/HardwareControl.Core/SampleAnalysis/BackgroundDiffSegmenter.cs deleted file mode 100644 index 1cfcc41..0000000 --- a/HardwareControl.Core/SampleAnalysis/BackgroundDiffSegmenter.cs +++ /dev/null @@ -1,283 +0,0 @@ -using HardwareControl.Core.UsbCamera; -using OpenCvSharp; - -namespace HardwareControl.Core.SampleAnalysis -{ - /// - /// 基于基准帧与靶样帧的 OpenCV 背景差分分割。 - /// 用于 ONNX 模型置信度不足或没有输出时兜底。 - /// 流程:Lab + CLAHE → 颜色/梯度双差分 → 均值+2σ阈值 - /// → 闭运算 + 轮廓填充 → GrabCut 细化。 - /// - public sealed class BackgroundDiffSegmenter - { - private const double MinAreaRatio = 0.0005; - - public Mat? BuildMask( - CameraFrameSnapshot baseline, - CameraFrameSnapshot target) - { - using var targetImage = Decode(target, "靶样画面"); - using var baselineImage = Decode(baseline, "基准画面"); - - if (baselineImage.Size() != targetImage.Size()) - { - Cv2.Resize(baselineImage, baselineImage, targetImage.Size()); - } - - using var baselineLab = new Mat(); - using var targetLab = new Mat(); - using var baselineGray = new Mat(); - using var targetGray = new Mat(); - - Normalize(baselineImage, baselineLab, baselineGray); - Normalize(targetImage, targetLab, targetGray); - - using var colorDiff = BuildColorDifference(baselineLab, targetLab); - using var gradientDiff = BuildGradientDifference(baselineGray, targetGray); - - using var combined = new Mat(); - Cv2.Max(colorDiff, gradientDiff, combined); - Cv2.GaussianBlur(combined, combined, new Size(5, 5), 0); - - using var mask = BuildBinaryMask( - combined, targetImage.Width, targetImage.Height); - - if (Cv2.CountNonZero(mask) == 0) - { - return null; - } - - return RefineWithGrabCut(targetImage, mask); - } - - private static Mat Decode(CameraFrameSnapshot frame, string label) - { - var image = Cv2.ImDecode(frame.ImageData, ImreadModes.Color); - if (image.Empty()) - { - image.Dispose(); - throw new HardwareException( - HardwareErrorKind.InvalidArgument, $"{label}无法解码"); - } - - return image; - } - - /// Lab 色彩空间 + CLAHE 亮度归一化。 - private static void Normalize(Mat bgr, Mat lab, Mat gray) - { - Cv2.CvtColor(bgr, lab, ColorConversionCodes.BGR2Lab); - - var channels = Cv2.Split(lab); - try - { - using var clahe = Cv2.CreateCLAHE(2.0, new Size(8, 8)); - clahe.Apply(channels[0], channels[0]); - Cv2.Merge(channels, lab); - channels[0].CopyTo(gray); - } - finally - { - foreach (var channel in channels) - { - channel.Dispose(); - } - } - } - - /// Lab 三通道绝对差加权,保留低对比度颜色差异。 - private static Mat BuildColorDifference(Mat lab1, Mat lab2) - { - using var diff = new Mat(); - Cv2.Absdiff(lab1, lab2, diff); - - var channels = Cv2.Split(diff); - try - { - using var luminance = new Mat(); - Cv2.AddWeighted(channels[0], 0.6, channels[1], 0.8, 0, luminance); - - var result = new Mat(); - Cv2.AddWeighted(luminance, 1.0, channels[2], 0.8, 0, result); - return result; - } - finally - { - foreach (var channel in channels) - { - channel.Dispose(); - } - } - } - - /// 梯度幅值差分,对低对比度物体边缘更敏感。 - private static Mat BuildGradientDifference(Mat gray1, Mat gray2) - { - using var magnitude1 = GradientMagnitude(gray1); - using var magnitude2 = GradientMagnitude(gray2); - - var diff = new Mat(); - Cv2.Absdiff(magnitude1, magnitude2, diff); - return diff; - } - - private static Mat GradientMagnitude(Mat gray) - { - using var gradientX = new Mat(); - using var gradientY = new Mat(); - Cv2.Sobel(gray, gradientX, MatType.CV_32F, 1, 0, 3); - Cv2.Sobel(gray, gradientY, MatType.CV_32F, 0, 1, 3); - - using var magnitude = new Mat(); - Cv2.Magnitude(gradientX, gradientY, magnitude); - - var result = new Mat(); - Cv2.ConvertScaleAbs(magnitude, result); - return result; - } - - /// - /// 使用均值 + 2σ 阈值,并对闭合边缘做内部填充, - /// 避免低对比度靶样只留下边缘、内部为空。 - /// - private static Mat BuildBinaryMask( - Mat combined, int width, int height) - { - Cv2.MeanStdDev(combined, out var mean, out var stddev); - var threshold = Math.Max(6.0, mean.Val0 + 2.0 * stddev.Val0); - - using var raw = new Mat(); - Cv2.Threshold(combined, raw, threshold, 255, ThresholdTypes.Binary); - - var closeSize = Math.Max(5, Math.Min(width, height) / 120); - if (closeSize % 2 == 0) - { - closeSize++; - } - - using (var closeKernel = Cv2.GetStructuringElement( - MorphShapes.Rect, new Size(closeSize, closeSize))) - { - Cv2.MorphologyEx( - raw, raw, MorphTypes.Close, closeKernel, iterations: 2); - } - - using var contourInput = raw.Clone(); - Cv2.FindContours( - contourInput, - out var contours, - out _, - RetrievalModes.External, - ContourApproximationModes.ApproxSimple); - - var mask = new Mat(height, width, MatType.CV_8UC1, Scalar.All(0)); - var minArea = width * (double)height * MinAreaRatio; - - foreach (var contour in contours) - { - if (Cv2.ContourArea(contour) >= minArea) - { - Cv2.DrawContours( - mask, new[] { contour }, -1, Scalar.All(255), -1); - } - } - - var openSize = Math.Max(3, Math.Min(width, height) / 300); - if (openSize % 2 == 0) - { - openSize++; - } - - using (var openKernel = Cv2.GetStructuringElement( - MorphShapes.Rect, new Size(openSize, openSize))) - { - Cv2.MorphologyEx(mask, mask, MorphTypes.Open, openKernel); - } - - return mask; - } - - /// 用差分掩膜初始化 GrabCut,让边界更贴合物品真实边缘。 - private static Mat RefineWithGrabCut(Mat targetImage, Mat mask) - { - if (Cv2.CountNonZero(mask) == 0) - { - return mask.Clone(); - } - - var bounds = Cv2.BoundingRect(mask); - var padding = Math.Max( - 10, Math.Min(targetImage.Width, targetImage.Height) / 100); - - var left = Math.Max(0, bounds.X - padding); - var top = Math.Max(0, bounds.Y - padding); - var right = Math.Min(targetImage.Width, bounds.Right + padding); - var bottom = Math.Min(targetImage.Height, bounds.Bottom + padding); - var rect = new Rect(left, top, right - left, bottom - top); - - if (rect.Width < 5 || rect.Height < 5) - { - return mask.Clone(); - } - - using var grabMask = new Mat( - targetImage.Size(), - MatType.CV_8UC1, - Scalar.All((byte)GrabCutClasses.PR_BGD)); - grabMask.SetTo(new Scalar((byte)GrabCutClasses.PR_FGD), mask); - - using var kernel = Cv2.GetStructuringElement( - MorphShapes.Rect, new Size(5, 5)); - using var dilated = new Mat(); - Cv2.Dilate(mask, dilated, kernel, iterations: 3); - - using var definiteBackground = new Mat(); - Cv2.BitwiseNot(dilated, definiteBackground); - grabMask.SetTo(new Scalar((byte)GrabCutClasses.BGD), definiteBackground); - - using var backgroundModel = new Mat(); - using var foregroundModel = new Mat(); - - try - { - Cv2.GrabCut( - targetImage, - grabMask, - rect, - backgroundModel, - foregroundModel, - 3, - GrabCutModes.InitWithMask); - } - catch (Exception) - { - return mask.Clone(); - } - - using var foreground = new Mat(); - using var probableForeground = new Mat(); - Cv2.InRange( - grabMask, - new Scalar((int)GrabCutClasses.FGD), - new Scalar((int)GrabCutClasses.FGD), - foreground); - Cv2.InRange( - grabMask, - new Scalar((int)GrabCutClasses.PR_FGD), - new Scalar((int)GrabCutClasses.PR_FGD), - probableForeground); - - var refined = new Mat(); - Cv2.BitwiseOr(foreground, probableForeground, refined); - - if (Cv2.CountNonZero(refined) == 0) - { - refined.Dispose(); - return mask.Clone(); - } - - return refined; - } - } -} diff --git a/HardwareControl.Core/SampleAnalysis/GpuAdapterEnumerator.cs b/HardwareControl.Core/SampleAnalysis/GpuAdapterEnumerator.cs new file mode 100644 index 0000000..ec927fa --- /dev/null +++ b/HardwareControl.Core/SampleAnalysis/GpuAdapterEnumerator.cs @@ -0,0 +1,170 @@ +using System.Runtime.InteropServices; + +namespace HardwareControl.Core.SampleAnalysis +{ + /// + /// 通过 DXGI 枚举本机显卡适配器,用于区分独立显卡与核心显卡。 + /// DirectML 执行后端的 device_id 就是 DXGI 适配器序号,因此这里返回的 + /// 可直接传给 AppendExecutionProvider_DML。 + /// + internal static class GpuAdapterEnumerator + { + /// 独立显卡的专用显存下限,低于该值视为核显。 + private const ulong DiscreteMemoryThreshold = 1024UL * 1024 * 1024; + + private const uint AdapterFlagSoftware = 0x2; + + /// IDXGIFactory1::EnumAdapters1 在虚表中的槽位。 + private const int EnumAdapters1VtableIndex = 12; + + /// IDXGIAdapter1::GetDesc1 在虚表中的槽位。 + private const int GetDesc1VtableIndex = 10; + + private static readonly Guid IID_IDXGIFactory1 = + new("770aae78-f26f-4dba-a829-253c83d1b387"); + + internal sealed record GpuAdapter( + int Index, + string Name, + ulong DedicatedVideoMemory, + bool IsSoftware); + + [DllImport("dxgi.dll")] + private static extern int CreateDXGIFactory1(ref Guid riid, out IntPtr factory); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int EnumAdapters1Delegate( + IntPtr self, uint index, out IntPtr adapter); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetDesc1Delegate(IntPtr self, out DxgiAdapterDesc1 desc); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct DxgiAdapterDesc1 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string Description; + + public uint VendorId; + public uint DeviceId; + public uint SubSysId; + public uint Revision; + public UIntPtr DedicatedVideoMemory; + public UIntPtr DedicatedSystemMemory; + public UIntPtr SharedSystemMemory; + public uint LuidLowPart; + public int LuidHighPart; + public uint Flags; + } + + /// + /// 按硬件使用类型解析可用的显卡适配器。 + /// 指定类型的显卡不存在时退回另一类显卡,完全没有可用显卡时返回 false。 + /// + public static bool TryResolve( + HardwareUsageType usageType, out GpuAdapter adapter) + { + adapter = null!; + + if (usageType == HardwareUsageType.Cpu) + { + return false; + } + + var devices = Enumerate() + .Where(item => !item.IsSoftware) + .ToList(); + + if (devices.Count == 0) + { + return false; + } + + var discrete = devices + .Where(item => item.DedicatedVideoMemory >= DiscreteMemoryThreshold) + .OrderByDescending(item => item.DedicatedVideoMemory) + .ToList(); + + var integrated = devices + .Where(item => item.DedicatedVideoMemory < DiscreteMemoryThreshold) + .OrderBy(item => item.DedicatedVideoMemory) + .ToList(); + + var preferred = usageType == HardwareUsageType.DiscreteGpu + ? discrete.Concat(integrated).FirstOrDefault() + : integrated.Concat(discrete).FirstOrDefault(); + + adapter = preferred!; + return adapter is not null; + } + + /// 枚举全部 DXGI 适配器(包含软件适配器),失败时返回空列表。 + public static IReadOnlyList Enumerate() + { + var adapters = new List(); + IntPtr factory = IntPtr.Zero; + + try + { + var factoryId = IID_IDXGIFactory1; + if (CreateDXGIFactory1(ref factoryId, out factory) < 0 || + factory == IntPtr.Zero) + { + return adapters; + } + + var enumAdapters1 = GetVtableDelegate( + factory, EnumAdapters1VtableIndex); + + for (uint index = 0; ; index++) + { + if (enumAdapters1(factory, index, out var adapter) < 0 || + adapter == IntPtr.Zero) + { + break; + } + + try + { + var getDesc1 = GetVtableDelegate( + adapter, GetDesc1VtableIndex); + + if (getDesc1(adapter, out var desc) >= 0) + { + adapters.Add(new GpuAdapter( + (int)index, + desc.Description ?? string.Empty, + desc.DedicatedVideoMemory.ToUInt64(), + (desc.Flags & AdapterFlagSoftware) != 0)); + } + } + finally + { + Marshal.Release(adapter); + } + } + } + catch + { + // DXGI 不可用(老系统/远程会话限制)时返回空列表,调用方回退 CPU。 + } + finally + { + if (factory != IntPtr.Zero) + { + Marshal.Release(factory); + } + } + + return adapters; + } + + private static T GetVtableDelegate(IntPtr instance, int vtableIndex) + where T : Delegate + { + var vtable = Marshal.ReadIntPtr(instance); + var method = Marshal.ReadIntPtr(vtable, vtableIndex * IntPtr.Size); + return Marshal.GetDelegateForFunctionPointer(method); + } + } +} diff --git a/HardwareControl.Core/SampleAnalysis/OnnxSegmentationOptions.cs b/HardwareControl.Core/SampleAnalysis/OnnxSegmentationOptions.cs index 8254ccf..2018d2a 100644 --- a/HardwareControl.Core/SampleAnalysis/OnnxSegmentationOptions.cs +++ b/HardwareControl.Core/SampleAnalysis/OnnxSegmentationOptions.cs @@ -1,5 +1,18 @@ namespace HardwareControl.Core.SampleAnalysis { + /// 硬件使用类型,对应系统参数 hardware_usage_type。 + public enum HardwareUsageType + { + /// 仅使用 CPU。 + Cpu = 1, + + /// 使用独立显卡(DirectML)。 + DiscreteGpu = 2, + + /// 使用核心显卡(DirectML)。 + IntegratedGpu = 3, + } + /// 靶样 ONNX 分割模型配置。 public sealed class OnnxSegmentationOptions { @@ -18,11 +31,20 @@ namespace HardwareControl.Core.SampleAnalysis public int InputHeight { get; set; } = 640; + /// + /// 推理执行后端:Auto(优先 DirectML,不可用时回退 CPU)、DirectML、Cpu。 + /// DirectML 可调用核显/独显,同时保留 CPU 算子回退。 + /// + public string ExecutionProvider { get; set; } = "Auto"; + + /// DirectML 设备序号,0 表示系统默认适配器。 + public int DmlDeviceId { get; set; } + /// YOLO 分割模型的目标置信度阈值。 public double ConfidenceThreshold { get; set; } = 0.25; /// - /// 模型置信度低于该值时,使用 OpenCV 背景差分兜底识别轮廓。 + /// 模型置信度低于该值时,继续尝试后续模型,取置信度最高的结果。 /// public double FallbackConfidenceThreshold { get; set; } = 0.6; diff --git a/HardwareControl.Core/SampleAnalysis/SampleAnalysisModels.cs b/HardwareControl.Core/SampleAnalysis/SampleAnalysisModels.cs index 0d96dcc..c772fe8 100644 --- a/HardwareControl.Core/SampleAnalysis/SampleAnalysisModels.cs +++ b/HardwareControl.Core/SampleAnalysis/SampleAnalysisModels.cs @@ -1,17 +1,5 @@ namespace HardwareControl.Core.SampleAnalysis { - /// 基准画面信息(放置靶样前)。 - public sealed record SampleBaselineInfo( - int Width, - int Height, - DateTimeOffset CapturedAt); - - /// 靶样画面信息(放置靶样后)。 - public sealed record SampleTargetInfo( - int Width, - int Height, - DateTimeOffset CapturedAt); - /// 图像坐标系下的采样点。 public sealed record SamplePoint(int X, int Y); diff --git a/HardwareControl.Core/SampleAnalysis/TargetOutlineAnalyzer.cs b/HardwareControl.Core/SampleAnalysis/TargetOutlineAnalyzer.cs index 97b9d8b..4b81824 100644 --- a/HardwareControl.Core/SampleAnalysis/TargetOutlineAnalyzer.cs +++ b/HardwareControl.Core/SampleAnalysis/TargetOutlineAnalyzer.cs @@ -1,5 +1,7 @@ +using System.Diagnostics; using System.Runtime.InteropServices; using System.Text.RegularExpressions; +using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareControl.Core.UsbCamera; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -12,34 +14,43 @@ namespace HardwareControl.Core.SampleAnalysis /// /// 基于多个 ONNX 模型的靶样分割与采样点规划。 /// 模型目录内按文件名前面的数字从小到大依次尝试; - /// 模型置信度不足或没有输出时,使用 OpenCV 背景差分兜底。 + /// 模型置信度不足或没有输出时继续尝试后续模型。 /// 支持检测框、YOLO 分割、检测+掩膜、二值/语义分割输出。 /// public sealed class TargetOutlineAnalyzer : IDisposable { + private const string HardwareUsageTypeConfigName = "hardware_usage_type"; + private readonly OnnxSegmentationOptions _options; private readonly ILogger _logger; - private readonly BackgroundDiffSegmenter _backgroundDiff; + private readonly ISystemConfigService _systemConfig; private readonly object _gate = new(); private readonly Dictionary _sessions = new(StringComparer.OrdinalIgnoreCase); + private ProviderSelection _provider; + private bool _providerApplied; + public TargetOutlineAnalyzer( IOptions options, - BackgroundDiffSegmenter backgroundDiff, + ISystemConfigService systemConfig, ILogger logger) { _options = options.Value; - _backgroundDiff = backgroundDiff; + _systemConfig = systemConfig; _logger = logger; + _provider = ResolveProviderFromOptions(); } + /// 当前生效的推理后端; 用于日志。 + private readonly record struct ProviderSelection( + bool UseDirectMl, int DeviceId, string Label); + private int InputWidth => Math.Max(32, _options.InputWidth); private int InputHeight => Math.Max(32, _options.InputHeight); public SampleAnalysisResult Analyze( - IReadOnlyList baselineFrames, CameraFrameSnapshot target, int samplingPointCount, double? samplingRadiusPixels = null) @@ -52,6 +63,8 @@ namespace HardwareControl.Core.SampleAnalysis lock (_gate) { + ApplyHardwareUsageType(); + var models = ResolveModelFiles(); CleanupSessions(models); @@ -67,6 +80,7 @@ namespace HardwareControl.Core.SampleAnalysis foreach (var modelPath in models) { var modelName = Path.GetFileName(modelPath); + var modelWatch = Stopwatch.StartNew(); try { var result = TryAnalyzeWithModel( @@ -77,6 +91,12 @@ namespace HardwareControl.Core.SampleAnalysis out var confidence, out var failureReason); + modelWatch.Stop(); + _logger.LogInformation( + "模型 {Model} 分析耗时 {Elapsed} ms", + modelName, + modelWatch.ElapsedMilliseconds); + if (result is not null) { if (confidence >= _options.FallbackConfidenceThreshold) @@ -100,7 +120,7 @@ namespace HardwareControl.Core.SampleAnalysis $"{_options.FallbackConfidenceThreshold:F2}"); _logger.LogInformation( "模型 {Model} 置信度 {Confidence:F2} 较低," + - "继续尝试后续模型或使用 OpenCV 兜底", + "继续尝试后续模型", modelName, confidence); continue; @@ -119,57 +139,10 @@ namespace HardwareControl.Core.SampleAnalysis } } - // 模型置信度不足或没有结果:使用基准帧与靶样帧做 OpenCV 背景差分 - if (baselineFrames.Count > 0) - { - _logger.LogInformation( - "ONNX 模型未达到置信度要求,启用 OpenCV 背景差分兜底"); - - try - { - using var fallbackMask = _backgroundDiff.BuildMask( - baselineFrames[0], target); - - if (fallbackMask is not null) - { - var fallbackResult = BuildResultFromMask( - fallbackMask, - targetImage, - pointCount, - samplingRadiusPixels, - out var fallbackFailure); - - if (fallbackResult is not null) - { - _logger.LogInformation("OpenCV 背景差分兜底识别成功"); - return fallbackResult; - } - - _logger.LogWarning( - "OpenCV 兜底未生成有效轮廓:{Reason}", fallbackFailure); - attempts.Add($"OpenCV 兜底:{fallbackFailure}"); - } - else - { - _logger.LogWarning("OpenCV 兜底未检测到前后画面差异"); - attempts.Add("OpenCV 兜底:未检测到前后画面差异"); - } - } - catch (Exception ex) - { - _logger.LogWarning(ex, "OpenCV 兜底执行失败"); - attempts.Add($"OpenCV 兜底:{ex.Message}"); - } - } - else - { - _logger.LogWarning("没有基准画面,跳过 OpenCV 兜底"); - } - if (lowConfidenceResult is not null) { _logger.LogWarning( - "OpenCV 兜底失败,返回置信度较低的模型结果:{Model}({Confidence:F2})", + "没有更高置信度的模型结果,返回置信度较低的模型结果:{Model}({Confidence:F2})", lowConfidenceModel, lowConfidence); return lowConfidenceResult; @@ -186,12 +159,46 @@ namespace HardwareControl.Core.SampleAnalysis { lock (_gate) { - foreach (var session in _sessions.Values) + DisposeSessions(); + } + } + + private void DisposeSessions() + { + foreach (var session in _sessions.Values) + { + session.Dispose(); + } + + _sessions.Clear(); + } + + /// + /// 预加载首个 ONNX 模型。大模型(数百 MB)首次加载往往需要数十秒, + /// 在程序启动后放到后台执行,可避免用户点击检测时才等待模型加载。 + /// + public void PreloadPrimaryModel() + { + lock (_gate) + { + ApplyHardwareUsageType(); + + var models = ResolveModelFiles(); + CleanupSessions(models); + + if (models.Count == 0) { - session.Dispose(); + return; } - _sessions.Clear(); + var watch = Stopwatch.StartNew(); + GetSession(models[0]); + watch.Stop(); + + _logger.LogInformation( + "首个 ONNX 模型预热完成:{Model},耗时 {Elapsed} ms", + Path.GetFileName(models[0]), + watch.ElapsedMilliseconds); } } @@ -240,7 +247,15 @@ namespace HardwareControl.Core.SampleAnalysis var inputValue = CreateInputValue( input.Key, letterboxed, inputWidth, inputHeight); + var inferenceWatch = Stopwatch.StartNew(); using var results = session.Run(new[] { inputValue }); + inferenceWatch.Stop(); + _logger.LogInformation( + "模型 {Model} 推理耗时 {Elapsed} ms(输入 {Width}x{Height})", + Path.GetFileName(modelPath), + inferenceWatch.ElapsedMilliseconds, + inputWidth, + inputHeight); var outputs = new List(); foreach (var result in results) @@ -314,13 +329,15 @@ namespace HardwareControl.Core.SampleAnalysis lineThickness, LineTypes.AntiAlias); + using var distanceMap = BuildDistanceMap(mask); var points = BuildSamplingPoints( contour, pointCount, CalculateSamplingMargin(contour, outputImage.Width, outputImage.Height), samplingRadiusPixels, outputImage.Width / 2.0, - outputImage.Height / 2.0); + outputImage.Height / 2.0, + distanceMap); DrawSamplingPoints(outputImage, points, lineThickness); Cv2.ImEncode( @@ -421,15 +438,14 @@ namespace HardwareControl.Core.SampleAnalysis try { - var options = new SessionOptions - { - GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, - }; + using var options = CreateSessionOptions(out var providerName); var session = new InferenceSession(modelPath, options); _sessions[modelPath] = session; _logger.LogInformation( - "ONNX Runtime 模型已加载:{Model}", Path.GetFileName(modelPath)); + "ONNX Runtime 模型已加载:{Model},执行后端:{Provider}", + Path.GetFileName(modelPath), + providerName); return session; } catch (Exception ex) @@ -441,6 +457,139 @@ namespace HardwareControl.Core.SampleAnalysis } } + /// + /// 读取系统参数 hardware_usage_type,与当前生效配置不同时重建会话, + /// 使运行中修改该参数后下一次分析即可切换推理后端。 + /// + private void ApplyHardwareUsageType() + { + var selection = ResolveProvider(); + if (_providerApplied && selection == _provider) + { + return; + } + + DisposeSessions(); + _provider = selection; + _providerApplied = true; + + _logger.LogInformation("ONNX 推理硬件模式:{Provider}", selection.Label); + } + + private ProviderSelection ResolveProvider() + { + var usageType = ReadHardwareUsageType(); + if (usageType is null) + { + return ResolveProviderFromOptions(); + } + + if (usageType == HardwareUsageType.Cpu) + { + return new ProviderSelection( + false, 0, "CPU(hardware_usage_type=1)"); + } + + var label = usageType == HardwareUsageType.DiscreteGpu + ? "独立GPU" + : "核心GPU"; + + if (GpuAdapterEnumerator.TryResolve(usageType.Value, out var adapter)) + { + return new ProviderSelection( + true, + adapter.Index, + $"DirectML {label}(设备 {adapter.Index}:{adapter.Name})"); + } + + _logger.LogWarning( + "hardware_usage_type={UsageType}({Label})未找到可用显卡,回退 CPU 推理", + (int)usageType.Value, + label); + return new ProviderSelection(false, 0, "CPU(未找到可用显卡)"); + } + + private ProviderSelection ResolveProviderFromOptions() + { + var requested = string.IsNullOrWhiteSpace(_options.ExecutionProvider) + ? "Auto" + : _options.ExecutionProvider.Trim(); + + if (requested.Equals("Cpu", StringComparison.OrdinalIgnoreCase)) + { + return new ProviderSelection(false, 0, "CPU"); + } + + var deviceId = Math.Max(0, _options.DmlDeviceId); + return new ProviderSelection(true, deviceId, $"DirectML(设备 {deviceId})"); + } + + private HardwareUsageType? ReadHardwareUsageType() + { + try + { + var config = _systemConfig + .GetAll() + .FirstOrDefault(item => string.Equals( + item.ConfigName, + HardwareUsageTypeConfigName, + StringComparison.OrdinalIgnoreCase)); + + if (int.TryParse(config?.ConfigValue?.Trim(), out var value) && + Enum.IsDefined(typeof(HardwareUsageType), value)) + { + return (HardwareUsageType)value; + } + } + catch (Exception ex) + { + _logger.LogWarning( + ex, + "读取系统参数 {ConfigName} 失败,沿用 appsettings 的推理配置", + HardwareUsageTypeConfigName); + } + + return null; + } + + /// + /// 按当前硬件模式创建会话选项:DirectML 不支持的算子由 ONNX Runtime 自动回退到 CPU。 + /// + private SessionOptions CreateSessionOptions(out string providerName) + { + if (!_provider.UseDirectMl) + { + providerName = _provider.Label; + return CreateCpuOptions(); + } + + var options = new SessionOptions + { + GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, + // DirectML 不支持内存复用模式 + EnableMemoryPattern = false, + }; + + try + { + options.AppendExecutionProvider_DML(_provider.DeviceId); + providerName = _provider.Label; + return options; + } + catch (Exception ex) + { + options.Dispose(); + _logger.LogWarning(ex, "DirectML 初始化失败,回退 CPU 推理"); + providerName = "CPU(DirectML 不可用)"; + return CreateCpuOptions(); + } + } + + private static SessionOptions CreateCpuOptions() => new() + { + GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, + }; + private void CleanupSessions(IReadOnlyCollection currentModels) { var current = new HashSet(currentModels, StringComparer.OrdinalIgnoreCase); @@ -1243,6 +1392,18 @@ namespace HardwareControl.Core.SampleAnalysis return Math.Max(markerRadius + 4, ratioMargin); } + /// + /// 计算掩膜内每个像素到最近边界的距离,供采样点校验一次查表完成, + /// 避免在重试缩放间距时反复对整条轮廓做 PointPolygonTest。 + /// + private static Mat BuildDistanceMap(Mat mask) + { + var distanceMap = new Mat(); + Cv2.DistanceTransform( + mask, distanceMap, DistanceTypes.L2, DistanceTransformMasks.Mask5); + return distanceMap; + } + /// /// 在轮廓内部按网格生成候选点,要求候选点到轮廓的距离不小于安全边距; /// 配置采样半径时,候选点还须位于以画面中心为原点的半径范围内。 @@ -1254,7 +1415,8 @@ namespace HardwareControl.Core.SampleAnalysis double margin, double? radiusPixels, double centerX, - double centerY) + double centerY, + Mat distanceMap) { var area = Cv2.ContourArea(contour); if (area <= 0 || count <= 0) @@ -1285,9 +1447,7 @@ namespace HardwareControl.Core.SampleAnalysis continue; } - var distance = Cv2.PointPolygonTest( - contour, new Point2f(point.X, point.Y), true); - if (distance >= margin) + if (distanceMap.At(point.Y, point.X) >= margin) { candidates.Add(point); } @@ -1306,7 +1466,7 @@ namespace HardwareControl.Core.SampleAnalysis { // 极窄轮廓可能无法满足安全边距,退回到离边缘最远的内部点 var fallback = FindBestInteriorPoint( - contour, radiusPixels, centerX, centerY); + contour, radiusPixels, centerX, centerY, distanceMap); return fallback.HasValue ? new List { fallback.Value } : new List(); @@ -1353,7 +1513,11 @@ namespace HardwareControl.Core.SampleAnalysis /// 找到轮廓内部距边缘最远的点,作为极端情况下的兜底。 private static Point? FindBestInteriorPoint( - Point[] contour, double? radiusPixels, double centerX, double centerY) + Point[] contour, + double? radiusPixels, + double centerX, + double centerY, + Mat distanceMap) { var rect = Cv2.BoundingRect(contour); var step = Math.Max(2, Math.Min(rect.Width, rect.Height) / 50); @@ -1370,8 +1534,7 @@ namespace HardwareControl.Core.SampleAnalysis continue; } - var distance = Cv2.PointPolygonTest( - contour, new Point2f(x, y), true); + var distance = distanceMap.At(y, x); if (distance > bestDistance) { diff --git a/HardwareControl.Core/Scanning/ScanWorkflowService.cs b/HardwareControl.Core/Scanning/ScanWorkflowService.cs index 57cf4e2..7219f34 100644 --- a/HardwareControl.Core/Scanning/ScanWorkflowService.cs +++ b/HardwareControl.Core/Scanning/ScanWorkflowService.cs @@ -127,7 +127,7 @@ namespace HardwareControl.Core.Scanning await _spectrometer.ConnectAsync(ct); } - var sample = _sampleAnalysis.Analyze(); + var sample = _sampleAnalysis.GetLatestAnalysis(); if (sample.SamplingPoints.Count == 0) { throw new HardwareException( diff --git a/HardwareWeb/Controllers/SampleAnalysisController.cs b/HardwareWeb/Controllers/SampleAnalysisController.cs index 2ce1730..6845984 100644 --- a/HardwareWeb/Controllers/SampleAnalysisController.cs +++ b/HardwareWeb/Controllers/SampleAnalysisController.cs @@ -7,7 +7,7 @@ namespace HardwareWeb.Controllers { /// /// 靶样轮廓识别与采样点规划接口。 - /// 流程:采集基准画面 -> 采集靶样画面 -> 分析并返回处理后的图像。 + /// 流程:抓取相机当前画面 -> 分析并返回处理后的图像。 /// [ApiController] [Route("api/sample")] @@ -24,36 +24,21 @@ namespace HardwareWeb.Controllers _logger = logger; } - /// 连续抓取多帧并取中值作为基准背景画面。 - [HttpPost("baseline")] - [ProducesResponseType(typeof(SampleBaselinePayload), StatusCodes.Status200OK)] - public async Task CaptureBaseline(CancellationToken ct) + /// + /// 获取轮廓识别的等待超时时间, + /// 取自系统参数 camera_Identification_outtime(秒)。 + /// + [HttpGet("analyze-timeout")] + [ProducesResponseType(typeof(AnalyzeTimeoutPayload), StatusCodes.Status200OK)] + public IActionResult AnalyzeTimeout() { - try - { - return Ok(SampleBaselinePayload.From( - await _service.CaptureBaselineAsync(ct))); - } - catch (HardwareException ex) - { - return HardwareError(ex); - } - } + var timeoutSeconds = _service.GetIdentificationTimeoutSeconds(); + _logger.LogInformation( + "前端轮廓识别等待超时:{TimeoutSeconds} 秒" + + "(系统参数 camera_Identification_outtime)", + timeoutSeconds); - /// 关闭红外测距光源后抓取当前最新画面作为靶样画面。 - [HttpPost("target")] - [ProducesResponseType(typeof(SampleTargetPayload), StatusCodes.Status200OK)] - public async Task CaptureTarget(CancellationToken ct) - { - try - { - return Ok(SampleTargetPayload.From( - await _service.CaptureTargetAsync(ct))); - } - catch (HardwareException ex) - { - return HardwareError(ex); - } + return Ok(new AnalyzeTimeoutPayload(timeoutSeconds)); } /// 提取靶样轮廓、绘制采样点并返回处理后的 JPEG 图像。 diff --git a/HardwareWeb/HardwareWeb.csproj b/HardwareWeb/HardwareWeb.csproj index 2cf3c9f..159a916 100644 --- a/HardwareWeb/HardwareWeb.csproj +++ b/HardwareWeb/HardwareWeb.csproj @@ -27,4 +27,24 @@ + + + + + + + + + + diff --git a/HardwareWeb/Models/SampleAnalysisPayload.cs b/HardwareWeb/Models/SampleAnalysisPayload.cs index afd3081..0447a0a 100644 --- a/HardwareWeb/Models/SampleAnalysisPayload.cs +++ b/HardwareWeb/Models/SampleAnalysisPayload.cs @@ -2,29 +2,12 @@ using HardwareControl.Core.SampleAnalysis; namespace HardwareWeb.Models { - /// 基准画面采集结果。 - public sealed record SampleBaselinePayload( - int Width, - int Height, - DateTimeOffset CapturedAt) - { - public static SampleBaselinePayload From(SampleBaselineInfo info) => - new(info.Width, info.Height, info.CapturedAt); - } - - /// 靶样画面采集结果。 - public sealed record SampleTargetPayload( - int Width, - int Height, - DateTimeOffset CapturedAt) - { - public static SampleTargetPayload From(SampleTargetInfo info) => - new(info.Width, info.Height, info.CapturedAt); - } - /// 采样点坐标(图像像素)。 public sealed record SamplePointPayload(int X, int Y); + /// 轮廓识别等待超时(单位:秒)。 + public sealed record AnalyzeTimeoutPayload(int TimeoutSeconds); + /// 靶样轮廓与采样点分析结果。 public sealed record SampleAnalysisPayload( string ImageBase64, diff --git a/HardwareWeb/Program.cs b/HardwareWeb/Program.cs index 29872f6..400443d 100644 --- a/HardwareWeb/Program.cs +++ b/HardwareWeb/Program.cs @@ -56,8 +56,8 @@ builder.Services.AddSingleton(); // 8. 靶样轮廓识别与采样点规划(ONNX 模型分割) builder.Services.Configure( builder.Configuration.GetSection(OnnxSegmentationOptions.SectionName)); -builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddHostedService(); builder.Services.AddSingleton(); // 9. 位移台:串口优先取系统参数 translation_com,未配置时回退到 appsettings 的 AxisStage:ComPort @@ -105,7 +105,19 @@ app.UseAuthorization(); //这两行是用来托管前端的 app.UseDefaultFiles(); -app.UseStaticFiles(); +app.UseStaticFiles(new StaticFileOptions +{ + OnPrepareResponse = context => + { + // 入口页禁止缓存,避免前端重新构建后浏览器仍加载旧的 JS 资源。 + if (string.Equals( + context.File.Name, "index.html", StringComparison.OrdinalIgnoreCase)) + { + context.Context.Response.Headers.CacheControl = + "no-cache, no-store, must-revalidate"; + } + }, +}); app.MapControllers(); diff --git a/HardwareWeb/Services/SampleAnalysisWarmupService.cs b/HardwareWeb/Services/SampleAnalysisWarmupService.cs new file mode 100644 index 0000000..d0bfa69 --- /dev/null +++ b/HardwareWeb/Services/SampleAnalysisWarmupService.cs @@ -0,0 +1,45 @@ +using HardwareControl.Core.SampleAnalysis; + +namespace HardwareWeb.Services +{ + /// + /// 应用启动后在后台预热靶样轮廓分析模型。 + /// 大模型首次加载往往需要数十秒,放到后台执行可以避免用户点击检测时才等待。 + /// + public sealed class SampleAnalysisWarmupService : IHostedService + { + private readonly TargetOutlineAnalyzer _analyzer; + private readonly ILogger _logger; + + public SampleAnalysisWarmupService( + TargetOutlineAnalyzer analyzer, + ILogger logger) + { + _analyzer = analyzer; + _logger = logger; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + _ = Task.Run( + () => + { + try + { + _analyzer.PreloadPrimaryModel(); + } + catch (Exception ex) + { + _logger.LogWarning( + ex, "靶样分析模型预热失败,将在检测时重新加载"); + } + }, + CancellationToken.None); + + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) => + Task.CompletedTask; + } +} diff --git a/HardwareWeb/appsettings.json b/HardwareWeb/appsettings.json index 5ffb550..7466197 100644 --- a/HardwareWeb/appsettings.json +++ b/HardwareWeb/appsettings.json @@ -49,7 +49,7 @@ }, "SystemSetting": { "DatabasePath": null, - "AdminPassword": "flzx3QC!1" + "AdminPassword": "123456" }, "Scanning": { "DatabasePath": null, @@ -60,6 +60,8 @@ "ModelDirectory": "Models", "InputWidth": 640, "InputHeight": 640, + "ExecutionProvider": "Auto", + "DmlDeviceId": 0, "ConfidenceThreshold": 0.25, "FallbackConfidenceThreshold": 0.6, "MaskThreshold": 0.5,