Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19b7b10e97 | ||
|
|
b30d9f92ce |
@@ -361,3 +361,6 @@ MigrationBackup/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
/.vscode
|
||||
/.gitignore
|
||||
/Visual Studio 18/Visualizers
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 靶样轮廓识别与采样点规划接口封装。
|
||||
* 后端实现见 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
|
||||
}
|
||||
|
||||
export interface SampleAnalysisResult {
|
||||
imageBase64: string
|
||||
mimeType: string
|
||||
width: number
|
||||
height: number
|
||||
samplingPointCount: number
|
||||
samplingPoints: SamplePoint[]
|
||||
}
|
||||
|
||||
const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '')
|
||||
const DEFAULT_TIMEOUT = 15000
|
||||
const ANALYZE_TIMEOUT = 30000
|
||||
|
||||
export class SampleApiError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(message: string, status = 0) {
|
||||
super(message)
|
||||
this.name = 'SampleApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
timeout = DEFAULT_TIMEOUT,
|
||||
): Promise<T> {
|
||||
const controller = new AbortController()
|
||||
const timer = window.setTimeout(() => controller.abort(), timeout)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = `HTTP ${response.status}`
|
||||
try {
|
||||
const body = (await response.json()) as { message?: string; error?: string }
|
||||
detail = body.message ?? body.error ?? detail
|
||||
} catch {
|
||||
// 响应不是 JSON 时保留状态码信息
|
||||
}
|
||||
throw new SampleApiError(detail, response.status)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
} catch (error) {
|
||||
if (error instanceof SampleApiError) throw error
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
throw new SampleApiError('图像分析服务响应超时')
|
||||
}
|
||||
throw new SampleApiError(
|
||||
error instanceof Error ? error.message : '无法连接图像分析服务',
|
||||
)
|
||||
} finally {
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** 相机画面稳定后采集基准画面。 */
|
||||
export function captureSampleBaseline(): Promise<SampleFrameResult> {
|
||||
return request<SampleFrameResult>('/api/sample/baseline', { method: 'POST' })
|
||||
}
|
||||
|
||||
/** 放置靶样并点击开始检测时采集第二张画面。 */
|
||||
export function captureSampleTarget(): Promise<SampleFrameResult> {
|
||||
return request<SampleFrameResult>('/api/sample/target', { method: 'POST' })
|
||||
}
|
||||
|
||||
/** 提取靶样轮廓、绘制采样点并返回处理后的图像。 */
|
||||
export function analyzeSample(): Promise<SampleAnalysisResult> {
|
||||
return request<SampleAnalysisResult>(
|
||||
'/api/sample/analyze',
|
||||
{ method: 'POST' },
|
||||
ANALYZE_TIMEOUT,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
'system-config': []
|
||||
ruler: []
|
||||
}>()
|
||||
|
||||
const firstButton = ref<HTMLButtonElement | null>(null)
|
||||
|
||||
function close() {
|
||||
emit('close')
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') close()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async (open) => {
|
||||
if (open) {
|
||||
window.addEventListener('keydown', onKeydown)
|
||||
await nextTick()
|
||||
firstButton.value?.focus()
|
||||
} else {
|
||||
window.removeEventListener('keydown', onKeydown)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onKeydown)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="function-panel">
|
||||
<div v-if="open" class="panel-backdrop" @click.self="close">
|
||||
<section
|
||||
class="panel-card"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="管理员功能选择"
|
||||
>
|
||||
<header class="panel-card__header">
|
||||
<h2>管理员功能</h2>
|
||||
<p>请选择需要进入的功能</p>
|
||||
</header>
|
||||
|
||||
<div class="panel-grid">
|
||||
<button
|
||||
ref="firstButton"
|
||||
class="function-card"
|
||||
type="button"
|
||||
@click="emit('system-config')"
|
||||
>
|
||||
<span class="function-card__icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 64 64">
|
||||
<path
|
||||
d="M26 8h12l2 7a20 20 0 0 1 5 3l7-1 6 10-5 5a20 20 0 0 1 0 6l5 5-6 10-7-1a20 20 0 0 1-5 3l-2 7H26l-2-7a20 20 0 0 1-5-3l-7 1-6-10 5-5a20 20 0 0 1 0-6l-5-5 6-10 7 1a20 20 0 0 1 5-3Z"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
<circle
|
||||
cx="32"
|
||||
cy="32"
|
||||
r="8"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="function-card__label">参数设置</span>
|
||||
<span class="function-card__desc">管理系统运行参数</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="function-card"
|
||||
type="button"
|
||||
@click="emit('ruler')"
|
||||
>
|
||||
<span class="function-card__icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 64 64">
|
||||
<rect
|
||||
x="7"
|
||||
y="22"
|
||||
width="50"
|
||||
height="20"
|
||||
rx="3"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
transform="rotate(-12 32 32)"
|
||||
/>
|
||||
<path
|
||||
d="M16 26v7M24 24v7M32 22v7M40 20v7M48 18v7"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
stroke-linecap="round"
|
||||
transform="rotate(-12 32 32)"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="function-card__label">标尺设定</span>
|
||||
<span class="function-card__desc">配置标尺与校准参数</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button class="panel-card__close" type="button" @click="close">
|
||||
取消
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 70;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(18, 33, 54, 0.44);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.panel-card {
|
||||
width: 820px;
|
||||
padding: 42px 46px 34px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.panel-card__header h2 {
|
||||
color: #1f2937;
|
||||
font-size: 32px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.panel-card__header p {
|
||||
margin-top: 12px;
|
||||
color: #778394;
|
||||
font-size: 19px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.panel-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 24px;
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
.function-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 30px 24px 28px;
|
||||
border: 2px solid var(--line);
|
||||
border-radius: 18px;
|
||||
background: linear-gradient(180deg, #ffffff 0%, #f7f9fc 100%);
|
||||
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.function-card:hover {
|
||||
border-color: #b9d1f3;
|
||||
box-shadow: 0 16px 34px rgba(47, 111, 208, 0.16);
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
|
||||
.function-card__icon {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
border-radius: 50%;
|
||||
color: var(--blue);
|
||||
background: linear-gradient(145deg, #f1f7ff, #dfeaff);
|
||||
box-shadow: inset 0 1px 0 #fff, 0 8px 22px rgba(47, 111, 208, 0.14);
|
||||
}
|
||||
|
||||
.function-card__icon svg {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.function-card__label {
|
||||
color: #1f2937;
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.function-card__desc {
|
||||
color: var(--muted);
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.panel-card__close {
|
||||
width: 180px;
|
||||
height: 54px;
|
||||
margin-top: 30px;
|
||||
border: 2px solid var(--line-strong);
|
||||
border-radius: 12px;
|
||||
color: var(--ink-soft);
|
||||
font-size: 19px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
background: #fff;
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
|
||||
.panel-card__close:hover {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.function-panel-enter-active,
|
||||
.function-panel-leave-active {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.function-panel-enter-active .panel-card,
|
||||
.function-panel-leave-active .panel-card {
|
||||
transition: transform 0.24s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.function-panel-enter-from,
|
||||
.function-panel-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.function-panel-enter-from .panel-card,
|
||||
.function-panel-leave-to .panel-card {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.97);
|
||||
}
|
||||
</style>
|
||||
@@ -1,14 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { connectCamera } from '@/api/camera'
|
||||
import { useCameraStatus } from '@/composables/useCameraStatus'
|
||||
import { useCameraStream } from '@/composables/useCameraStream'
|
||||
import cameraPlaceholder from '@/assets/camera-placeholder.webp'
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 相机画面稳定显示后触发一次,用于采集基准画面。 */
|
||||
ready: []
|
||||
}>()
|
||||
|
||||
const { state: cameraState, refresh, startPolling } = useCameraStatus(5000, false)
|
||||
const { state: streamState, frameUrl, isLive, connect } = useCameraStream()
|
||||
|
||||
const connectingCamera = ref(false)
|
||||
const readyEmitted = ref(false)
|
||||
let readyTimer: number | undefined
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (isLive.value) return '实时画面'
|
||||
@@ -32,6 +39,34 @@ const statusTone = computed<'on' | 'wait' | '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 () => {
|
||||
await refresh()
|
||||
|
||||
|
||||
@@ -45,6 +45,12 @@ const router = createRouter({
|
||||
component: () => import('@/views/SystemConfigView.vue'),
|
||||
meta: { title: '系统参数管理', requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: '/ruler',
|
||||
name: 'ruler',
|
||||
component: () => import('@/views/RulerSettingView.vue'),
|
||||
meta: { title: '标尺设定', requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: { name: 'home' },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AdminFunctionPanel from '@/components/AdminFunctionPanel.vue'
|
||||
import AdminPasswordModal from '@/components/AdminPasswordModal.vue'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
import ModuleButton from '@/components/ModuleButton.vue'
|
||||
@@ -29,6 +30,7 @@ const router = useRouter()
|
||||
const modalOpen = ref(false)
|
||||
const modalModule = ref('')
|
||||
const adminModalOpen = ref(false)
|
||||
const adminPanelOpen = ref(false)
|
||||
|
||||
// 隐藏入口:800ms 内连续点击 Logo 三次,打开管理员密码框。
|
||||
const LOGO_CLICK_WINDOW = 800
|
||||
@@ -57,9 +59,19 @@ function onLogoClick() {
|
||||
|
||||
function onAdminSuccess() {
|
||||
adminModalOpen.value = false
|
||||
adminPanelOpen.value = true
|
||||
}
|
||||
|
||||
function openSystemConfig() {
|
||||
adminPanelOpen.value = false
|
||||
void router.push({ name: 'systemConfig' })
|
||||
}
|
||||
|
||||
function openRulerSetting() {
|
||||
adminPanelOpen.value = false
|
||||
void router.push({ name: 'ruler' })
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (logoTimer !== undefined) {
|
||||
window.clearTimeout(logoTimer)
|
||||
@@ -121,6 +133,13 @@ function openModule(module: HomeModule) {
|
||||
@close="adminModalOpen = false"
|
||||
@success="onAdminSuccess"
|
||||
/>
|
||||
|
||||
<AdminFunctionPanel
|
||||
:open="adminPanelOpen"
|
||||
@close="adminPanelOpen = false"
|
||||
@system-config="openSystemConfig"
|
||||
@ruler="openRulerSetting"
|
||||
/>
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,728 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { connectCamera } from '@/api/camera'
|
||||
import {
|
||||
SystemConfigApiError,
|
||||
clearAdminSession,
|
||||
createSystemConfig,
|
||||
listSystemConfigs,
|
||||
updateSystemConfig,
|
||||
} from '@/api/systemConfig'
|
||||
import { useCameraStatus } from '@/composables/useCameraStatus'
|
||||
import { useCameraStream } from '@/composables/useCameraStream'
|
||||
import { showToast } from '@/composables/useToast'
|
||||
import cameraPlaceholder from '@/assets/camera-placeholder.webp'
|
||||
|
||||
interface Point {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
const SCALE_CONFIG_NAME = 'camera_scale'
|
||||
const MIN_LINE_PIXELS = 4
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const { state: cameraState, refresh, startPolling } = useCameraStatus(5000, false)
|
||||
const { state: streamState, frameUrl, isLive, connect } = useCameraStream()
|
||||
|
||||
const viewport = ref<HTMLElement | null>(null)
|
||||
const overlay = ref<SVGSVGElement | null>(null)
|
||||
|
||||
// 相机原始画面尺寸(像素),用于把显示坐标换算成采集画面像素
|
||||
const frameWidth = ref(0)
|
||||
const frameHeight = ref(0)
|
||||
const overlayRect = ref({ left: 0, top: 0, width: 0, height: 0 })
|
||||
|
||||
const startPoint = ref<Point | null>(null)
|
||||
const endPoint = ref<Point | null>(null)
|
||||
const drawing = ref(false)
|
||||
|
||||
const distanceModalOpen = ref(false)
|
||||
const distanceInput = ref('')
|
||||
const inputError = ref('')
|
||||
const saving = ref(false)
|
||||
const distanceField = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (isLive.value) return '实时画面'
|
||||
if (
|
||||
streamState.value === 'connecting' ||
|
||||
cameraState.value === 'checking'
|
||||
) {
|
||||
return '连接中'
|
||||
}
|
||||
if (cameraState.value === 'offline') return '相机服务离线'
|
||||
return '等待画面'
|
||||
})
|
||||
|
||||
const overlayStyle = computed(() => ({
|
||||
left: `${overlayRect.value.left}px`,
|
||||
top: `${overlayRect.value.top}px`,
|
||||
width: `${overlayRect.value.width}px`,
|
||||
height: `${overlayRect.value.height}px`,
|
||||
}))
|
||||
|
||||
const pixelDistance = computed(() => {
|
||||
if (!startPoint.value || !endPoint.value) return 0
|
||||
return Math.hypot(
|
||||
endPoint.value.x - startPoint.value.x,
|
||||
endPoint.value.y - startPoint.value.y,
|
||||
)
|
||||
})
|
||||
|
||||
const handleRadius = computed(() => Math.max(6, frameWidth.value * 0.006))
|
||||
|
||||
function goHome() {
|
||||
void router.replace({ name: 'home' })
|
||||
}
|
||||
|
||||
/** 根据相机原始比例计算画面在容器内的实际显示区域 */
|
||||
function updateOverlayRect() {
|
||||
const element = viewport.value
|
||||
if (!element || !frameWidth.value || !frameHeight.value) return
|
||||
|
||||
const viewWidth = element.clientWidth
|
||||
const viewHeight = element.clientHeight
|
||||
if (!viewWidth || !viewHeight) return
|
||||
|
||||
const aspect = frameWidth.value / frameHeight.value
|
||||
let width = viewWidth
|
||||
let height = viewHeight
|
||||
|
||||
if (viewWidth / viewHeight > aspect) {
|
||||
width = viewHeight * aspect
|
||||
} else {
|
||||
height = viewWidth / aspect
|
||||
}
|
||||
|
||||
overlayRect.value = {
|
||||
left: (viewWidth - width) / 2,
|
||||
top: (viewHeight - height) / 2,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
function onImageLoad(event: Event) {
|
||||
if (!frameUrl.value) return
|
||||
|
||||
const image = event.target as HTMLImageElement
|
||||
if (!image.naturalWidth || !image.naturalHeight) return
|
||||
|
||||
frameWidth.value = image.naturalWidth
|
||||
frameHeight.value = image.naturalHeight
|
||||
updateOverlayRect()
|
||||
}
|
||||
|
||||
function pointFromEvent(event: PointerEvent): Point | null {
|
||||
const element = overlay.value
|
||||
if (!element || !frameWidth.value || !frameHeight.value) return null
|
||||
|
||||
const rect = element.getBoundingClientRect()
|
||||
if (!rect.width || !rect.height) return null
|
||||
|
||||
return {
|
||||
x: ((event.clientX - rect.left) / rect.width) * frameWidth.value,
|
||||
y: ((event.clientY - rect.top) / rect.height) * frameHeight.value,
|
||||
}
|
||||
}
|
||||
|
||||
function clearLine() {
|
||||
startPoint.value = null
|
||||
endPoint.value = null
|
||||
drawing.value = false
|
||||
}
|
||||
|
||||
function onPointerDown(event: PointerEvent) {
|
||||
if (!isLive.value || distanceModalOpen.value || event.button !== 0) return
|
||||
|
||||
const point = pointFromEvent(event)
|
||||
if (!point) return
|
||||
|
||||
startPoint.value = point
|
||||
endPoint.value = point
|
||||
drawing.value = true
|
||||
overlay.value?.setPointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
function onPointerMove(event: PointerEvent) {
|
||||
if (!drawing.value) return
|
||||
|
||||
const point = pointFromEvent(event)
|
||||
if (point) endPoint.value = point
|
||||
}
|
||||
|
||||
function finishDrawing() {
|
||||
if (!drawing.value) return
|
||||
drawing.value = false
|
||||
|
||||
if (pixelDistance.value < MIN_LINE_PIXELS) {
|
||||
clearLine()
|
||||
return
|
||||
}
|
||||
|
||||
distanceInput.value = ''
|
||||
inputError.value = ''
|
||||
distanceModalOpen.value = true
|
||||
}
|
||||
|
||||
function onPointerUp(event: PointerEvent) {
|
||||
if (overlay.value?.hasPointerCapture(event.pointerId)) {
|
||||
overlay.value.releasePointerCapture(event.pointerId)
|
||||
}
|
||||
finishDrawing()
|
||||
}
|
||||
|
||||
function onPointerCancel(event: PointerEvent) {
|
||||
if (overlay.value?.hasPointerCapture(event.pointerId)) {
|
||||
overlay.value.releasePointerCapture(event.pointerId)
|
||||
}
|
||||
finishDrawing()
|
||||
}
|
||||
|
||||
function cancelDistanceInput() {
|
||||
if (saving.value) return
|
||||
distanceModalOpen.value = false
|
||||
clearLine()
|
||||
}
|
||||
|
||||
async function confirmDistance() {
|
||||
if (saving.value) return
|
||||
|
||||
const distanceMm = Number(distanceInput.value)
|
||||
if (!Number.isFinite(distanceMm) || distanceMm <= 0) {
|
||||
inputError.value = '请输入大于 0 的实际距离'
|
||||
return
|
||||
}
|
||||
|
||||
if (pixelDistance.value < MIN_LINE_PIXELS) {
|
||||
inputError.value = '线段无效,请重新绘制'
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
inputError.value = ''
|
||||
|
||||
try {
|
||||
const scale = pixelDistance.value / distanceMm
|
||||
const scaleValue = scale.toFixed(2)
|
||||
|
||||
const matches = await listSystemConfigs(SCALE_CONFIG_NAME)
|
||||
const existing = matches.find(
|
||||
(item) => item.configName.trim().toLowerCase() === SCALE_CONFIG_NAME,
|
||||
)
|
||||
|
||||
if (existing) {
|
||||
await updateSystemConfig(existing.configId, {
|
||||
configClass: existing.configClass || '相机',
|
||||
configName: SCALE_CONFIG_NAME,
|
||||
configValue: scaleValue,
|
||||
configDescript: existing.configDescript || '标尺比例(像素/毫米)',
|
||||
})
|
||||
} else {
|
||||
await createSystemConfig({
|
||||
configClass: '相机',
|
||||
configName: SCALE_CONFIG_NAME,
|
||||
configValue: scaleValue,
|
||||
configDescript: '标尺比例(像素/毫米)',
|
||||
})
|
||||
}
|
||||
|
||||
distanceModalOpen.value = false
|
||||
showToast(`标尺设定完成:${scaleValue} px/mm`)
|
||||
goHome()
|
||||
} catch (error) {
|
||||
if (error instanceof SystemConfigApiError && error.status === 401) {
|
||||
clearAdminSession()
|
||||
showToast('管理员凭证已过期,请重新进入标尺设定')
|
||||
goHome()
|
||||
return
|
||||
}
|
||||
|
||||
inputError.value = error instanceof Error ? error.message : '标尺保存失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onModalKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') cancelDistanceInput()
|
||||
}
|
||||
|
||||
watch(distanceModalOpen, async (open) => {
|
||||
if (open) {
|
||||
window.addEventListener('keydown', onModalKeydown)
|
||||
await nextTick()
|
||||
distanceField.value?.focus()
|
||||
} else {
|
||||
window.removeEventListener('keydown', onModalKeydown)
|
||||
}
|
||||
})
|
||||
|
||||
watch(frameUrl, (url) => {
|
||||
if (!url) {
|
||||
clearLine()
|
||||
frameWidth.value = 0
|
||||
frameHeight.value = 0
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await refresh()
|
||||
|
||||
const streamPromise = connect()
|
||||
|
||||
if (cameraState.value === 'disconnected') {
|
||||
try {
|
||||
await connectCamera()
|
||||
await refresh()
|
||||
} catch {
|
||||
// 没有相机或服务不可达时保留占位画面
|
||||
}
|
||||
}
|
||||
|
||||
startPolling()
|
||||
await streamPromise
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onModalKeydown)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppStage>
|
||||
<PageHeader title="标尺设定" subtitle="在相机画面中拖动画线,输入实际距离完成标定">
|
||||
<template #left>
|
||||
<button class="header-button header-button--outline" type="button" @click="goHome">
|
||||
返回
|
||||
</button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<main class="ruler-main">
|
||||
<section class="ruler-card">
|
||||
<header class="ruler-card__header">
|
||||
<h2>相机画面</h2>
|
||||
<span class="ruler-card__status">
|
||||
<i class="ruler-card__dot" :class="{ 'ruler-card__dot--on': isLive }"></i>
|
||||
{{ statusText }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div ref="viewport" class="ruler-viewport">
|
||||
<img
|
||||
class="ruler-viewport__image"
|
||||
:src="frameUrl ?? cameraPlaceholder"
|
||||
:alt="frameUrl ? '相机实时画面' : '相机预览画面'"
|
||||
draggable="false"
|
||||
@load="onImageLoad"
|
||||
/>
|
||||
|
||||
<svg
|
||||
v-if="frameUrl && frameWidth && frameHeight"
|
||||
ref="overlay"
|
||||
class="ruler-overlay"
|
||||
:style="overlayStyle"
|
||||
:viewBox="`0 0 ${frameWidth} ${frameHeight}`"
|
||||
preserveAspectRatio="none"
|
||||
@pointerdown="onPointerDown"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointercancel="onPointerCancel"
|
||||
>
|
||||
<line
|
||||
v-if="startPoint && endPoint"
|
||||
class="ruler-line"
|
||||
:x1="startPoint.x"
|
||||
:y1="startPoint.y"
|
||||
:x2="endPoint.x"
|
||||
:y2="endPoint.y"
|
||||
vector-effect="non-scaling-stroke"
|
||||
/>
|
||||
<circle
|
||||
v-if="startPoint"
|
||||
class="ruler-handle"
|
||||
:cx="startPoint.x"
|
||||
:cy="startPoint.y"
|
||||
:r="handleRadius"
|
||||
/>
|
||||
<circle
|
||||
v-if="endPoint"
|
||||
class="ruler-handle"
|
||||
:cx="endPoint.x"
|
||||
:cy="endPoint.y"
|
||||
:r="handleRadius"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<p v-if="!isLive" class="ruler-viewport__tip">等待相机画面...</p>
|
||||
</div>
|
||||
|
||||
<footer class="ruler-card__footer">
|
||||
<span class="ruler-card__step">1</span>
|
||||
<span>按住鼠标左键,沿已知实际长度的物体拖动画线</span>
|
||||
<span class="ruler-card__divider"></span>
|
||||
<span class="ruler-card__step">2</span>
|
||||
<span>松开后输入该线段的实际距离(mm),确认后自动计算比例尺</span>
|
||||
</footer>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="distance-modal">
|
||||
<div v-if="distanceModalOpen" class="distance-backdrop" @click.self="cancelDistanceInput">
|
||||
<section class="distance-card" role="dialog" aria-modal="true" aria-label="输入实际距离">
|
||||
<h2>输入实际距离</h2>
|
||||
<p>线段像素长度:<strong>{{ pixelDistance.toFixed(1) }} px</strong></p>
|
||||
|
||||
<form class="distance-form" @submit.prevent="confirmDistance">
|
||||
<label class="distance-field">
|
||||
<span>实际距离</span>
|
||||
<div class="distance-field__control">
|
||||
<input
|
||||
ref="distanceField"
|
||||
v-model="distanceInput"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
inputmode="decimal"
|
||||
placeholder="例如:100"
|
||||
:disabled="saving"
|
||||
/>
|
||||
<span class="distance-field__unit">mm</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<p v-if="inputError" class="distance-error">{{ inputError }}</p>
|
||||
|
||||
<div class="distance-actions">
|
||||
<button
|
||||
class="distance-button distance-button--ghost"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@click="cancelDistanceInput"
|
||||
>
|
||||
重画
|
||||
</button>
|
||||
<button
|
||||
class="distance-button distance-button--primary"
|
||||
type="submit"
|
||||
:disabled="saving"
|
||||
>
|
||||
{{ saving ? '保存中...' : '确定' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ruler-main {
|
||||
position: absolute;
|
||||
top: 176px;
|
||||
right: 44px;
|
||||
bottom: 40px;
|
||||
left: 44px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ruler-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 1400px;
|
||||
max-width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
border: 1px solid #d8e0e9;
|
||||
border-radius: 18px;
|
||||
background: #fff;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.ruler-card__header {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 76px;
|
||||
padding: 0 28px;
|
||||
background: linear-gradient(180deg, #3d80e2 0%, #2f6fd0 100%);
|
||||
}
|
||||
|
||||
.ruler-card__header h2 {
|
||||
color: #fff;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
text-shadow: 0 1px 3px rgba(16, 49, 101, 0.22);
|
||||
}
|
||||
|
||||
.ruler-card__status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.24);
|
||||
border-radius: 30px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-size: 15px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.ruler-card__dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #c9d4e4;
|
||||
}
|
||||
|
||||
.ruler-card__dot--on {
|
||||
background: #74f4c5;
|
||||
box-shadow: 0 0 9px rgba(116, 244, 197, 0.9);
|
||||
}
|
||||
|
||||
.ruler-viewport {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: #080d14;
|
||||
}
|
||||
|
||||
.ruler-viewport__image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ruler-overlay {
|
||||
position: absolute;
|
||||
touch-action: none;
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.ruler-line {
|
||||
stroke: #74f1df;
|
||||
stroke-width: 3;
|
||||
stroke-linecap: round;
|
||||
filter: drop-shadow(0 0 4px rgba(116, 241, 223, 0.75));
|
||||
}
|
||||
|
||||
.ruler-handle {
|
||||
fill: #74f1df;
|
||||
stroke: rgba(8, 13, 20, 0.65);
|
||||
stroke-width: 2;
|
||||
}
|
||||
|
||||
.ruler-viewport__tip {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
color: rgba(216, 228, 243, 0.7);
|
||||
font-size: 20px;
|
||||
letter-spacing: 2px;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.ruler-card__footer {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
height: 72px;
|
||||
padding: 0 30px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.ruler-card__step {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ruler-card__divider {
|
||||
width: 1px;
|
||||
height: 22px;
|
||||
margin: 0 8px;
|
||||
background: var(--line-strong);
|
||||
}
|
||||
|
||||
.distance-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 70;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(18, 33, 54, 0.44);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.distance-card {
|
||||
width: 600px;
|
||||
padding: 38px 44px 34px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.distance-card h2 {
|
||||
color: #1f2937;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.distance-card > p {
|
||||
margin-top: 12px;
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.distance-card > p strong {
|
||||
color: var(--blue);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.distance-form {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.distance-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
text-align: left;
|
||||
color: var(--ink-soft);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.distance-field__control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
border: 2px solid var(--line-strong);
|
||||
border-radius: 10px;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.distance-field__control:focus-within {
|
||||
border-color: var(--blue);
|
||||
box-shadow: 0 0 0 4px rgba(47, 111, 208, 0.12);
|
||||
}
|
||||
|
||||
.distance-field input {
|
||||
flex: 1;
|
||||
height: 58px;
|
||||
padding: 0 18px;
|
||||
border: 0;
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 22px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.distance-field__unit {
|
||||
flex: none;
|
||||
padding: 0 20px;
|
||||
color: var(--muted);
|
||||
font-size: 19px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.distance-error {
|
||||
margin-top: 14px;
|
||||
color: var(--red);
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.distance-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 20px;
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.distance-button {
|
||||
width: 180px;
|
||||
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;
|
||||
}
|
||||
|
||||
.distance-button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.distance-button--ghost {
|
||||
border: 2px solid var(--line-strong);
|
||||
color: var(--ink-soft);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.distance-button--ghost:hover:not(:disabled) {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.distance-button--primary {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
|
||||
}
|
||||
|
||||
.distance-button--primary:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
|
||||
}
|
||||
|
||||
.distance-modal-enter-active,
|
||||
.distance-modal-leave-active {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.distance-modal-enter-active .distance-card,
|
||||
.distance-modal-leave-active .distance-card {
|
||||
transition: transform 0.24s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.distance-modal-enter-from,
|
||||
.distance-modal-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.distance-modal-enter-from .distance-card,
|
||||
.distance-modal-leave-to .distance-card {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.97);
|
||||
}
|
||||
</style>
|
||||
@@ -1,30 +1,87 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import CameraPreview from '@/components/CameraPreview.vue'
|
||||
import GuideIcon from '@/components/GuideIcon.vue'
|
||||
import StatusFooter from '@/components/StatusFooter.vue'
|
||||
import { captureSampleBaseline, captureSampleTarget } from '@/api/sample'
|
||||
import { showToast } from '@/composables/useToast'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const baselineReady = ref(false)
|
||||
const capturingBaseline = ref(false)
|
||||
const starting = ref(false)
|
||||
const requirementsConfirmed = ref(false)
|
||||
|
||||
const steps = [
|
||||
{ title: '打开样品仓', icon: 'door' as const },
|
||||
{ title: '放置待测样品', icon: 'tray' as const },
|
||||
{ title: '调整聚焦位置', icon: 'focus' as const },
|
||||
]
|
||||
|
||||
const placementRequirements = [
|
||||
'待测样品边缘不能超出载物台',
|
||||
'样品尽量放置在画面中央',
|
||||
'样品放置要稳定,检测过程中不能滑动或翻滚',
|
||||
'样品高度不能超过 2 厘米',
|
||||
]
|
||||
|
||||
const footerItems = computed(() => [
|
||||
baselineReady.value
|
||||
? '基准画面已采集'
|
||||
: capturingBaseline.value
|
||||
? '正在采集基准画面'
|
||||
: '等待相机画面稳定',
|
||||
'激光安全等级 Class 1',
|
||||
'环境温度 22℃',
|
||||
])
|
||||
|
||||
function goHome() {
|
||||
void router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
function startDetection() {
|
||||
void router.push({ name: 'scan' })
|
||||
async function onCameraReady() {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
function previewFocus() {
|
||||
showToast('预览对焦功能正在研发中')
|
||||
async function startDetection() {
|
||||
if (starting.value) return
|
||||
|
||||
if (!requirementsConfirmed.value) {
|
||||
showToast('请先确认样品放置符合要求')
|
||||
return
|
||||
}
|
||||
|
||||
if (!baselineReady.value) {
|
||||
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>
|
||||
|
||||
@@ -39,7 +96,7 @@ function previewFocus() {
|
||||
</PageHeader>
|
||||
|
||||
<main class="sample-main">
|
||||
<CameraPreview class="sample-camera" />
|
||||
<CameraPreview class="sample-camera" @ready="onCameraReady" />
|
||||
|
||||
<aside class="guide-column">
|
||||
<section class="guide-card">
|
||||
@@ -56,22 +113,49 @@ function previewFocus() {
|
||||
</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<section class="placement-requirements">
|
||||
<h3>
|
||||
<span class="placement-requirements__mark">!</span>
|
||||
放置要求
|
||||
</h3>
|
||||
|
||||
<ul>
|
||||
<li
|
||||
v-for="(requirement, index) in placementRequirements"
|
||||
:key="requirement"
|
||||
>
|
||||
<span class="placement-requirements__index">{{ index + 1 }}</span>
|
||||
<span>{{ requirement }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p class="placement-requirements__warning">
|
||||
以上任一项不符合请中止检测,否则可能损坏机器。
|
||||
</p>
|
||||
|
||||
<label class="placement-confirm">
|
||||
<input v-model="requirementsConfirmed" type="checkbox" />
|
||||
<span>我已确认样品放置符合以上要求</span>
|
||||
</label>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<div class="guide-actions">
|
||||
<button class="action-button action-button--start" type="button" @click="startDetection">
|
||||
开始检测
|
||||
</button>
|
||||
<button class="action-button action-button--ghost" type="button" @click="previewFocus">
|
||||
预览对焦
|
||||
<button
|
||||
class="action-button action-button--start"
|
||||
type="button"
|
||||
:disabled="starting || !requirementsConfirmed"
|
||||
:title="requirementsConfirmed ? undefined : '请先确认样品放置符合要求'"
|
||||
@click="startDetection"
|
||||
>
|
||||
{{ starting ? '准备中...' : '开始检测' }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<StatusFooter
|
||||
:items="['样品仓已关闭', '激光安全等级 Class 1', '环境温度 22℃']"
|
||||
/>
|
||||
<StatusFooter :items="footerItems" />
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
@@ -128,16 +212,16 @@ function previewFocus() {
|
||||
|
||||
.guide-steps {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.guide-step {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 22px;
|
||||
min-height: 0;
|
||||
min-height: 88px;
|
||||
padding: 0 34px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
@@ -177,10 +261,105 @@ function previewFocus() {
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.placement-requirements {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
margin: 0 24px 22px;
|
||||
padding: 18px 22px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(224, 154, 6, 0.45);
|
||||
border-radius: 14px;
|
||||
background: var(--orange-soft);
|
||||
color: #5b4213;
|
||||
}
|
||||
|
||||
.placement-requirements h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: #8a5b00;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.placement-requirements__mark {
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
color: #fff;
|
||||
background: var(--orange-dark);
|
||||
font-size: 19px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.placement-requirements ul {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.placement-requirements li {
|
||||
display: flex;
|
||||
gap: 9px;
|
||||
color: #5b4213;
|
||||
font-size: 18px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.placement-requirements__index {
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
width: 21px;
|
||||
height: 21px;
|
||||
margin-top: 2px;
|
||||
border-radius: 50%;
|
||||
background: rgba(224, 154, 6, 0.18);
|
||||
color: #8a5b00;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.placement-requirements__warning {
|
||||
margin-top: 10px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px dashed rgba(138, 91, 0, 0.32);
|
||||
color: var(--red);
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.placement-confirm {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: auto;
|
||||
padding-top: 10px;
|
||||
color: #5b4213;
|
||||
font-size: 17px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.placement-confirm input {
|
||||
flex: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
accent-color: var(--teal-dark);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.guide-actions {
|
||||
display: grid;
|
||||
flex: none;
|
||||
grid-template-columns: 1.16fr 0.84fr;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 20px;
|
||||
height: 78px;
|
||||
}
|
||||
@@ -200,6 +379,12 @@ function previewFocus() {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.action-button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.action-button--start {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #ffc52c 0%, #f3ae0d 100%);
|
||||
@@ -214,15 +399,4 @@ function previewFocus() {
|
||||
0 16px 30px rgba(224, 154, 6, 0.36),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.action-button--ghost {
|
||||
border: 2px solid #d3dbe6;
|
||||
color: #253243;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.action-button--ghost:hover {
|
||||
border-color: #aebdcd;
|
||||
background: #f8fafc;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,24 +1,115 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
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 { useTimedProgress } from '@/composables/useTimedProgress'
|
||||
import { analyzeSample, type SampleAnalysisResult } from '@/api/sample'
|
||||
|
||||
type AnalysisStatus = 'processing' | 'done' | 'error'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const { progress } = useTimedProgress(15000, () => {
|
||||
void router.replace({ name: 'spectrum' })
|
||||
const status = ref<AnalysisStatus>('processing')
|
||||
const result = ref<SampleAnalysisResult | null>(null)
|
||||
const errorMessage = ref('')
|
||||
const progress = ref(0)
|
||||
|
||||
let progressTimer: number | undefined
|
||||
|
||||
const resultImageUrl = computed(() =>
|
||||
result.value
|
||||
? `data:${result.value.mimeType};base64,${result.value.imageBase64}`
|
||||
: '',
|
||||
)
|
||||
|
||||
const samplingPointCount = computed(
|
||||
() => result.value?.samplingPointCount ?? '—',
|
||||
)
|
||||
|
||||
const progressLabel = computed(() => {
|
||||
if (status.value === 'done') return '靶样轮廓与采样点 100%'
|
||||
if (status.value === 'error') return '图像分析失败'
|
||||
return `靶样轮廓识别 ${Math.round(progress.value)}%`
|
||||
})
|
||||
|
||||
const progressLabel = computed(() => `点位扫描 ${Math.round(progress.value)}%`)
|
||||
const progressNote = computed(() => {
|
||||
if (status.value === 'done') {
|
||||
return `已规划 ${result.value?.samplingPointCount ?? 0} 个采样点`
|
||||
}
|
||||
if (status.value === 'error') return '请返回或重试'
|
||||
return '背景差分分析中'
|
||||
})
|
||||
|
||||
const footerItems = computed(() => {
|
||||
if (status.value === 'done') {
|
||||
return [
|
||||
'轮廓提取完成',
|
||||
`已规划 ${result.value?.samplingPointCount ?? 0} 个采样点`,
|
||||
'等待采集光谱',
|
||||
]
|
||||
}
|
||||
if (status.value === 'error') {
|
||||
return ['轮廓提取失败', '请检查靶样放置', '等待重试']
|
||||
}
|
||||
return ['相机画面分析中', '背景差分识别轮廓', '采样点规划中']
|
||||
})
|
||||
|
||||
function stopProgress() {
|
||||
if (progressTimer !== undefined) {
|
||||
window.clearInterval(progressTimer)
|
||||
progressTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function startProgress() {
|
||||
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)
|
||||
}
|
||||
|
||||
async function runAnalysis() {
|
||||
status.value = 'processing'
|
||||
result.value = null
|
||||
errorMessage.value = ''
|
||||
startProgress()
|
||||
|
||||
try {
|
||||
result.value = await analyzeSample()
|
||||
progress.value = 100
|
||||
status.value = 'done'
|
||||
} catch (error) {
|
||||
status.value = 'error'
|
||||
errorMessage.value =
|
||||
error instanceof Error ? error.message : '靶样轮廓分析失败'
|
||||
} finally {
|
||||
stopProgress()
|
||||
}
|
||||
}
|
||||
|
||||
function abortProcess() {
|
||||
void router.replace({ name: 'home' })
|
||||
}
|
||||
|
||||
function retry() {
|
||||
void runAnalysis()
|
||||
}
|
||||
|
||||
function goSpectrum() {
|
||||
void router.replace({ name: 'spectrum' })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void runAnalysis()
|
||||
})
|
||||
|
||||
onBeforeUnmount(stopProgress)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -40,7 +131,39 @@ function abortProcess() {
|
||||
</PageHeader>
|
||||
|
||||
<main class="scan-main">
|
||||
<ScanVisual class="scan-card" />
|
||||
<ScanVisual v-if="status === 'processing'" class="scan-card" />
|
||||
|
||||
<section v-else-if="status === 'done'" class="result-card">
|
||||
<header class="result-card__header">
|
||||
<h2>靶样轮廓与采样点</h2>
|
||||
<span class="result-card__count">
|
||||
采样点 {{ result?.samplingPointCount ?? 0 }} 个
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div class="result-card__viewport">
|
||||
<img class="result-card__image" :src="resultImageUrl" alt="靶样轮廓与采样点分析结果" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-else class="error-card">
|
||||
<div class="error-card__icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 64 64">
|
||||
<circle cx="32" cy="32" r="24" fill="none" stroke="currentColor" stroke-width="3" />
|
||||
<path d="M32 20v18M32 44v2" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" />
|
||||
</svg>
|
||||
</div>
|
||||
<h2>靶样轮廓识别失败</h2>
|
||||
<p>{{ errorMessage }}</p>
|
||||
<div class="error-card__actions">
|
||||
<button class="error-button error-button--ghost" type="button" @click="abortProcess">
|
||||
返回首页
|
||||
</button>
|
||||
<button class="error-button error-button--primary" type="button" @click="retry">
|
||||
重新分析
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="params-card">
|
||||
<header class="params-card__header">
|
||||
@@ -50,7 +173,7 @@ function abortProcess() {
|
||||
<div class="params-card__body">
|
||||
<div class="param-field">
|
||||
<span class="param-field__label">采样点数</span>
|
||||
<div class="param-field__value">5</div>
|
||||
<div class="param-field__value">{{ samplingPointCount }}</div>
|
||||
</div>
|
||||
|
||||
<div class="param-field">
|
||||
@@ -71,14 +194,22 @@ function abortProcess() {
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<div class="scan-progress">
|
||||
<ProgressStrip :progress="progress" :label="progressLabel" note="已规划 5 个采样点" />
|
||||
<div v-if="status !== 'error'" class="scan-progress">
|
||||
<div class="scan-progress__strip">
|
||||
<ProgressStrip :progress="progress" :label="progressLabel" :note="progressNote" />
|
||||
</div>
|
||||
|
||||
<StatusFooter
|
||||
icon="info"
|
||||
:items="['轮廓提取完成', '点位校验通过', '等待采集光谱']"
|
||||
/>
|
||||
<button
|
||||
v-if="status === 'done'"
|
||||
class="scan-next"
|
||||
type="button"
|
||||
@click="goSpectrum"
|
||||
>
|
||||
开始采集光谱
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<StatusFooter icon="info" :items="footerItems" />
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
@@ -101,6 +232,147 @@ function abortProcess() {
|
||||
justify-self: center;
|
||||
}
|
||||
|
||||
.result-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 1120px;
|
||||
max-width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
border: 1px solid #1e55a4;
|
||||
border-radius: 18px;
|
||||
background: #0b1220;
|
||||
box-shadow: 0 18px 44px rgba(31, 77, 147, 0.28);
|
||||
justify-self: center;
|
||||
}
|
||||
|
||||
.result-card__header {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 66px;
|
||||
padding: 0 26px;
|
||||
background: linear-gradient(180deg, #3d80e2 0%, #2f6fd0 100%);
|
||||
}
|
||||
|
||||
.result-card__header h2 {
|
||||
color: #fff;
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
text-shadow: 0 1px 3px rgba(16, 49, 101, 0.22);
|
||||
}
|
||||
|
||||
.result-card__count {
|
||||
padding: 5px 14px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
border-radius: 30px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
font-size: 17px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.result-card__viewport {
|
||||
display: grid;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
place-items: center;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.result-card__image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1120px;
|
||||
max-width: 100%;
|
||||
height: 100%;
|
||||
padding: 40px;
|
||||
border: 1px solid #d9e0e8;
|
||||
border-radius: 18px;
|
||||
background: #fff;
|
||||
box-shadow: var(--shadow-card);
|
||||
justify-self: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-card__icon {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
margin-bottom: 24px;
|
||||
border-radius: 50%;
|
||||
color: var(--red);
|
||||
background: #fdeeee;
|
||||
}
|
||||
|
||||
.error-card__icon svg {
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
}
|
||||
|
||||
.error-card h2 {
|
||||
color: #1f2937;
|
||||
font-size: 32px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.error-card p {
|
||||
margin-top: 16px;
|
||||
max-width: 760px;
|
||||
color: var(--muted);
|
||||
font-size: 20px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.error-card__actions {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
.error-button {
|
||||
width: 200px;
|
||||
height: 58px;
|
||||
border-radius: 12px;
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
|
||||
}
|
||||
|
||||
.error-button--ghost {
|
||||
border: 2px solid var(--line-strong);
|
||||
color: var(--ink-soft);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.error-button--ghost:hover {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.error-button--primary {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
|
||||
}
|
||||
|
||||
.error-button--primary:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
|
||||
}
|
||||
|
||||
.params-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -173,6 +445,33 @@ function abortProcess() {
|
||||
top: 900px;
|
||||
right: 44px;
|
||||
left: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
height: 54px;
|
||||
}
|
||||
|
||||
.scan-progress__strip {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.scan-next {
|
||||
flex: none;
|
||||
width: 280px;
|
||||
height: 54px;
|
||||
border-radius: 10px;
|
||||
color: #fff;
|
||||
font-size: 23px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.scan-next:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -109,6 +109,22 @@ function closeForm() {
|
||||
formOpen.value = false
|
||||
}
|
||||
|
||||
let backdropPressed = false
|
||||
|
||||
function onBackdropPointerDown(event: PointerEvent) {
|
||||
backdropPressed = event.target === event.currentTarget
|
||||
}
|
||||
|
||||
function onBackdropPointerUp(event: PointerEvent) {
|
||||
if (event.target !== event.currentTarget) backdropPressed = false
|
||||
}
|
||||
|
||||
function closeOnBackdrop(event: MouseEvent, action: () => void) {
|
||||
const shouldClose = backdropPressed && event.target === event.currentTarget
|
||||
backdropPressed = false
|
||||
if (shouldClose) action()
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
|
||||
@@ -254,7 +270,13 @@ onMounted(() => {
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="config-modal">
|
||||
<div v-if="formOpen" class="config-backdrop" @click.self="closeForm">
|
||||
<div
|
||||
v-if="formOpen"
|
||||
class="config-backdrop"
|
||||
@pointerdown="onBackdropPointerDown"
|
||||
@pointerup="onBackdropPointerUp"
|
||||
@click="closeOnBackdrop($event, closeForm)"
|
||||
>
|
||||
<section class="form-card" role="dialog" aria-modal="true" aria-label="系统参数表单">
|
||||
<h2>{{ editingId === null ? '新增系统参数' : '编辑系统参数' }}</h2>
|
||||
|
||||
@@ -316,7 +338,13 @@ onMounted(() => {
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="config-modal">
|
||||
<div v-if="deleting" class="config-backdrop" @click.self="cancelDelete">
|
||||
<div
|
||||
v-if="deleting"
|
||||
class="config-backdrop"
|
||||
@pointerdown="onBackdropPointerDown"
|
||||
@pointerup="onBackdropPointerUp"
|
||||
@click="closeOnBackdrop($event, cancelDelete)"
|
||||
>
|
||||
<section class="confirm-card" role="dialog" aria-modal="true" aria-label="删除确认">
|
||||
<h2>删除系统参数</h2>
|
||||
<p>
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
<PackageReference Include="LiteDB" Version="5.0.21" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.20.1" />
|
||||
<PackageReference Include="OpenCvSharp4" Version="4.10.0.20241108" />
|
||||
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.10.0.20241108" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using HardwareControl.Core.SampleAnalysis;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
|
||||
{
|
||||
/// <summary>
|
||||
/// 靶样轮廓与采样点分析服务:基准画面、靶样画面采集与分析。
|
||||
/// </summary>
|
||||
public interface ISampleAnalysisService
|
||||
{
|
||||
/// <summary>连续抓取多帧并取中值作为基准背景画面。</summary>
|
||||
Task<SampleBaselineInfo> CaptureBaselineAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>抓取当前最新画面作为靶样画面(需先采集基准画面)。</summary>
|
||||
SampleTargetInfo CaptureTarget();
|
||||
|
||||
/// <summary>基于基准画面和靶样画面提取轮廓并生成采样点。</summary>
|
||||
SampleAnalysisResult Analyze();
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
|
||||
Task ConnectAsync(CancellationToken ct = default);
|
||||
Task DisconnectAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>获取最近一帧图像快照;尚未收到帧或已断开时返回 null。</summary>
|
||||
CameraFrameSnapshot? GetLatestFrame();
|
||||
|
||||
event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
|
||||
event EventHandler<FrameArrivedEventArgs>? FrameArrived;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareControl.Core.SampleAnalysis;
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
using HardwareControl.Core.UsbCamera;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
/// <summary>
|
||||
/// 采集基准画面 / 靶样画面并调用 ONNX 模型分析。
|
||||
/// 作为单例使用,保存本次检测的画面。
|
||||
/// </summary>
|
||||
public sealed class SampleAnalysisService : ISampleAnalysisService
|
||||
{
|
||||
private const string SamplingPointConfigName = "camera_sampling_point";
|
||||
private const int DefaultSamplingPointCount = 5;
|
||||
private const int MaxSamplingPointCount = 100;
|
||||
|
||||
private readonly IUsbCameraService _camera;
|
||||
private readonly ISystemConfigService _systemConfig;
|
||||
private readonly TargetOutlineAnalyzer _analyzer;
|
||||
private readonly ILogger<SampleAnalysisService> _logger;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private IReadOnlyList<CameraFrameSnapshot>? _baseline;
|
||||
private CameraFrameSnapshot? _target;
|
||||
|
||||
public SampleAnalysisService(
|
||||
IUsbCameraService camera,
|
||||
ISystemConfigService systemConfig,
|
||||
TargetOutlineAnalyzer analyzer,
|
||||
ILogger<SampleAnalysisService> logger)
|
||||
{
|
||||
_camera = camera;
|
||||
_systemConfig = systemConfig;
|
||||
_analyzer = analyzer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task<SampleBaselineInfo> CaptureBaselineAsync(
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var frame = CaptureLatestFrame();
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_baseline = new[] { frame };
|
||||
_target = null;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"基准画面已采集:{Width}x{Height}", frame.Width, frame.Height);
|
||||
|
||||
return Task.FromResult(
|
||||
new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt));
|
||||
}
|
||||
|
||||
public SampleTargetInfo CaptureTarget()
|
||||
{
|
||||
var frame = CaptureLatestFrame();
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (_baseline is null || _baseline.Count == 0)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidState,
|
||||
"尚未采集基准画面,请等待相机画面稳定后再试");
|
||||
}
|
||||
|
||||
_target = frame;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height);
|
||||
|
||||
return new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt);
|
||||
}
|
||||
|
||||
public SampleAnalysisResult Analyze()
|
||||
{
|
||||
IReadOnlyList<CameraFrameSnapshot> baseline;
|
||||
CameraFrameSnapshot target;
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
baseline = _baseline ?? throw new HardwareException(
|
||||
HardwareErrorKind.InvalidState,
|
||||
"尚未采集基准画面,请返回样品放置界面重新检测");
|
||||
|
||||
target = _target ?? throw new HardwareException(
|
||||
HardwareErrorKind.InvalidState,
|
||||
"尚未采集靶样画面,请返回样品放置界面重新检测");
|
||||
}
|
||||
|
||||
var pointCount = GetSamplingPointCount();
|
||||
_logger.LogInformation("开始靶样轮廓分析,采样点数:{PointCount}", pointCount);
|
||||
|
||||
var result = _analyzer.Analyze(baseline, target, pointCount);
|
||||
|
||||
_logger.LogInformation(
|
||||
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个",
|
||||
result.Width,
|
||||
result.Height,
|
||||
result.SamplingPointCount);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private CameraFrameSnapshot CaptureLatestFrame() =>
|
||||
_camera.GetLatestFrame() ?? throw new HardwareException(
|
||||
HardwareErrorKind.NotConnected,
|
||||
"相机尚未产生画面,请确认相机已连接");
|
||||
|
||||
private int GetSamplingPointCount()
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = _systemConfig
|
||||
.GetAll()
|
||||
.FirstOrDefault(c => string.Equals(
|
||||
c.ConfigName, SamplingPointConfigName, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (int.TryParse(config?.ConfigValue, out var count) && count > 0)
|
||||
{
|
||||
return Math.Min(count, MaxSamplingPointCount);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex, "读取系统参数 {ConfigName} 失败,使用默认采样点数",
|
||||
SamplingPointConfigName);
|
||||
}
|
||||
|
||||
return DefaultSamplingPointCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,12 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
public class UsbCameraService : IUsbCameraService
|
||||
{
|
||||
// 系统参数中保存相机硬件 ID 的配置名称
|
||||
private const string CameraVidConfigName = "camera_vid";
|
||||
|
||||
private readonly UsbCameraOptions _options;
|
||||
private readonly ILogger<UsbCameraService> _logger;
|
||||
private readonly ISystemConfigService? _systemConfig;
|
||||
|
||||
// 串行化所有对 FlashCap 设备对象的访问
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
@@ -23,6 +27,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
private long _lastFrameAtTicks;
|
||||
private long _framesReceived;
|
||||
private long _connectedAtTicks;
|
||||
private volatile CameraFrameSnapshot? _latestFrame;
|
||||
|
||||
public bool IsConnected => _connected;
|
||||
|
||||
@@ -41,15 +46,57 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
|
||||
public long FramesReceived => Interlocked.Read(ref _framesReceived);
|
||||
|
||||
public CameraFrameSnapshot? GetLatestFrame() => _latestFrame;
|
||||
|
||||
public event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
|
||||
public event EventHandler<FrameArrivedEventArgs>? FrameArrived;
|
||||
|
||||
public UsbCameraService(
|
||||
IOptions<UsbCameraOptions> options,
|
||||
ILogger<UsbCameraService> logger)
|
||||
ILogger<UsbCameraService> logger,
|
||||
ISystemConfigService? systemConfig = null)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_systemConfig = systemConfig;
|
||||
RefreshCameraVid();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从系统参数读取 camera_vid 并写入 <see cref="UsbCameraOptions"/>。
|
||||
/// 读取失败时保留原有配置,不影响相机连接流程。
|
||||
/// </summary>
|
||||
private void RefreshCameraVid()
|
||||
{
|
||||
if (_systemConfig is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var config = _systemConfig
|
||||
.GetAll()
|
||||
.FirstOrDefault(c => string.Equals(
|
||||
c.ConfigName, CameraVidConfigName, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
var value = config?.ConfigValue?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(value) ||
|
||||
string.Equals(_options.CameraVid, value, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_options.CameraVid = value;
|
||||
_logger.LogInformation(
|
||||
"相机选择使用系统参数 {ConfigName}={CameraVid}",
|
||||
CameraVidConfigName,
|
||||
value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", CameraVidConfigName);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 连接 ----------
|
||||
@@ -72,6 +119,11 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
try
|
||||
{
|
||||
// 每次连接前重新读取系统参数,管理界面修改 camera_vid 后重连即可生效
|
||||
RefreshCameraVid();
|
||||
|
||||
_latestFrame = null;
|
||||
|
||||
var devices = new CaptureDevices();
|
||||
var descriptors = devices.EnumerateDescriptors().ToList();
|
||||
|
||||
@@ -117,6 +169,15 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
Interlocked.Increment(ref _framesReceived);
|
||||
Interlocked.Exchange(ref _lastFrameAtTicks, capturedAt.UtcTicks);
|
||||
|
||||
// 缓存独立副本,供后台按需抓帧(事件回调仍使用同一份数据)
|
||||
_latestFrame = new CameraFrameSnapshot(
|
||||
image,
|
||||
format.Width,
|
||||
format.Height,
|
||||
format.MimeType,
|
||||
capturedAt,
|
||||
frameIndex);
|
||||
|
||||
FrameArrived?.Invoke(
|
||||
this,
|
||||
new FrameArrivedEventArgs(
|
||||
@@ -144,6 +205,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
_connected = false;
|
||||
_frameFormat = null;
|
||||
_deviceName = null;
|
||||
_latestFrame = null;
|
||||
_device?.Dispose();
|
||||
_device = null;
|
||||
throw;
|
||||
@@ -153,6 +215,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
_connected = false;
|
||||
_frameFormat = null;
|
||||
_deviceName = null;
|
||||
_latestFrame = null;
|
||||
_device?.Dispose();
|
||||
_device = null;
|
||||
|
||||
@@ -165,6 +228,26 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
private CaptureDeviceDescriptor SelectDescriptor(
|
||||
List<CaptureDeviceDescriptor> descriptors)
|
||||
{
|
||||
// 优先按系统参数 camera_vid 匹配设备的 Identity。
|
||||
// Identity 在不同设备/平台上大小写不一致,统一转大写后比较。
|
||||
var cameraVid = _options.CameraVid?.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(cameraVid))
|
||||
{
|
||||
var target = cameraVid.ToUpperInvariant();
|
||||
var matched = descriptors.FirstOrDefault(d =>
|
||||
{
|
||||
var identity = d.Identity?.ToString();
|
||||
return identity is not null &&
|
||||
identity.ToUpperInvariant().Contains(target);
|
||||
});
|
||||
|
||||
if (matched != null) return matched;
|
||||
|
||||
_logger.LogWarning(
|
||||
"未找到 Identity 包含 {CameraVid} 的相机,回退到名称关键词选择",
|
||||
cameraVid);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_options.DeviceNameKeyword))
|
||||
{
|
||||
var matched = descriptors.FirstOrDefault(
|
||||
@@ -221,6 +304,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
CancelReconnectWatcher();
|
||||
await StopDeviceAsync();
|
||||
_latestFrame = null;
|
||||
|
||||
if (_connected)
|
||||
{
|
||||
@@ -385,6 +469,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
|
||||
|
||||
_connected = false;
|
||||
Interlocked.Exchange(ref _connectedAtTicks, 0);
|
||||
_latestFrame = null;
|
||||
await StopDeviceAsync();
|
||||
StatusChanged?.Invoke(this, new(false, message));
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,283 @@
|
||||
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,53 @@
|
||||
namespace HardwareControl.Core.SampleAnalysis
|
||||
{
|
||||
/// <summary>靶样 ONNX 分割模型配置。</summary>
|
||||
public sealed class OnnxSegmentationOptions
|
||||
{
|
||||
public const string SectionName = "SampleAnalysis:Onnx";
|
||||
|
||||
/// <summary>模型路径;相对路径基于程序运行目录。</summary>
|
||||
public string? ModelPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型目录;相对路径基于程序运行目录。
|
||||
/// 目录内按文件名前面的数字从小到大依次尝试,直到某个模型识别成功。
|
||||
/// </summary>
|
||||
public string? ModelDirectory { get; set; } = "Models";
|
||||
|
||||
public int InputWidth { get; set; } = 640;
|
||||
|
||||
public int InputHeight { get; set; } = 640;
|
||||
|
||||
/// <summary>YOLO 分割模型的目标置信度阈值。</summary>
|
||||
public double ConfidenceThreshold { get; set; } = 0.25;
|
||||
|
||||
/// <summary>
|
||||
/// 模型置信度低于该值时,使用 OpenCV 背景差分兜底识别轮廓。
|
||||
/// </summary>
|
||||
public double FallbackConfidenceThreshold { get; set; } = 0.6;
|
||||
|
||||
/// <summary>概率型二值 mask 的阈值;logits 输出会自动改用 0。</summary>
|
||||
public double MaskThreshold { get; set; } = 0.5;
|
||||
|
||||
/// <summary>像素归一化系数。</summary>
|
||||
public double Scale { get; set; } = 1.0 / 255.0;
|
||||
|
||||
/// <summary>是否交换 R/B 通道(大多数 ONNX 模型需要 true)。</summary>
|
||||
public bool SwapRB { get; set; } = true;
|
||||
|
||||
/// <summary>Letterbox 填充值。</summary>
|
||||
public double LetterboxPadValue { get; set; } = 114;
|
||||
|
||||
/// <summary>轮廓面积占图像的最小比例。</summary>
|
||||
public double MinAreaRatio { get; set; } = 0.0005;
|
||||
|
||||
/// <summary>轮廓面积占图像的最大比例。</summary>
|
||||
public double MaxAreaRatio { get; set; } = 0.98;
|
||||
|
||||
/// <summary>
|
||||
/// 采样点距轮廓边缘的最小比例(相对于轮廓外接矩形短边)。
|
||||
/// 防止激光点过于贴近靶样边缘而脱离靶面。
|
||||
/// </summary>
|
||||
public double SamplingMarginRatio { get; set; } = 0.1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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>
|
||||
public sealed record SamplePoint(int X, int Y);
|
||||
|
||||
/// <summary>靶样轮廓与采样点分析结果。</summary>
|
||||
public sealed record SampleAnalysisResult(
|
||||
byte[] ImageData,
|
||||
string MimeType,
|
||||
int Width,
|
||||
int Height,
|
||||
int SamplingPointCount,
|
||||
IReadOnlyList<SamplePoint> SamplingPoints);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
namespace HardwareControl.Core.UsbCamera
|
||||
{
|
||||
/// <summary>
|
||||
/// 相机最近一帧图像快照,用于后台图像处理。
|
||||
/// </summary>
|
||||
public sealed record CameraFrameSnapshot(
|
||||
byte[] ImageData,
|
||||
int Width,
|
||||
int Height,
|
||||
string MimeType,
|
||||
DateTimeOffset CapturedAt,
|
||||
long FrameIndex);
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
/// </summary>
|
||||
public class UsbCameraOptions
|
||||
{
|
||||
// 相机的硬件 ID,来自系统参数 camera_vid;匹配 CaptureDeviceDescriptor.Identity
|
||||
// 为 null 时按 DeviceNameKeyword 或第一个设备选择
|
||||
public string? CameraVid { get; set; }
|
||||
|
||||
// 设备名称关键词,null 表示取第一个设备
|
||||
public string? DeviceNameKeyword { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using HardwareControl.Core;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareWeb.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HardwareWeb.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// 靶样轮廓识别与采样点规划接口。
|
||||
/// 流程:采集基准画面 -> 采集靶样画面 -> 分析并返回处理后的图像。
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/sample")]
|
||||
public class SampleAnalysisController : ControllerBase
|
||||
{
|
||||
private readonly ISampleAnalysisService _service;
|
||||
private readonly ILogger<SampleAnalysisController> _logger;
|
||||
|
||||
public SampleAnalysisController(
|
||||
ISampleAnalysisService service,
|
||||
ILogger<SampleAnalysisController> logger)
|
||||
{
|
||||
_service = service;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>连续抓取多帧并取中值作为基准背景画面。</summary>
|
||||
[HttpPost("baseline")]
|
||||
[ProducesResponseType(typeof(SampleBaselinePayload), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CaptureBaseline(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(SampleBaselinePayload.From(
|
||||
await _service.CaptureBaselineAsync(ct)));
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return HardwareError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>抓取当前最新画面作为靶样画面。</summary>
|
||||
[HttpPost("target")]
|
||||
[ProducesResponseType(typeof(SampleTargetPayload), StatusCodes.Status200OK)]
|
||||
public IActionResult CaptureTarget()
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(SampleTargetPayload.From(_service.CaptureTarget()));
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return HardwareError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>提取靶样轮廓、绘制采样点并返回处理后的 JPEG 图像。</summary>
|
||||
[HttpPost("analyze")]
|
||||
[ProducesResponseType(typeof(SampleAnalysisPayload), StatusCodes.Status200OK)]
|
||||
public IActionResult Analyze()
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(SampleAnalysisPayload.From(_service.Analyze()));
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return HardwareError(ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "靶样轮廓分析失败");
|
||||
return StatusCode(
|
||||
StatusCodes.Status500InternalServerError,
|
||||
new { error = "AnalyzeFailed", message = "靶样轮廓分析失败,请重试" });
|
||||
}
|
||||
}
|
||||
|
||||
private IActionResult HardwareError(HardwareException ex)
|
||||
{
|
||||
var statusCode = ex.Kind switch
|
||||
{
|
||||
HardwareErrorKind.InvalidArgument => StatusCodes.Status400BadRequest,
|
||||
HardwareErrorKind.NotConnected => StatusCodes.Status409Conflict,
|
||||
HardwareErrorKind.InvalidState => StatusCodes.Status409Conflict,
|
||||
HardwareErrorKind.Timeout => StatusCodes.Status504GatewayTimeout,
|
||||
_ => StatusCodes.Status500InternalServerError,
|
||||
};
|
||||
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError(ex, "靶样分析接口失败:{Message}", ex.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("靶样分析接口失败:{Message}", ex.Message);
|
||||
}
|
||||
|
||||
return new ObjectResult(new
|
||||
{
|
||||
error = ex.Kind.ToString(),
|
||||
message = ex.Message
|
||||
})
|
||||
{
|
||||
StatusCode = statusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,19 @@
|
||||
<ProjectReference Include="..\HardwareControl.Core\HardwareControl.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
ONNX 分割模型放在 Models 目录下,构建时自动复制到输出目录。
|
||||
默认加载路径为 Models 目录(见 appsettings.json)。
|
||||
-->
|
||||
<ItemGroup>
|
||||
<Content Include="Models\**\*.onnx" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="..\HardwareControl.Core\Models\**\*.onnx" Link="Models\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Remove="..\HardwareControl.Core\Models\3.medicinals_expert_logits.onnx" />
|
||||
<Content Remove="..\HardwareControl.Core\Models\4.highvalue_expert_logits.onnx" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
HardwareControl.Core 通过裸 <Reference> 引用 ArisSharp.dll。
|
||||
这里再显式引用一次,确保 ArisSharp 出现在 HardwareWeb.deps.json 中;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using HardwareControl.Core.SampleAnalysis;
|
||||
|
||||
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>
|
||||
public sealed record SamplePointPayload(int X, int Y);
|
||||
|
||||
/// <summary>靶样轮廓与采样点分析结果。</summary>
|
||||
public sealed record SampleAnalysisPayload(
|
||||
string ImageBase64,
|
||||
string MimeType,
|
||||
int Width,
|
||||
int Height,
|
||||
int SamplingPointCount,
|
||||
IReadOnlyList<SamplePointPayload> SamplingPoints)
|
||||
{
|
||||
public static SampleAnalysisPayload From(SampleAnalysisResult result) =>
|
||||
new(
|
||||
Convert.ToBase64String(result.ImageData),
|
||||
result.MimeType,
|
||||
result.Width,
|
||||
result.Height,
|
||||
result.SamplingPointCount,
|
||||
result.SamplingPoints
|
||||
.Select(point => new SamplePointPayload(point.X, point.Y))
|
||||
.ToList());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using HardwareControl.Core.HardwareServiceImpl;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareControl.Core.SampleAnalysis;
|
||||
using HardwareControl.Core.Spectrometer;
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
using HardwareControl.Core.UsbCamera;
|
||||
@@ -48,6 +49,13 @@ builder.Services.AddSingleton(_ => new SystemConfigRepository(systemConfigDbPath
|
||||
builder.Services.AddSingleton<ISystemConfigService, SystemConfigService>();
|
||||
builder.Services.AddSingleton<AdminAccessService>();
|
||||
|
||||
// 8. 靶样轮廓识别与采样点规划(ONNX 模型分割)
|
||||
builder.Services.Configure<OnnxSegmentationOptions>(
|
||||
builder.Configuration.GetSection(OnnxSegmentationOptions.SectionName));
|
||||
builder.Services.AddSingleton<BackgroundDiffSegmenter>();
|
||||
builder.Services.AddSingleton<TargetOutlineAnalyzer>();
|
||||
builder.Services.AddSingleton<ISampleAnalysisService, SampleAnalysisService>();
|
||||
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
|
||||
@@ -36,5 +36,16 @@
|
||||
"SystemSetting": {
|
||||
"DatabasePath": null,
|
||||
"AdminPassword": "flzx3QC!1"
|
||||
},
|
||||
"SampleAnalysis": {
|
||||
"Onnx": {
|
||||
"ModelDirectory": "Models",
|
||||
"InputWidth": 640,
|
||||
"InputHeight": 640,
|
||||
"ConfidenceThreshold": 0.25,
|
||||
"FallbackConfidenceThreshold": 0.6,
|
||||
"MaskThreshold": 0.5,
|
||||
"SamplingMarginRatio": 0.1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user