提交代码

This commit is contained in:
ldh
2026-11-25 13:35:06 +08:00
parent 162bc73395
commit 48126f7f80
25 changed files with 3471 additions and 682 deletions
+22 -20
View File
@@ -1,17 +1,9 @@
/** /**
* 靶样轮廓识别与采样点规划接口封装。 * 靶样轮廓识别与采样点规划接口封装。
* 后端实现见 HardwareWeb/Controllers/SampleAnalysisController.cs: * 后端实现见 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 } * POST /api/sample/analyze -> { imageBase64, mimeType, width, height, samplingPointCount, samplingPoints }
*/ */
export interface SampleFrameResult {
width: number
height: number
capturedAt: string
}
export interface SamplePoint { export interface SamplePoint {
x: number x: number
y: number y: number
@@ -28,7 +20,9 @@ export interface SampleAnalysisResult {
const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '') const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '')
const DEFAULT_TIMEOUT = 15000 const DEFAULT_TIMEOUT = 15000
const ANALYZE_TIMEOUT = 30000 // 轮廓识别的等待时间优先取系统参数 camera_Identification_outtime,
// 读取失败时使用该默认值。
const DEFAULT_ANALYZE_TIMEOUT = 60000
export class SampleApiError extends Error { export class SampleApiError extends Error {
readonly status: number readonly status: number
@@ -74,7 +68,9 @@ async function request<T>(
} catch (error) { } catch (error) {
if (error instanceof SampleApiError) throw error if (error instanceof SampleApiError) throw error
if (error instanceof DOMException && error.name === 'AbortError') { if (error instanceof DOMException && error.name === 'AbortError') {
throw new SampleApiError('图像分析服务响应超时') throw new SampleApiError(
`图像分析服务响应超时(等待上限 ${Math.round(timeout / 1000)} 秒)`,
)
} }
throw new SampleApiError( throw new SampleApiError(
error instanceof Error ? error.message : '无法连接图像分析服务', error instanceof Error ? error.message : '无法连接图像分析服务',
@@ -84,21 +80,27 @@ async function request<T>(
} }
} }
/** 相机画面稳定后采集基准画面。 */ /** 读取系统参数 camera_Identification_outtime 换算的等待超时(毫秒)。 */
export function captureSampleBaseline(): Promise<SampleFrameResult> { export async function getAnalyzeTimeoutMs(): Promise<number> {
return request<SampleFrameResult>('/api/sample/baseline', { method: 'POST' }) try {
} const result = await request<{ timeoutSeconds: number }>(
'/api/sample/analyze-timeout',
/** 放置靶样并点击开始检测时采集第二张画面。 */ )
export function captureSampleTarget(): Promise<SampleFrameResult> { return result.timeoutSeconds > 0
return request<SampleFrameResult>('/api/sample/target', { method: 'POST' }) ? result.timeoutSeconds * 1000
: DEFAULT_ANALYZE_TIMEOUT
} catch {
return DEFAULT_ANALYZE_TIMEOUT
}
} }
/** 提取靶样轮廓、绘制采样点并返回处理后的图像。 */ /** 提取靶样轮廓、绘制采样点并返回处理后的图像。 */
export function analyzeSample(): Promise<SampleAnalysisResult> { export function analyzeSample(
timeout = DEFAULT_ANALYZE_TIMEOUT,
): Promise<SampleAnalysisResult> {
return request<SampleAnalysisResult>( return request<SampleAnalysisResult>(
'/api/sample/analyze', '/api/sample/analyze',
{ method: 'POST' }, { method: 'POST' },
ANALYZE_TIMEOUT, timeout,
) )
} }
+1 -36
View File
@@ -1,21 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref } from 'vue'
import { connectCamera } from '@/api/camera' import { connectCamera } from '@/api/camera'
import { useCameraStatus } from '@/composables/useCameraStatus' import { useCameraStatus } from '@/composables/useCameraStatus'
import { useCameraStream } from '@/composables/useCameraStream' import { useCameraStream } from '@/composables/useCameraStream'
import cameraPlaceholder from '@/assets/camera-placeholder.webp' import cameraPlaceholder from '@/assets/camera-placeholder.webp'
const emit = defineEmits<{
/** 相机画面稳定显示后触发一次,用于采集基准画面。 */
ready: []
}>()
const { state: cameraState, refresh, startPolling } = useCameraStatus(5000, false) const { state: cameraState, refresh, startPolling } = useCameraStatus(5000, false)
const { state: streamState, frameUrl, isLive, connect } = useCameraStream() const { state: streamState, frameUrl, isLive, connect } = useCameraStream()
const connectingCamera = ref(false) const connectingCamera = ref(false)
const readyEmitted = ref(false)
let readyTimer: number | undefined
const statusText = computed(() => { const statusText = computed(() => {
if (isLive.value) return '实时画面' if (isLive.value) return '实时画面'
@@ -39,34 +32,6 @@ const statusTone = computed<'on' | 'wait' | 'off'>(() => {
return 'off' return 'off'
}) })
watch(isLive, (live) => {
if (readyTimer !== undefined) {
window.clearTimeout(readyTimer)
readyTimer = undefined
}
if (!live) {
readyEmitted.value = false
return
}
if (readyEmitted.value) return
// 画面连续显示 800ms 视为稳定,再通知外部采集基准画面
readyTimer = window.setTimeout(() => {
readyTimer = undefined
if (!isLive.value || readyEmitted.value) return
readyEmitted.value = true
emit('ready')
}, 800)
})
onBeforeUnmount(() => {
if (readyTimer !== undefined) {
window.clearTimeout(readyTimer)
}
})
onMounted(async () => { onMounted(async () => {
await refresh() await refresh()
File diff suppressed because it is too large Load Diff
+396
View File
@@ -0,0 +1,396 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import ReportDocument from '@/components/ReportDocument.vue'
import type { ScanRun } from '@/api/scan'
import { showToast } from '@/composables/useToast'
const props = withDefaults(
defineProps<{
open: boolean
run: ScanRun | null
imageUrl?: string
pointIndex?: number
}>(),
{ imageUrl: '', pointIndex: 0 },
)
const emit = defineEmits<{
close: []
}>()
const closeButton = ref<HTMLButtonElement | null>(null)
function pad2(value: number) {
return String(value).padStart(2, '0')
}
const reportNo = computed(() => {
const run = props.run
if (!run) return 'LIBS-00000000-000000'
const date = new Date(run.startedAt)
const stamp = Number.isNaN(date.getTime())
? '00000000'
: `${date.getFullYear()}${pad2(date.getMonth() + 1)}${pad2(date.getDate())}`
const tail =
run.scanId.replace(/[^a-zA-Z0-9]/g, '').slice(-6).toUpperCase() || '000000'
return `LIBS-${stamp}-${tail}`
})
function close() {
emit('close')
}
function exportPdf() {
if (!props.run) return
showToast('正在打开打印窗口,请选择“另存为 PDF”导出 A4 报告')
const previousTitle = document.title
document.title = `${reportNo.value} 检测报告`
const restoreTitle = () => {
document.title = previousTitle
window.removeEventListener('afterprint', restoreTitle)
}
window.addEventListener('afterprint', restoreTitle)
window.setTimeout(() => {
window.print()
window.setTimeout(restoreTitle, 4000)
}, 180)
}
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') close()
}
watch(
() => props.open,
async (open) => {
if (open) {
window.addEventListener('keydown', onKeydown)
await nextTick()
closeButton.value?.focus()
} else {
window.removeEventListener('keydown', onKeydown)
}
},
)
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown)
})
</script>
<template>
<Transition name="report-modal">
<div v-if="open" class="report-modal" role="dialog" aria-modal="true" aria-label="检测报告预览">
<div class="report-modal__backdrop" @click.self="close"></div>
<section class="report-modal__shell">
<header class="report-modal__bar">
<div class="report-modal__identity">
<span class="report-modal__badge" aria-hidden="true">
<svg viewBox="0 0 32 32">
<path
d="M8 4h11l6 6v18H8z"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linejoin="round"
/>
<path d="M19 4v6h6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" />
<path d="M12 16h9M12 20h9M12 24h6" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
</svg>
</span>
<div>
<h2>检测报告预览</h2>
<p>{{ reportNo }} · A4 210 × 297 mm · 共 3 页</p>
</div>
</div>
<div class="report-modal__actions">
<button
ref="closeButton"
class="report-modal__button report-modal__button--ghost"
type="button"
@click="close"
>
关闭
</button>
<button
class="report-modal__button report-modal__button--primary"
type="button"
:disabled="!run"
@click="exportPdf"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path
d="M12 4v10m0 0 3.5-3.5M12 14 8.5 10.5M5 16v2.5A1.5 1.5 0 0 0 6.5 20h11a1.5 1.5 0 0 0 1.5-1.5V16"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
导出 PDF
</button>
</div>
</header>
<div class="report-modal__scroll">
<ReportDocument
v-if="run"
:run="run"
:image-url="imageUrl"
:point-index="pointIndex"
preview
/>
<p v-else class="report-modal__empty">暂无可导出的检测结果</p>
</div>
<footer class="report-modal__foot">
<span class="report-modal__dot"></span>
点击“导出 PDF”后将打开系统打印窗口,请在“目标打印机”中选择“另存为 PDF”,纸张保持 A4。
</footer>
</section>
</div>
</Transition>
<Teleport to="body">
<div v-if="open && run" class="report-print-root">
<ReportDocument :run="run" :image-url="imageUrl" :point-index="pointIndex" />
</div>
</Teleport>
</template>
<style scoped>
.report-modal {
position: absolute;
inset: 0;
z-index: 70;
display: grid;
place-items: center;
}
.report-modal__backdrop {
position: absolute;
inset: 0;
background: rgba(3, 9, 20, 0.74);
backdrop-filter: blur(10px);
}
.report-modal__shell {
position: relative;
display: flex;
flex-direction: column;
width: 1300px;
height: 976px;
overflow: hidden;
border: 1px solid rgba(130, 175, 255, 0.26);
border-radius: 24px;
background: linear-gradient(158deg, #0e1e3a 0%, #081226 62%, #070f1f 100%);
box-shadow:
0 44px 120px rgba(0, 6, 20, 0.72),
0 0 70px rgba(48, 118, 255, 0.14),
inset 0 1px 0 rgba(255, 255, 255, 0.08);
}
.report-modal__bar {
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
height: 88px;
padding: 0 28px 0 30px;
border-bottom: 1px solid rgba(130, 175, 255, 0.14);
background: linear-gradient(120deg, rgba(30, 66, 128, 0.4) 0%, rgba(8, 18, 38, 0.2) 70%);
}
.report-modal__identity {
display: flex;
align-items: center;
gap: 16px;
}
.report-modal__badge {
display: grid;
place-items: center;
width: 52px;
height: 52px;
border: 1px solid rgba(130, 195, 255, 0.3);
border-radius: 14px;
background: rgba(30, 66, 128, 0.4);
color: #9fe8ff;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.12);
}
.report-modal__badge svg {
width: 28px;
height: 28px;
}
.report-modal__identity h2 {
color: #f0f7ff;
font-size: 26px;
font-weight: 600;
letter-spacing: 2px;
}
.report-modal__identity p {
margin-top: 4px;
color: rgba(158, 190, 226, 0.72);
font-size: 15px;
letter-spacing: 1px;
}
.report-modal__actions {
display: flex;
align-items: center;
gap: 16px;
}
.report-modal__button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 10px;
height: 56px;
border-radius: 12px;
font-size: 20px;
font-weight: 600;
letter-spacing: 3px;
transition:
transform 0.2s ease,
box-shadow 0.2s ease,
background 0.2s ease,
border-color 0.2s ease;
}
.report-modal__button:hover {
transform: translateY(-1px);
}
.report-modal__button svg {
width: 22px;
height: 22px;
}
.report-modal__button--ghost {
width: 132px;
border: 1px solid rgba(150, 200, 255, 0.32);
background: rgba(18, 40, 78, 0.4);
color: #cfe4ff;
letter-spacing: 4px;
}
.report-modal__button--ghost:hover {
border-color: rgba(160, 210, 255, 0.55);
background: rgba(30, 66, 128, 0.55);
}
.report-modal__button--primary {
width: 194px;
background: linear-gradient(180deg, #ffd166 0%, #f0ac0b 100%);
color: #241500;
box-shadow:
0 14px 30px rgba(240, 172, 11, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.6);
}
.report-modal__button--primary:hover {
box-shadow:
0 18px 38px rgba(240, 172, 11, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.6);
}
.report-modal__button--primary:disabled {
cursor: not-allowed;
opacity: 0.5;
transform: none;
}
.report-modal__scroll {
position: relative;
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
min-height: 0;
padding: 30px 0 40px;
overflow-y: auto;
background:
radial-gradient(760px 420px at 50% -8%, rgba(48, 118, 255, 0.16), transparent 70%),
radial-gradient(600px 400px at 88% 100%, rgba(42, 183, 172, 0.08), transparent 70%),
#091325;
scrollbar-width: thin;
scrollbar-color: rgba(130, 175, 255, 0.32) transparent;
}
.report-modal__scroll::-webkit-scrollbar {
width: 10px;
}
.report-modal__scroll::-webkit-scrollbar-thumb {
border: 3px solid #091325;
border-radius: 6px;
background: rgba(130, 175, 255, 0.36);
}
.report-modal__scroll::-webkit-scrollbar-track {
background: transparent;
}
.report-modal__empty {
margin-top: 200px;
color: rgba(158, 190, 226, 0.7);
font-size: 20px;
letter-spacing: 2px;
}
.report-modal__foot {
display: flex;
flex: none;
align-items: center;
gap: 10px;
height: 46px;
padding: 0 30px;
border-top: 1px solid rgba(130, 175, 255, 0.12);
background: rgba(8, 18, 38, 0.75);
color: rgba(158, 190, 226, 0.66);
font-size: 15px;
letter-spacing: 0.6px;
}
.report-modal__dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #8df6ff;
box-shadow: 0 0 10px rgba(141, 246, 255, 0.8);
}
.report-modal-enter-active,
.report-modal-leave-active {
transition: opacity 0.26s ease;
}
.report-modal-enter-active .report-modal__shell,
.report-modal-leave-active .report-modal__shell {
transition:
transform 0.28s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.26s ease;
}
.report-modal-enter-from,
.report-modal-leave-to {
opacity: 0;
}
.report-modal-enter-from .report-modal__shell,
.report-modal-leave-to .report-modal__shell {
opacity: 0;
transform: translateY(18px) scale(0.975);
}
</style>
+1 -1
View File
@@ -170,7 +170,7 @@ const markers = [
text-anchor="middle" text-anchor="middle"
opacity="0.95" opacity="0.95"
> >
样品图片识别动画 样品图片识别中...
</text> </text>
<text <text
x="500" x="500"
@@ -5,6 +5,7 @@ export function useCountdown(
seconds: number, seconds: number,
onComplete: () => void, onComplete: () => void,
enabled = true, enabled = true,
isPaused: () => boolean = () => false,
) { ) {
const remaining = ref(seconds) const remaining = ref(seconds)
@@ -15,6 +16,8 @@ export function useCountdown(
if (!enabled) return if (!enabled) return
timer = window.setInterval(() => { timer = window.setInterval(() => {
if (isPaused()) return
remaining.value = Math.max(0, remaining.value - 1) remaining.value = Math.max(0, remaining.value - 1)
if (remaining.value === 0 && !finished) { if (remaining.value === 0 && !finished) {
+32
View File
@@ -179,6 +179,38 @@ ol {
transform: translateY(-6px); 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) { @media (prefers-reduced-motion: reduce) {
*, *,
*::before, *::before,
+22 -2
View File
@@ -3,6 +3,7 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue' import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue' import PageHeader from '@/components/PageHeader.vue'
import ReportModal from '@/components/ReportModal.vue'
import SpectrumChart from '@/components/SpectrumChart.vue' import SpectrumChart from '@/components/SpectrumChart.vue'
import { getLatestScan, getScan, type ScanRun } from '@/api/scan' import { getLatestScan, getScan, type ScanRun } from '@/api/scan'
import { useCountdown } from '@/composables/useCountdown' import { useCountdown } from '@/composables/useCountdown'
@@ -18,6 +19,7 @@ const run = ref<ScanRun | null>(null)
const loading = ref(true) const loading = ref(true)
const loadError = ref('') const loadError = ref('')
const selectedIndex = ref(0) const selectedIndex = ref(0)
const reportOpen = ref(false)
const viewport = ref<HTMLElement | null>(null) const viewport = ref<HTMLElement | null>(null)
const imageWidth = ref(0) const imageWidth = ref(0)
@@ -34,7 +36,12 @@ function goHistory() {
void router.replace({ name: 'history' }) void router.replace({ name: 'history' })
} }
const { remaining } = useCountdown(60, goHome, !isHistoryMode) const { remaining } = useCountdown(
60,
goHome,
!isHistoryMode,
() => reportOpen.value,
)
const targetScanId = computed(() => { const targetScanId = computed(() => {
const raw = isHistoryMode ? route.params.scanId : route.query.scanId const raw = isHistoryMode ? route.params.scanId : route.query.scanId
@@ -159,7 +166,12 @@ async function loadResult() {
} }
function exportReport() { function exportReport() {
showToast('报告导出功能正在研发中') if (!run.value) {
showToast('暂无可导出的检测结果')
return
}
reportOpen.value = true
} }
onMounted(async () => { onMounted(async () => {
@@ -377,6 +389,14 @@ onBeforeUnmount(() => {
</button> </button>
</div> </div>
</div> </div>
<ReportModal
:open="reportOpen"
:run="run"
:image-url="imageUrl"
:point-index="selectedIndex"
@close="reportOpen = false"
/>
</AppStage> </AppStage>
</template> </template>
+11 -102
View File
@@ -1,19 +1,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue' import { ref } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import AppStage from '@/components/AppStage.vue' import AppStage from '@/components/AppStage.vue'
import PageHeader from '@/components/PageHeader.vue' import PageHeader from '@/components/PageHeader.vue'
import CameraPreview from '@/components/CameraPreview.vue' import CameraPreview from '@/components/CameraPreview.vue'
import GuideIcon from '@/components/GuideIcon.vue' import GuideIcon from '@/components/GuideIcon.vue'
import StatusFooter from '@/components/StatusFooter.vue' import StatusFooter from '@/components/StatusFooter.vue'
import { captureSampleBaseline, captureSampleTarget } from '@/api/sample'
import { showToast } from '@/composables/useToast' import { showToast } from '@/composables/useToast'
const router = useRouter() const router = useRouter()
const baselineReady = ref(false)
const capturingBaseline = ref(false)
const starting = ref(false)
const requirementsConfirmed = ref(false) const requirementsConfirmed = ref(false)
const steps = [ const steps = [
@@ -28,66 +24,19 @@ const placementRequirements = [
'样品高度不能超过 2 厘米', '样品高度不能超过 2 厘米',
] ]
const footerItems = computed(() => [ const footerItems = ['等待开始检测', '激光安全等级 Class 1', '环境温度 22℃']
baselineReady.value
? '基准画面已采集'
: capturingBaseline.value
? '正在采集基准画面'
: '等待相机画面稳定',
'激光安全等级 Class 1',
'环境温度 22℃',
])
const captureStatusText = computed(() => {
if (baselineReady.value) return '基准画面就绪'
if (capturingBaseline.value) return '正在采集基准画面'
return '等待相机画面'
})
function goHome() { function goHome() {
void router.push({ name: 'home' }) void router.push({ name: 'home' })
} }
async function onCameraReady() { function startDetection() {
if (baselineReady.value || capturingBaseline.value) return
capturingBaseline.value = true
try {
await captureSampleBaseline()
baselineReady.value = true
} catch (error) {
showToast(
error instanceof Error
? `基准画面采集失败:${error.message}`
: '基准画面采集失败',
)
} finally {
capturingBaseline.value = false
}
}
async function startDetection() {
if (starting.value) return
if (!requirementsConfirmed.value) { if (!requirementsConfirmed.value) {
showToast('请先确认样品放置符合要求') showToast('请先确认样品放置符合要求')
return return
} }
if (!baselineReady.value) { void router.push({ name: 'scan' })
showToast('基准画面尚未采集完成,请稍候再试')
return
}
starting.value = true
try {
await captureSampleTarget()
void router.push({ name: 'scan' })
} catch (error) {
showToast(error instanceof Error ? error.message : '靶样画面采集失败')
} finally {
starting.value = false
}
} }
</script> </script>
@@ -108,7 +57,7 @@ async function startDetection() {
</PageHeader> </PageHeader>
<main class="sample-main"> <main class="sample-main">
<CameraPreview class="sample-camera" @ready="onCameraReady" /> <CameraPreview class="sample-camera" />
<aside class="guide-column"> <aside class="guide-column">
<section class="guide-card"> <section class="guide-card">
@@ -158,19 +107,14 @@ async function startDetection() {
</section> </section>
<div class="guide-actions"> <div class="guide-actions">
<span class="capture-status" :class="{ 'is-ready': baselineReady }">
<i class="capture-status__dot"></i>
{{ captureStatusText }}
</span>
<button <button
class="action-button action-button--start" class="action-button action-button--start"
type="button" type="button"
:disabled="starting || !requirementsConfirmed" :disabled="!requirementsConfirmed"
:title="requirementsConfirmed ? undefined : '请先确认样品放置符合要求'" :title="requirementsConfirmed ? undefined : '请先确认样品放置符合要求'"
@click="startDetection" @click="startDetection"
> >
{{ starting ? '准备中...' : '开始检测' }} 开始检测
</button> </button>
</div> </div>
</aside> </aside>
@@ -524,52 +468,17 @@ async function startDetection() {
} }
.guide-actions { .guide-actions {
display: grid;
flex: none;
grid-template-columns: minmax(0, 1fr) 320px;
align-items: center;
gap: 18px;
height: 78px;
}
.capture-status {
display: flex; 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; flex: none;
width: 9px; justify-content: flex-end;
height: 9px; align-items: center;
border-radius: 50%; height: 78px;
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);
} }
.action-button { .action-button {
display: grid; display: grid;
place-items: center; place-items: center;
width: 320px;
height: 78px; height: 78px;
border-radius: 14px; border-radius: 14px;
font-size: 30px; font-size: 30px;
+41 -14
View File
@@ -6,7 +6,7 @@ import PageHeader from '@/components/PageHeader.vue'
import ScanVisual from '@/components/ScanVisual.vue' import ScanVisual from '@/components/ScanVisual.vue'
import ProgressStrip from '@/components/ProgressStrip.vue' import ProgressStrip from '@/components/ProgressStrip.vue'
import StatusFooter from '@/components/StatusFooter.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 { startScan } from '@/api/scan'
import { useStageHub } from '@/composables/useStageHub' import { useStageHub } from '@/composables/useStageHub'
import { showToast } from '@/composables/useToast' import { showToast } from '@/composables/useToast'
@@ -23,7 +23,11 @@ const scanStarting = ref(false)
const { position: stagePosition, connect: connectStageHub } = useStageHub() 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(() => const resultImageUrl = computed(() =>
result.value result.value
@@ -74,38 +78,61 @@ const footerItems = computed(() => {
}) })
function stopProgress() { function stopProgress() {
if (progressTimer !== undefined) { if (progressFrame !== undefined) {
window.clearInterval(progressTimer) window.cancelAnimationFrame(progressFrame)
progressTimer = undefined progressFrame = undefined
} }
} }
function startProgress() { /**
* 按真实耗时推进进度:在预估的分析时长内匀速走到 99%,
* 超过预估时长后继续缓慢爬升,分析结束后再置为 100%,
* 避免像以往那样提前卡在固定百分比上空等。
*/
function startProgress(durationMs: number) {
stopProgress() stopProgress()
progress.value = 0 progress.value = 0
progressTimer = window.setInterval(() => { const total = Math.max(1000, durationMs)
if (progress.value >= 90) return const startedAt = performance.now()
progress.value = Math.min(90, progress.value + (progress.value < 60 ? 4 : 1.5))
}, 120) 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() { async function runAnalysis() {
status.value = 'processing' status.value = 'processing'
result.value = null result.value = null
errorMessage.value = '' errorMessage.value = ''
startProgress() progress.value = 0
try { 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 progress.value = 100
status.value = 'done' status.value = 'done'
} catch (error) { } catch (error) {
stopProgress()
status.value = 'error' status.value = 'error'
errorMessage.value = errorMessage.value =
error instanceof Error ? error.message : '靶样轮廓分析失败' error instanceof Error ? error.message : '靶样轮廓分析失败'
} finally {
stopProgress()
} }
} }
@@ -4,6 +4,11 @@
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<!--
DirectML 的 build targets 仅在 PlatformTarget=x64 时复制 DirectML.dll,
AnyCPU 会导致运行时缺少该原生库而退回 CPU,因此这里固定为 x64。
-->
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -11,7 +16,12 @@
<PackageReference Include="LiteDB" Version="5.0.21" /> <PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" /> <PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.20.1" /> <!--
DirectML 版 ONNX Runtime:可用核显/独显推理,不支持的算子自动回退 CPU。
注意:该包与纯 CPU 版 Microsoft.ML.OnnxRuntime 的原生 dll 冲突,只能二选一;
1.24.4 是最后一个提供 DirectML 执行后端的稳定版本。
-->
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.24.4" />
<PackageReference Include="OpenCvSharp4" Version="4.10.0.20241108" /> <PackageReference Include="OpenCvSharp4" Version="4.10.0.20241108" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.10.0.20241108" /> <PackageReference Include="OpenCvSharp4.runtime.win" Version="4.10.0.20241108" />
</ItemGroup> </ItemGroup>
@@ -3,19 +3,23 @@ using HardwareControl.Core.SampleAnalysis;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{ {
/// <summary> /// <summary>
/// 靶样轮廓与采样点分析服务:基准画面、靶样画面采集与分析。 /// 靶样轮廓与采样点分析服务:抓取相机当前画面并分析。
/// </summary> /// </summary>
public interface ISampleAnalysisService public interface ISampleAnalysisService
{ {
/// <summary>连续抓取多帧并取中值作为基准背景画面。</summary> /// <summary>抓取相机当前画面,提取轮廓并生成采样点。</summary>
Task<SampleBaselineInfo> CaptureBaselineAsync(CancellationToken ct = default); SampleAnalysisResult Analyze();
/// <summary> /// <summary>
/// 关闭红外测距光源后抓取当前最新画面作为靶样画面(需先采集基准画面)。 /// 获取最近一次轮廓分析结果供扫描流程复用;
/// 尚未分析过时立即执行一次分析。
/// </summary> /// </summary>
Task<SampleTargetInfo> CaptureTargetAsync(CancellationToken ct = default); SampleAnalysisResult GetLatestAnalysis();
/// <summary>基于基准画面和靶样画面提取轮廓并生成采样点。</summary> /// <summary>
SampleAnalysisResult Analyze(); /// 前端等待轮廓识别结果的超时时间(秒),
/// 取自系统参数 camera_Identification_outtime。
/// </summary>
int GetIdentificationTimeoutSeconds();
} }
} }
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.SampleAnalysis; using HardwareControl.Core.SampleAnalysis;
@@ -8,16 +9,20 @@ using Microsoft.Extensions.Logging;
namespace HardwareControl.Core.HardwareServiceImpl namespace HardwareControl.Core.HardwareServiceImpl
{ {
/// <summary> /// <summary>
/// 采集基准画面 / 靶样画面并调用 ONNX 模型分析。 /// 抓取相机当前画面并调用 ONNX 模型分析。
/// 作为单例使用,保存本次检测的画面。 /// 作为单例使用,保存最近一次分析结果供扫描流程复用。
/// </summary> /// </summary>
public sealed class SampleAnalysisService : ISampleAnalysisService public sealed class SampleAnalysisService : ISampleAnalysisService
{ {
private const string SamplingPointConfigName = "camera_sampling_point"; private const string SamplingPointConfigName = "camera_sampling_point";
private const string SamplingRadiusConfigName = "camera_sampling_radius"; private const string SamplingRadiusConfigName = "camera_sampling_radius";
private const string CameraScaleConfigName = "camera_scale"; private const string CameraScaleConfigName = "camera_scale";
private const string IdentificationTimeoutConfigName = "camera_Identification_outtime";
private const int DefaultSamplingPointCount = 5; private const int DefaultSamplingPointCount = 5;
private const int MaxSamplingPointCount = 100; 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 IUsbCameraService _camera;
private readonly ISystemConfigService _systemConfig; private readonly ISystemConfigService _systemConfig;
@@ -25,8 +30,6 @@ namespace HardwareControl.Core.HardwareServiceImpl
private readonly ILogger<SampleAnalysisService> _logger; private readonly ILogger<SampleAnalysisService> _logger;
private readonly object _gate = new(); private readonly object _gate = new();
private IReadOnlyList<CameraFrameSnapshot>? _baseline;
private CameraFrameSnapshot? _target;
private SampleAnalysisResult? _lastAnalysis; private SampleAnalysisResult? _lastAnalysis;
public SampleAnalysisService( public SampleAnalysisService(
@@ -41,75 +44,9 @@ namespace HardwareControl.Core.HardwareServiceImpl
_logger = logger; _logger = logger;
} }
public Task<SampleBaselineInfo> 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<SampleTargetInfo> 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() public SampleAnalysisResult Analyze()
{ {
IReadOnlyList<CameraFrameSnapshot> baseline; var target = CaptureLatestFrame();
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 pointCount = GetSamplingPointCount(); var pointCount = GetSamplingPointCount();
var samplingRadiusPixels = GetSamplingRadiusPixels(); var samplingRadiusPixels = GetSamplingRadiusPixels();
@@ -121,32 +58,83 @@ namespace HardwareControl.Core.HardwareServiceImpl
? $"{samplingRadiusPixels.Value:F1}px" ? $"{samplingRadiusPixels.Value:F1}px"
: "不限制"); : "不限制");
var watch = Stopwatch.StartNew();
var result = _analyzer.Analyze( var result = _analyzer.Analyze(
baseline, target, pointCount, samplingRadiusPixels); target, pointCount, samplingRadiusPixels);
watch.Stop();
_logger.LogInformation( _logger.LogInformation(
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个", "靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个,总耗时 {Elapsed} ms",
result.Width, result.Width,
result.Height, result.Height,
result.SamplingPointCount); result.SamplingPointCount,
watch.ElapsedMilliseconds);
lock (_gate) lock (_gate)
{ {
// 分析期间如果靶样画面已被重新采集,则不缓存本次结果。 _lastAnalysis = result;
if (ReferenceEquals(_target, target))
{
_lastAnalysis = result;
}
} }
return result; return result;
} }
public SampleAnalysisResult GetLatestAnalysis()
{
lock (_gate)
{
if (_lastAnalysis is not null)
{
return _lastAnalysis;
}
}
return Analyze();
}
private CameraFrameSnapshot CaptureLatestFrame() => private CameraFrameSnapshot CaptureLatestFrame() =>
_camera.GetLatestFrame() ?? throw new HardwareException( _camera.GetLatestFrame() ?? throw new HardwareException(
HardwareErrorKind.NotConnected, HardwareErrorKind.NotConnected,
"相机尚未产生画面,请确认相机已连接"); "相机尚未产生画面,请确认相机已连接");
/// <summary>
/// 读取系统参数 camera_Identification_outtime(秒),
/// 作为前端等待轮廓识别结果的超时时间;未配置或无效时使用默认值。
/// </summary>
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() private int GetSamplingPointCount()
{ {
try try
@@ -1,283 +0,0 @@
using HardwareControl.Core.UsbCamera;
using OpenCvSharp;
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>
/// 基于基准帧与靶样帧的 OpenCV 背景差分分割。
/// 用于 ONNX 模型置信度不足或没有输出时兜底。
/// 流程:Lab + CLAHE → 颜色/梯度双差分 → 均值+2σ阈值
/// → 闭运算 + 轮廓填充 → GrabCut 细化。
/// </summary>
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;
}
/// <summary>Lab 色彩空间 + CLAHE 亮度归一化。</summary>
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();
}
}
}
/// <summary>Lab 三通道绝对差加权,保留低对比度颜色差异。</summary>
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();
}
}
}
/// <summary>梯度幅值差分,对低对比度物体边缘更敏感。</summary>
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;
}
/// <summary>
/// 使用均值 + 2σ 阈值,并对闭合边缘做内部填充,
/// 避免低对比度靶样只留下边缘、内部为空。
/// </summary>
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;
}
/// <summary>用差分掩膜初始化 GrabCut,让边界更贴合物品真实边缘。</summary>
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;
}
}
}
@@ -0,0 +1,170 @@
using System.Runtime.InteropServices;
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>
/// 通过 DXGI 枚举本机显卡适配器,用于区分独立显卡与核心显卡。
/// DirectML 执行后端的 device_id 就是 DXGI 适配器序号,因此这里返回的
/// <see cref="GpuAdapter.Index"/> 可直接传给 AppendExecutionProvider_DML。
/// </summary>
internal static class GpuAdapterEnumerator
{
/// <summary>独立显卡的专用显存下限,低于该值视为核显。</summary>
private const ulong DiscreteMemoryThreshold = 1024UL * 1024 * 1024;
private const uint AdapterFlagSoftware = 0x2;
/// <summary>IDXGIFactory1::EnumAdapters1 在虚表中的槽位。</summary>
private const int EnumAdapters1VtableIndex = 12;
/// <summary>IDXGIAdapter1::GetDesc1 在虚表中的槽位。</summary>
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;
}
/// <summary>
/// 按硬件使用类型解析可用的显卡适配器。
/// 指定类型的显卡不存在时退回另一类显卡,完全没有可用显卡时返回 false。
/// </summary>
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;
}
/// <summary>枚举全部 DXGI 适配器(包含软件适配器),失败时返回空列表。</summary>
public static IReadOnlyList<GpuAdapter> Enumerate()
{
var adapters = new List<GpuAdapter>();
IntPtr factory = IntPtr.Zero;
try
{
var factoryId = IID_IDXGIFactory1;
if (CreateDXGIFactory1(ref factoryId, out factory) < 0 ||
factory == IntPtr.Zero)
{
return adapters;
}
var enumAdapters1 = GetVtableDelegate<EnumAdapters1Delegate>(
factory, EnumAdapters1VtableIndex);
for (uint index = 0; ; index++)
{
if (enumAdapters1(factory, index, out var adapter) < 0 ||
adapter == IntPtr.Zero)
{
break;
}
try
{
var getDesc1 = GetVtableDelegate<GetDesc1Delegate>(
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<T>(IntPtr instance, int vtableIndex)
where T : Delegate
{
var vtable = Marshal.ReadIntPtr(instance);
var method = Marshal.ReadIntPtr(vtable, vtableIndex * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(method);
}
}
}
@@ -1,5 +1,18 @@
namespace HardwareControl.Core.SampleAnalysis namespace HardwareControl.Core.SampleAnalysis
{ {
/// <summary>硬件使用类型,对应系统参数 hardware_usage_type。</summary>
public enum HardwareUsageType
{
/// <summary>仅使用 CPU。</summary>
Cpu = 1,
/// <summary>使用独立显卡(DirectML)。</summary>
DiscreteGpu = 2,
/// <summary>使用核心显卡(DirectML)。</summary>
IntegratedGpu = 3,
}
/// <summary>靶样 ONNX 分割模型配置。</summary> /// <summary>靶样 ONNX 分割模型配置。</summary>
public sealed class OnnxSegmentationOptions public sealed class OnnxSegmentationOptions
{ {
@@ -18,11 +31,20 @@ namespace HardwareControl.Core.SampleAnalysis
public int InputHeight { get; set; } = 640; public int InputHeight { get; set; } = 640;
/// <summary>
/// 推理执行后端:Auto(优先 DirectML,不可用时回退 CPU)、DirectML、Cpu。
/// DirectML 可调用核显/独显,同时保留 CPU 算子回退。
/// </summary>
public string ExecutionProvider { get; set; } = "Auto";
/// <summary>DirectML 设备序号,0 表示系统默认适配器。</summary>
public int DmlDeviceId { get; set; }
/// <summary>YOLO 分割模型的目标置信度阈值。</summary> /// <summary>YOLO 分割模型的目标置信度阈值。</summary>
public double ConfidenceThreshold { get; set; } = 0.25; public double ConfidenceThreshold { get; set; } = 0.25;
/// <summary> /// <summary>
/// 模型置信度低于该值时,使用 OpenCV 背景差分兜底识别轮廓。 /// 模型置信度低于该值时,继续尝试后续模型,取置信度最高的结果。
/// </summary> /// </summary>
public double FallbackConfidenceThreshold { get; set; } = 0.6; public double FallbackConfidenceThreshold { get; set; } = 0.6;
@@ -1,17 +1,5 @@
namespace HardwareControl.Core.SampleAnalysis namespace HardwareControl.Core.SampleAnalysis
{ {
/// <summary>基准画面信息(放置靶样前)。</summary>
public sealed record SampleBaselineInfo(
int Width,
int Height,
DateTimeOffset CapturedAt);
/// <summary>靶样画面信息(放置靶样后)。</summary>
public sealed record SampleTargetInfo(
int Width,
int Height,
DateTimeOffset CapturedAt);
/// <summary>图像坐标系下的采样点。</summary> /// <summary>图像坐标系下的采样点。</summary>
public sealed record SamplePoint(int X, int Y); public sealed record SamplePoint(int X, int Y);
@@ -1,5 +1,7 @@
using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.UsbCamera; using HardwareControl.Core.UsbCamera;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -12,34 +14,43 @@ namespace HardwareControl.Core.SampleAnalysis
/// <summary> /// <summary>
/// 基于多个 ONNX 模型的靶样分割与采样点规划。 /// 基于多个 ONNX 模型的靶样分割与采样点规划。
/// 模型目录内按文件名前面的数字从小到大依次尝试; /// 模型目录内按文件名前面的数字从小到大依次尝试;
/// 模型置信度不足或没有输出时,使用 OpenCV 背景差分兜底。 /// 模型置信度不足或没有输出时继续尝试后续模型。
/// 支持检测框、YOLO 分割、检测+掩膜、二值/语义分割输出。 /// 支持检测框、YOLO 分割、检测+掩膜、二值/语义分割输出。
/// </summary> /// </summary>
public sealed class TargetOutlineAnalyzer : IDisposable public sealed class TargetOutlineAnalyzer : IDisposable
{ {
private const string HardwareUsageTypeConfigName = "hardware_usage_type";
private readonly OnnxSegmentationOptions _options; private readonly OnnxSegmentationOptions _options;
private readonly ILogger<TargetOutlineAnalyzer> _logger; private readonly ILogger<TargetOutlineAnalyzer> _logger;
private readonly BackgroundDiffSegmenter _backgroundDiff; private readonly ISystemConfigService _systemConfig;
private readonly object _gate = new(); private readonly object _gate = new();
private readonly Dictionary<string, InferenceSession> _sessions = private readonly Dictionary<string, InferenceSession> _sessions =
new(StringComparer.OrdinalIgnoreCase); new(StringComparer.OrdinalIgnoreCase);
private ProviderSelection _provider;
private bool _providerApplied;
public TargetOutlineAnalyzer( public TargetOutlineAnalyzer(
IOptions<OnnxSegmentationOptions> options, IOptions<OnnxSegmentationOptions> options,
BackgroundDiffSegmenter backgroundDiff, ISystemConfigService systemConfig,
ILogger<TargetOutlineAnalyzer> logger) ILogger<TargetOutlineAnalyzer> logger)
{ {
_options = options.Value; _options = options.Value;
_backgroundDiff = backgroundDiff; _systemConfig = systemConfig;
_logger = logger; _logger = logger;
_provider = ResolveProviderFromOptions();
} }
/// <summary>当前生效的推理后端;<see cref="ProviderSelection.Label"/> 用于日志。</summary>
private readonly record struct ProviderSelection(
bool UseDirectMl, int DeviceId, string Label);
private int InputWidth => Math.Max(32, _options.InputWidth); private int InputWidth => Math.Max(32, _options.InputWidth);
private int InputHeight => Math.Max(32, _options.InputHeight); private int InputHeight => Math.Max(32, _options.InputHeight);
public SampleAnalysisResult Analyze( public SampleAnalysisResult Analyze(
IReadOnlyList<CameraFrameSnapshot> baselineFrames,
CameraFrameSnapshot target, CameraFrameSnapshot target,
int samplingPointCount, int samplingPointCount,
double? samplingRadiusPixels = null) double? samplingRadiusPixels = null)
@@ -52,6 +63,8 @@ namespace HardwareControl.Core.SampleAnalysis
lock (_gate) lock (_gate)
{ {
ApplyHardwareUsageType();
var models = ResolveModelFiles(); var models = ResolveModelFiles();
CleanupSessions(models); CleanupSessions(models);
@@ -67,6 +80,7 @@ namespace HardwareControl.Core.SampleAnalysis
foreach (var modelPath in models) foreach (var modelPath in models)
{ {
var modelName = Path.GetFileName(modelPath); var modelName = Path.GetFileName(modelPath);
var modelWatch = Stopwatch.StartNew();
try try
{ {
var result = TryAnalyzeWithModel( var result = TryAnalyzeWithModel(
@@ -77,6 +91,12 @@ namespace HardwareControl.Core.SampleAnalysis
out var confidence, out var confidence,
out var failureReason); out var failureReason);
modelWatch.Stop();
_logger.LogInformation(
"模型 {Model} 分析耗时 {Elapsed} ms",
modelName,
modelWatch.ElapsedMilliseconds);
if (result is not null) if (result is not null)
{ {
if (confidence >= _options.FallbackConfidenceThreshold) if (confidence >= _options.FallbackConfidenceThreshold)
@@ -100,7 +120,7 @@ namespace HardwareControl.Core.SampleAnalysis
$"{_options.FallbackConfidenceThreshold:F2}"); $"{_options.FallbackConfidenceThreshold:F2}");
_logger.LogInformation( _logger.LogInformation(
"模型 {Model} 置信度 {Confidence:F2} 较低," + "模型 {Model} 置信度 {Confidence:F2} 较低," +
"继续尝试后续模型或使用 OpenCV 兜底", "继续尝试后续模型",
modelName, modelName,
confidence); confidence);
continue; 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) if (lowConfidenceResult is not null)
{ {
_logger.LogWarning( _logger.LogWarning(
"OpenCV 兜底失败,返回置信度较低的模型结果:{Model}({Confidence:F2})", "没有更高置信度的模型结果,返回置信度较低的模型结果:{Model}({Confidence:F2})",
lowConfidenceModel, lowConfidenceModel,
lowConfidence); lowConfidence);
return lowConfidenceResult; return lowConfidenceResult;
@@ -186,12 +159,46 @@ namespace HardwareControl.Core.SampleAnalysis
{ {
lock (_gate) lock (_gate)
{ {
foreach (var session in _sessions.Values) DisposeSessions();
}
}
private void DisposeSessions()
{
foreach (var session in _sessions.Values)
{
session.Dispose();
}
_sessions.Clear();
}
/// <summary>
/// 预加载首个 ONNX 模型。大模型(数百 MB)首次加载往往需要数十秒,
/// 在程序启动后放到后台执行,可避免用户点击检测时才等待模型加载。
/// </summary>
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( var inputValue = CreateInputValue(
input.Key, letterboxed, inputWidth, inputHeight); input.Key, letterboxed, inputWidth, inputHeight);
var inferenceWatch = Stopwatch.StartNew();
using var results = session.Run(new[] { inputValue }); 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<OutputTensor>(); var outputs = new List<OutputTensor>();
foreach (var result in results) foreach (var result in results)
@@ -314,13 +329,15 @@ namespace HardwareControl.Core.SampleAnalysis
lineThickness, lineThickness,
LineTypes.AntiAlias); LineTypes.AntiAlias);
using var distanceMap = BuildDistanceMap(mask);
var points = BuildSamplingPoints( var points = BuildSamplingPoints(
contour, contour,
pointCount, pointCount,
CalculateSamplingMargin(contour, outputImage.Width, outputImage.Height), CalculateSamplingMargin(contour, outputImage.Width, outputImage.Height),
samplingRadiusPixels, samplingRadiusPixels,
outputImage.Width / 2.0, outputImage.Width / 2.0,
outputImage.Height / 2.0); outputImage.Height / 2.0,
distanceMap);
DrawSamplingPoints(outputImage, points, lineThickness); DrawSamplingPoints(outputImage, points, lineThickness);
Cv2.ImEncode( Cv2.ImEncode(
@@ -421,15 +438,14 @@ namespace HardwareControl.Core.SampleAnalysis
try try
{ {
var options = new SessionOptions using var options = CreateSessionOptions(out var providerName);
{
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
var session = new InferenceSession(modelPath, options); var session = new InferenceSession(modelPath, options);
_sessions[modelPath] = session; _sessions[modelPath] = session;
_logger.LogInformation( _logger.LogInformation(
"ONNX Runtime 模型已加载:{Model}", Path.GetFileName(modelPath)); "ONNX Runtime 模型已加载:{Model},执行后端:{Provider}",
Path.GetFileName(modelPath),
providerName);
return session; return session;
} }
catch (Exception ex) catch (Exception ex)
@@ -441,6 +457,139 @@ namespace HardwareControl.Core.SampleAnalysis
} }
} }
/// <summary>
/// 读取系统参数 hardware_usage_type,与当前生效配置不同时重建会话,
/// 使运行中修改该参数后下一次分析即可切换推理后端。
/// </summary>
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;
}
/// <summary>
/// 按当前硬件模式创建会话选项:DirectML 不支持的算子由 ONNX Runtime 自动回退到 CPU。
/// </summary>
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<string> currentModels) private void CleanupSessions(IReadOnlyCollection<string> currentModels)
{ {
var current = new HashSet<string>(currentModels, StringComparer.OrdinalIgnoreCase); var current = new HashSet<string>(currentModels, StringComparer.OrdinalIgnoreCase);
@@ -1243,6 +1392,18 @@ namespace HardwareControl.Core.SampleAnalysis
return Math.Max(markerRadius + 4, ratioMargin); return Math.Max(markerRadius + 4, ratioMargin);
} }
/// <summary>
/// 计算掩膜内每个像素到最近边界的距离,供采样点校验一次查表完成,
/// 避免在重试缩放间距时反复对整条轮廓做 PointPolygonTest。
/// </summary>
private static Mat BuildDistanceMap(Mat mask)
{
var distanceMap = new Mat();
Cv2.DistanceTransform(
mask, distanceMap, DistanceTypes.L2, DistanceTransformMasks.Mask5);
return distanceMap;
}
/// <summary> /// <summary>
/// 在轮廓内部按网格生成候选点,要求候选点到轮廓的距离不小于安全边距; /// 在轮廓内部按网格生成候选点,要求候选点到轮廓的距离不小于安全边距;
/// 配置采样半径时,候选点还须位于以画面中心为原点的半径范围内。 /// 配置采样半径时,候选点还须位于以画面中心为原点的半径范围内。
@@ -1254,7 +1415,8 @@ namespace HardwareControl.Core.SampleAnalysis
double margin, double margin,
double? radiusPixels, double? radiusPixels,
double centerX, double centerX,
double centerY) double centerY,
Mat distanceMap)
{ {
var area = Cv2.ContourArea(contour); var area = Cv2.ContourArea(contour);
if (area <= 0 || count <= 0) if (area <= 0 || count <= 0)
@@ -1285,9 +1447,7 @@ namespace HardwareControl.Core.SampleAnalysis
continue; continue;
} }
var distance = Cv2.PointPolygonTest( if (distanceMap.At<float>(point.Y, point.X) >= margin)
contour, new Point2f(point.X, point.Y), true);
if (distance >= margin)
{ {
candidates.Add(point); candidates.Add(point);
} }
@@ -1306,7 +1466,7 @@ namespace HardwareControl.Core.SampleAnalysis
{ {
// 极窄轮廓可能无法满足安全边距,退回到离边缘最远的内部点 // 极窄轮廓可能无法满足安全边距,退回到离边缘最远的内部点
var fallback = FindBestInteriorPoint( var fallback = FindBestInteriorPoint(
contour, radiusPixels, centerX, centerY); contour, radiusPixels, centerX, centerY, distanceMap);
return fallback.HasValue return fallback.HasValue
? new List<Point> { fallback.Value } ? new List<Point> { fallback.Value }
: new List<Point>(); : new List<Point>();
@@ -1353,7 +1513,11 @@ namespace HardwareControl.Core.SampleAnalysis
/// <summary>找到轮廓内部距边缘最远的点,作为极端情况下的兜底。</summary> /// <summary>找到轮廓内部距边缘最远的点,作为极端情况下的兜底。</summary>
private static Point? FindBestInteriorPoint( 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 rect = Cv2.BoundingRect(contour);
var step = Math.Max(2, Math.Min(rect.Width, rect.Height) / 50); var step = Math.Max(2, Math.Min(rect.Width, rect.Height) / 50);
@@ -1370,8 +1534,7 @@ namespace HardwareControl.Core.SampleAnalysis
continue; continue;
} }
var distance = Cv2.PointPolygonTest( var distance = distanceMap.At<float>(y, x);
contour, new Point2f(x, y), true);
if (distance > bestDistance) if (distance > bestDistance)
{ {
@@ -127,7 +127,7 @@ namespace HardwareControl.Core.Scanning
await _spectrometer.ConnectAsync(ct); await _spectrometer.ConnectAsync(ct);
} }
var sample = _sampleAnalysis.Analyze(); var sample = _sampleAnalysis.GetLatestAnalysis();
if (sample.SamplingPoints.Count == 0) if (sample.SamplingPoints.Count == 0)
{ {
throw new HardwareException( throw new HardwareException(
@@ -7,7 +7,7 @@ namespace HardwareWeb.Controllers
{ {
/// <summary> /// <summary>
/// 靶样轮廓识别与采样点规划接口。 /// 靶样轮廓识别与采样点规划接口。
/// 流程:采集基准画面 -> 采集靶样画面 -> 分析并返回处理后的图像。 /// 流程:抓取相机当前画面 -> 分析并返回处理后的图像。
/// </summary> /// </summary>
[ApiController] [ApiController]
[Route("api/sample")] [Route("api/sample")]
@@ -24,36 +24,21 @@ namespace HardwareWeb.Controllers
_logger = logger; _logger = logger;
} }
/// <summary>连续抓取多帧并取中值作为基准背景画面。</summary> /// <summary>
[HttpPost("baseline")] /// 获取轮廓识别的等待超时时间,
[ProducesResponseType(typeof(SampleBaselinePayload), StatusCodes.Status200OK)] /// 取自系统参数 camera_Identification_outtime(秒)。
public async Task<IActionResult> CaptureBaseline(CancellationToken ct) /// </summary>
[HttpGet("analyze-timeout")]
[ProducesResponseType(typeof(AnalyzeTimeoutPayload), StatusCodes.Status200OK)]
public IActionResult AnalyzeTimeout()
{ {
try var timeoutSeconds = _service.GetIdentificationTimeoutSeconds();
{ _logger.LogInformation(
return Ok(SampleBaselinePayload.From( "前端轮廓识别等待超时:{TimeoutSeconds} 秒" +
await _service.CaptureBaselineAsync(ct))); "(系统参数 camera_Identification_outtime)",
} timeoutSeconds);
catch (HardwareException ex)
{
return HardwareError(ex);
}
}
/// <summary>关闭红外测距光源后抓取当前最新画面作为靶样画面。</summary> return Ok(new AnalyzeTimeoutPayload(timeoutSeconds));
[HttpPost("target")]
[ProducesResponseType(typeof(SampleTargetPayload), StatusCodes.Status200OK)]
public async Task<IActionResult> CaptureTarget(CancellationToken ct)
{
try
{
return Ok(SampleTargetPayload.From(
await _service.CaptureTargetAsync(ct)));
}
catch (HardwareException ex)
{
return HardwareError(ex);
}
} }
/// <summary>提取靶样轮廓、绘制采样点并返回处理后的 JPEG 图像。</summary> /// <summary>提取靶样轮廓、绘制采样点并返回处理后的 JPEG 图像。</summary>
+20
View File
@@ -27,4 +27,24 @@
<Content Remove="..\HardwareControl.Core\Models\4.highvalue_expert_logits.onnx" /> <Content Remove="..\HardwareControl.Core\Models\4.highvalue_expert_logits.onnx" />
</ItemGroup> </ItemGroup>
<!--
前端构建产物:pnpm build 生成的 dist 在发布时自动复制到 wwwroot。
避免发布目录继续使用旧的前端包(旧包把识别等待时间写死为 30 秒)。
未执行 pnpm build 时 dist 不存在,该配置不会产生任何文件。
-->
<ItemGroup>
<Content Include="..\Hardware-Vue\dist\**\*"
Link="wwwroot\%(RecursiveDir)%(Filename)%(Extension)"
CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<!--
ASP.NET Core 的静态 Web 资源清单会把项目 wwwroot 作为内容根目录,
目录不存在时 Development 环境启动会在 WebApplication.CreateBuilder
抛 DirectoryNotFoundException。这里在构建前确保目录存在。
-->
<Target Name="EnsureWwwRootDirectory" BeforeTargets="PrepareForBuild">
<MakeDir Directories="$(MSBuildProjectDirectory)\wwwroot" />
</Target>
</Project> </Project>
+3 -20
View File
@@ -2,29 +2,12 @@ using HardwareControl.Core.SampleAnalysis;
namespace HardwareWeb.Models namespace HardwareWeb.Models
{ {
/// <summary>基准画面采集结果。</summary>
public sealed record SampleBaselinePayload(
int Width,
int Height,
DateTimeOffset CapturedAt)
{
public static SampleBaselinePayload From(SampleBaselineInfo info) =>
new(info.Width, info.Height, info.CapturedAt);
}
/// <summary>靶样画面采集结果。</summary>
public sealed record SampleTargetPayload(
int Width,
int Height,
DateTimeOffset CapturedAt)
{
public static SampleTargetPayload From(SampleTargetInfo info) =>
new(info.Width, info.Height, info.CapturedAt);
}
/// <summary>采样点坐标(图像像素)。</summary> /// <summary>采样点坐标(图像像素)。</summary>
public sealed record SamplePointPayload(int X, int Y); public sealed record SamplePointPayload(int X, int Y);
/// <summary>轮廓识别等待超时(单位:秒)。</summary>
public sealed record AnalyzeTimeoutPayload(int TimeoutSeconds);
/// <summary>靶样轮廓与采样点分析结果。</summary> /// <summary>靶样轮廓与采样点分析结果。</summary>
public sealed record SampleAnalysisPayload( public sealed record SampleAnalysisPayload(
string ImageBase64, string ImageBase64,
+14 -2
View File
@@ -56,8 +56,8 @@ builder.Services.AddSingleton<AdminAccessService>();
// 8. 靶样轮廓识别与采样点规划(ONNX 模型分割) // 8. 靶样轮廓识别与采样点规划(ONNX 模型分割)
builder.Services.Configure<OnnxSegmentationOptions>( builder.Services.Configure<OnnxSegmentationOptions>(
builder.Configuration.GetSection(OnnxSegmentationOptions.SectionName)); builder.Configuration.GetSection(OnnxSegmentationOptions.SectionName));
builder.Services.AddSingleton<BackgroundDiffSegmenter>();
builder.Services.AddSingleton<TargetOutlineAnalyzer>(); builder.Services.AddSingleton<TargetOutlineAnalyzer>();
builder.Services.AddHostedService<SampleAnalysisWarmupService>();
builder.Services.AddSingleton<ISampleAnalysisService, SampleAnalysisService>(); builder.Services.AddSingleton<ISampleAnalysisService, SampleAnalysisService>();
// 9. 位移台:串口优先取系统参数 translation_com,未配置时回退到 appsettings 的 AxisStage:ComPort // 9. 位移台:串口优先取系统参数 translation_com,未配置时回退到 appsettings 的 AxisStage:ComPort
@@ -105,7 +105,19 @@ app.UseAuthorization();
//这两行是用来托管前端的 //这两行是用来托管前端的
app.UseDefaultFiles(); 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(); app.MapControllers();
@@ -0,0 +1,45 @@
using HardwareControl.Core.SampleAnalysis;
namespace HardwareWeb.Services
{
/// <summary>
/// 应用启动后在后台预热靶样轮廓分析模型。
/// 大模型首次加载往往需要数十秒,放到后台执行可以避免用户点击检测时才等待。
/// </summary>
public sealed class SampleAnalysisWarmupService : IHostedService
{
private readonly TargetOutlineAnalyzer _analyzer;
private readonly ILogger<SampleAnalysisWarmupService> _logger;
public SampleAnalysisWarmupService(
TargetOutlineAnalyzer analyzer,
ILogger<SampleAnalysisWarmupService> 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;
}
}
+3 -1
View File
@@ -49,7 +49,7 @@
}, },
"SystemSetting": { "SystemSetting": {
"DatabasePath": null, "DatabasePath": null,
"AdminPassword": "flzx3QC!1" "AdminPassword": "123456"
}, },
"Scanning": { "Scanning": {
"DatabasePath": null, "DatabasePath": null,
@@ -60,6 +60,8 @@
"ModelDirectory": "Models", "ModelDirectory": "Models",
"InputWidth": 640, "InputWidth": 640,
"InputHeight": 640, "InputHeight": 640,
"ExecutionProvider": "Auto",
"DmlDeviceId": 0,
"ConfidenceThreshold": 0.25, "ConfidenceThreshold": 0.25,
"FallbackConfidenceThreshold": 0.6, "FallbackConfidenceThreshold": 0.6,
"MaskThreshold": 0.5, "MaskThreshold": 0.5,