- 页面:pose-hub 选择动作,pose-coach 跟练(教练小甄示范 + 摄像头动作识别计数) - 动作:徒手深蹲、原地高抬腿、低冲击开合、站姿侧平举 - VisionKit 人体识别,按动作幅度计数、评分、纠错;没有摄像头或识别不可用时自动进入领练模式 - 教练逐帧动画:分包内置 600px 帧,COS 高清帧全部加载完后无缝切换 - 语音报数与口令(WechatSI),舒缓背景音乐(COS,教练说话时自动压低,可关闭) - 逻辑单测:npm run test:pose
183 lines
6.1 KiB
TypeScript
183 lines
6.1 KiB
TypeScript
/**
|
||
* 摄像头取帧 + VisionKit 人体关键点检测
|
||
*
|
||
* 方案:<camera> 负责预览(原生、流畅),CameraContext.onCameraFrame 拿 RGBA 帧,
|
||
* 节流后交给 VKSession.detectBody(mode 2,手动传图),结果通过 updateAnchors 回调。
|
||
* 这样不需要自己用 WebGL 渲染相机画面;<camera> 放在哪个组件里都可以(一个页面只有一个摄像头)。
|
||
*
|
||
* 要求:微信基础库 >= 2.28.0;非微信端或不支持的机型会返回 unsupported。
|
||
*/
|
||
import { ref, shallowRef, onUnmounted } from 'vue'
|
||
import { anchorToPose, smoothPose, type Pose } from './keypoints.ts'
|
||
|
||
export type CameraStatus = 'idle' | 'starting' | 'running' | 'unsupported' | 'denied' | 'error'
|
||
|
||
/** 检测间隔:约 10fps,兼顾流畅与发热 */
|
||
const DETECT_INTERVAL_MS = 90
|
||
/** 检测请求超时:没有回调视为画面里没人 */
|
||
const DETECT_TIMEOUT_MS = 600
|
||
/** 连续多久没检测到人,清空姿态 */
|
||
const LOST_AFTER_MS = 800
|
||
|
||
type FrameInfo = { width: number; height: number }
|
||
|
||
export function usePoseCamera(onPose?: (pose: Pose | null) => void) {
|
||
const status = ref<CameraStatus>('idle')
|
||
const errorText = ref('')
|
||
const pose = shallowRef<Pose | null>(null)
|
||
const frame = ref<FrameInfo>({ width: 480, height: 640 })
|
||
/** 实际检测帧率,调试用 */
|
||
const fps = ref(0)
|
||
|
||
let session: any = null
|
||
let listener: any = null
|
||
let pending = false
|
||
let pendingTimer: ReturnType<typeof setTimeout> | null = null
|
||
let lastSent = 0
|
||
let lastSeen = 0
|
||
let sentFrame: FrameInfo = { width: 0, height: 0 }
|
||
let fpsCount = 0
|
||
let fpsTimer: ReturnType<typeof setInterval> | null = null
|
||
|
||
function emit(next: Pose | null) {
|
||
pose.value = next
|
||
onPose?.(next)
|
||
}
|
||
|
||
function clearPending() {
|
||
pending = false
|
||
if (pendingTimer) {
|
||
clearTimeout(pendingTimer)
|
||
pendingTimer = null
|
||
}
|
||
}
|
||
|
||
function handleAnchors(anchors: any[]) {
|
||
clearPending()
|
||
fpsCount += 1
|
||
const now = Date.now()
|
||
// 画面里多人时取检测框最大的那个
|
||
const best = (anchors || []).slice().sort((a, b) => area(b) - area(a))[0]
|
||
const next = best ? anchorToPose(best, sentFrame.width, sentFrame.height, now) : null
|
||
if (next) {
|
||
lastSeen = now
|
||
emit(smoothPose(pose.value, next))
|
||
} else if (now - lastSeen > LOST_AFTER_MS) {
|
||
emit(null)
|
||
}
|
||
}
|
||
|
||
function area(a: any) {
|
||
const s = a?.size
|
||
if (!s) return 0
|
||
return Array.isArray(s) ? s[0] * s[1] : (s.width || 0) * (s.height || 0)
|
||
}
|
||
|
||
/** 相机组件 initdone 后调用 */
|
||
function start() {
|
||
if (status.value === 'running' || status.value === 'starting') return
|
||
status.value = 'starting'
|
||
// #ifdef MP-WEIXIN
|
||
startVisionKit()
|
||
// #endif
|
||
// #ifndef MP-WEIXIN
|
||
status.value = 'unsupported'
|
||
// #endif
|
||
}
|
||
|
||
function startVisionKit() {
|
||
try {
|
||
const w: any = wx
|
||
if (typeof w.createVKSession !== 'function' || (w.isVKSupport && !w.isVKSupport('v1'))) {
|
||
status.value = 'unsupported'
|
||
return
|
||
}
|
||
session = w.createVKSession({ track: { body: { mode: 2 } }, version: 'v1' })
|
||
session.on('updateAnchors', (anchors: any[]) => handleAnchors(anchors))
|
||
session.on('removeAnchors', () => handleAnchors([]))
|
||
session.start((err: any) => {
|
||
if (err) {
|
||
status.value = 'unsupported'
|
||
errorText.value = String(err?.errMsg || err)
|
||
return
|
||
}
|
||
startFrames()
|
||
})
|
||
} catch (e: any) {
|
||
status.value = 'unsupported'
|
||
errorText.value = String(e?.message || e)
|
||
}
|
||
}
|
||
|
||
function startFrames() {
|
||
const cam: any = uni.createCameraContext()
|
||
if (!cam?.onCameraFrame) {
|
||
status.value = 'unsupported'
|
||
return
|
||
}
|
||
listener = cam.onCameraFrame((f: { data: ArrayBuffer; width: number; height: number }) => {
|
||
const now = Date.now()
|
||
if (pending || now - lastSent < DETECT_INTERVAL_MS || !session) return
|
||
if (frame.value.width !== f.width || frame.value.height !== f.height) {
|
||
frame.value = { width: f.width, height: f.height }
|
||
}
|
||
pending = true
|
||
lastSent = now
|
||
sentFrame = { width: f.width, height: f.height }
|
||
pendingTimer = setTimeout(() => handleAnchors([]), DETECT_TIMEOUT_MS)
|
||
try {
|
||
session.detectBody({
|
||
frameBuffer: f.data,
|
||
width: f.width,
|
||
height: f.height,
|
||
scoreThreshold: 0.5,
|
||
// 0 表示输入来自视频连续帧,算法会做帧间跟踪
|
||
sourceType: 0,
|
||
})
|
||
} catch (e) {
|
||
clearPending()
|
||
}
|
||
})
|
||
listener.start({
|
||
success: () => {
|
||
status.value = 'running'
|
||
fpsTimer = setInterval(() => {
|
||
fps.value = fpsCount
|
||
fpsCount = 0
|
||
}, 1000)
|
||
},
|
||
fail: (e: any) => {
|
||
status.value = 'error'
|
||
errorText.value = String(e?.errMsg || e)
|
||
},
|
||
})
|
||
}
|
||
|
||
function stop() {
|
||
clearPending()
|
||
try {
|
||
listener?.stop?.()
|
||
} catch (e) {}
|
||
listener = null
|
||
try {
|
||
session?.stop?.()
|
||
session?.destroy?.()
|
||
} catch (e) {}
|
||
session = null
|
||
if (fpsTimer) clearInterval(fpsTimer)
|
||
fpsTimer = null
|
||
if (status.value === 'running' || status.value === 'starting') status.value = 'idle'
|
||
pose.value = null
|
||
}
|
||
|
||
/** <camera @error>:通常是用户拒绝了摄像头权限 */
|
||
function onCameraError(e: any) {
|
||
status.value = 'denied'
|
||
errorText.value = String(e?.detail?.errMsg || '')
|
||
}
|
||
|
||
onUnmounted(stop)
|
||
|
||
return { status, errorText, pose, frame, fps, start, stop, onCameraError }
|
||
}
|