【HarmonyOS 5】VisionKit人臉活體檢測詳解
##鴻蒙開發能力 ##HarmonyOS SDK應用服務##鴻蒙金融類應用 (金融理財#
一、VisionKit人臉活體檢測是什么?
VisionKit是HamronyOS提供的場景化視覺服務工具包。
華為將常見的解決方案,通常需要三方應用使用SDK進行集成。華為以Kit的形式集成在HarmoyOS系統中,方便三方應用快速開發和賦能。
而VisionKit中包含人臉活體檢測的功能接口interactiveLiveness 。人臉活體檢測見名知意,主要是為了檢測當前人是否為活人本人,而不是照片,硅膠面具,AI視頻仿真的可能。
雖然該算法接口已通過中金金融(CECA)認證。但是官方還是建議添加額外的安全措施后,在使用該人臉檢測接口,盡量不要直接使用在高風險性的支付和金融場景中。推薦在低危險場景,例如登錄,考勤,實名認證等業務場景進行使用。
需要注意的是**,人臉活體檢測,不支持模擬器和預覽器。**
詳情參見官方接口:
[https://developer.huawei.com/consumer/cn/doc/harmonyos-references/vision-interactive-liveness] [https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/vision-interactiveliveness]
二、人臉活體檢測如何使用?
人臉活體檢測功能interactiveLiveness ,起始版本為 5.0.0 (API12),可通過@kit.VisionKit模塊導入,支持動作活體檢測模式(INTERACTIVE_MODE),動作數量可配置為 3 或 4 個,包含點頭、張嘴、眨眼等 6 種動作。
通過InteractiveLivenessConfig配置檢測模式、跳轉路徑、語音播報等參數,提供startLivenessDetection和getInteractiveLivenessResult接口,能抵御照片、視頻等GJ,適用于身份驗證場景,需申請ohos.permission.CAMERA相機權限,錯誤碼可參考 Vision Kit 錯誤碼文檔。
Vision Kit 錯誤碼文檔
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/vision-error-code
1. 核心接口為人臉頁面喚起接口:
interactiveLiveness.startLivenessDetection,該接口需要配置config進行設置人臉的模式,動作等操作。
(1) Promise 方式:僅返回跳轉結果(boolean)。
interactiveLiveness.startLivenessDetection(routerOptions).then((DetectState: boolean) = > {
hilog.info(0x0001, "LivenessCollectionIndex", `Succeeded in jumping.`);
}).catch((err: BusinessError) = > {
hilog.error(0x0001, "LivenessCollectionIndex", `Failed to jump. Code:${err.code},message:${err.message}`);
})
(2) Promise + 回調方式:同時返回跳轉結果和檢測結果(僅適用于 BACK_MODE)。
interactiveLiveness.startLivenessDetection(routerOptions, (err: BusinessError, result: interactiveLiveness.InteractiveLivenessResult | undefined) = > {
if(err.code !== 0 && !result) {
hilog.error(0x0001, "LivenessCollectionIndex", `Failed to detect. Code:${err.code},message:${err.message}`);
return;
}
hilog.info(0x0001, 'LivenessCollectionIndex', `Succeeded in detecting result:${result}`);
})
2. InteractiveLivenessConfig配置接口:
調用人臉活體檢測,需要填入該配置對象,進行相關設置,參數見以下表格:
檢測模式(DetectionMode)
名稱 值 說明 SILENT_MODE "SILENT_MODE" 靜默活體檢測(暫未支持) INTERACTIVE_MODE "INTERACTIVE_MODE" 動作活體檢測(默認模式) 動作數量(ActionsNumber)
名稱 值 說明 ONE_ACTION 1 隨機1個動作(暫未支持) TWO_ACTION 2 隨機2個動作(暫未支持) THREE_ACTION 3 隨機3個動作([眨眼,注視]不同時存在且不相鄰,相鄰動作不重復) FOUR_ACTION 4 隨機4個動作(眨眼僅1次,注視最多1次,[眨眼,注視]不相鄰,相鄰動作不重復) 跳轉模式(RouteRedirectionMode)
名稱 值 說明 BACK_MODE "back" 檢測完成后調用router.back返回上一頁 REPLACE_MODE "replace" 檢測完成后調用router.replaceUrl跳轉(默認模式) 配置項(InteractiveLivenessConfig)
名稱 類型 必填/可選 說明 isSilentMode DetectionMode 必填 檢測模式(默認INTERACTIVE_MODE) actionsNum ActionsNumber 可選 動作數量(3或4,默認3) successfulRouteUrl string 可選 檢測成功跳轉路徑(未填則用系統默認頁面) failedRouteUrl string 可選 檢測失敗跳轉路徑(未填則用系統默認頁面) routeMode RouteRedirectionMode 可選 跳轉模式(默認REPLACE_MODE) challenge string 可選 安全攝像頭場景挑戰值(16-128位,空值表示不使用) speechSwitch boolean 可選 語音播報開關(默認開啟) isPrivacyMode boolean 可選 隱私模式(需申請ohos.permission.PRIVACY_WINDOW權限,默認關閉)
人臉活體檢測的配置項對象除了isSilentMode是必填,其他屬性均為可選:
import { interactiveLiveness } from '@kit.VisionKit';
let isSilentMode = "INTERACTIVE_MODE" as interactiveLiveness.DetectionMode;
let routeMode = "replace" as interactiveLiveness.RouteRedirectionMode;
let actionsNum = 3 as interactiveLiveness.ActionsNumber;
let routerOptions: interactiveLiveness.InteractiveLivenessConfig= {
isSilentMode: isSilentMode,
routeMode: routeMode,
actionsNum: actionsNum,
failedRouteUrl: "pages/FailPage",
successfulRouteUrl: "pages/SuccessPage"
}
3. getInteractiveLivenessResult獲取人臉活體檢測結果:
在調用人臉活體檢測成功后,可通過該接口獲取檢測結果。結果內容如下表格所示:
名稱 | 類型 | 只讀 | 可選 | 說明 |
---|---|---|---|---|
livenessType | LivenessType | 是 | 否 | 活體檢測模式,值包括:-0 (INTERACTIVE_LIVENESS,動作活體檢測)-1 (SILENT_LIVENESS,靜默活體檢測,暫未支持)-2 (NOT_LIVENESS,非活體) |
mPixelMap | image.PixelMap | 是 | 是 | 檢測成功后返回的最具有活體特征的圖片(如包含人臉關鍵點的特征圖),檢測失敗時無此數據。 |
securedImageBuffer | ArrayBuffer | 是 | 是 | 安全攝像頭場景下返回的安全流數據(加密后的圖像特征數據),非安全場景無此數據。 |
certificate | Array | 是 | 是 | 安全攝像頭場景下返回的證書鏈(用于驗證安全流的合法性),非安全場景無此數據。 |
let successResult = interactiveLiveness.getInteractiveLivenessResult();
successResult.then(data = > {
hilog.info(0x0001, "LivenessCollectionIndex", `Succeeded in detecting.`);
}).catch((err: BusinessError) = > {
hilog.error(0x0001, "LivenessCollectionIndex", `Failed to detect. Code:${err.code},message:${err.message}`);
})
三、DEMO源碼示例
import { interactiveLiveness } from '@kit.VisionKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { abilityAccessCtrl, common } from '@kit.AbilityKit';
@Entry
@Component
struct FaceLivenessDemo {
@State userGrant: boolean = false // 權限狀態
@State detectionResult: string = "" // 檢測結果展示
@State actionCount: interactiveLiveness.ActionsNumber = interactiveLiveness.ActionsNumber.THREE_ACTION; // 動作數量(3或4)
@State speechEnabled: boolean = true // 語音播報開關
// 表示人臉活體檢測完成后使用router.back返回到上一頁。
@State routeMode: interactiveLiveness.RouteRedirectionMode = interactiveLiveness.RouteRedirectionMode.BACK_MODE; // 跳轉模式
// 權限申請邏輯
private async requestPermissions() {
const context = getContext() as common.UIAbilityContext;
const atManager = abilityAccessCtrl.createAtManager();
const results = await atManager.requestPermissionsFromUser(context, ["ohos.permission.CAMERA"]);
this.userGrant = results.authResults.every(status = > status === 0);
}
// 檢測配置生成
private generateDetectionConfig(): interactiveLiveness.InteractiveLivenessConfig {
return {
// 表示的是人臉活體檢測模式,默認動作活體檢測模式。
// INTERACTIVE_MODE表示動作活體檢測模式。
isSilentMode: interactiveLiveness.DetectionMode.INTERACTIVE_MODE,
// 表示動作活體檢測的動作數量,數量范圍3或4個,默認3個動作。隨機生成,規則如下:
//
// 當actionsNum=3時,[眨眼,注視]組合中的動作元素不會同時存在并且相鄰的動作元素不會相同。
//
// 當actionsNum=4時,眨眼動作元素有且僅有1次,注視動作元素最多出現1次,[眨眼,注視]組合中的動作元素不會相鄰,相鄰的動作元素不會相同。
//
// 該參數只有當isSilentMode是INTERACTIVE_MODE的時候有效。
actionsNum: this.actionCount,
// 表示人臉活體檢測成功后跳轉的頁面路徑。如果不填,系統有默認的檢測成功頁面。
// successfulRouteUrl: "pages/result/success", // 自定義成功跳轉路徑(需提前創建頁面)
// 表示人臉活體檢測失敗后跳轉的頁面路徑。如果不填,系統有默認的檢測失敗頁面。
// failedRouteUrl: "pages/result/fail", // 自定義失敗跳轉路徑(需提前創建頁面)
routeMode: this.routeMode, // 跳轉模式
// 語音播報的開關。
//
// true表示開啟語音播報。
// false表示關閉語音播報。
// 默認開啟語音播報。
speechSwitch: this.speechEnabled, // 語音播報控制
// 挑戰值。僅用于安全攝像頭場景(對應initializeAttestContext方法中的“userData”字段)的活體檢測。
//
// 使用安全攝像頭場景的前提需要開通Device Security服務。
//
// 長度范圍是16-128之間(challenge傳空或者undefined表示不使用安全攝像頭)。
// challenge: "自定義挑戰值1234567890abcdef", // 安全攝像頭場景可選
// 是否設置隱私模式。
//
// true:設置隱私模式。
// false:不設置隱私模式。
// 默認值為false。
// isPrivacyMode: true // 隱私模式需額外權限 當設置隱私模式時,需要申請ohos.permission.PRIVACY_WINDOW權限。
};
}
// 啟動檢測
private async startDetection() {
if (!this.userGrant) {
this.detectionResult = "請先申請相機權限";
return;
}
const config = this.generateDetectionConfig();
try {
const jumpSuccess = await interactiveLiveness.startLivenessDetection(config);
if (jumpSuccess) {
hilog.info(0x0001, "Detection", "跳轉檢測頁面成功");
// 檢測完成后獲取結果(需在返回頁面時調用)
const result = await interactiveLiveness.getInteractiveLivenessResult();
this.processResult(result);
}
} catch (err) {
const error = err as BusinessError;
hilog.error(0x0001, "Detection", `檢測失敗: 錯誤碼${error.code}, 信息${error.message}`);
this.detectionResult = `檢測異常:錯誤碼${error.code}`;
}
}
// 結果處理
private processResult(result: interactiveLiveness.InteractiveLivenessResult) {
let status = "";
let livenessType = result.livenessType;
switch (livenessType) {
case 0: // 動作活體檢測成功
status = "活體檢測通過";
// 可在此處處理特征圖片或安全數據
break;
case 2: // 非活體
status = "檢測到非活體(照片/視頻GJ)";
break;
default:
status = "檢測結果異常";
}
this.detectionResult = status;
}
build() {
Column({ space: 40 })
{
// 權限申請按鈕
Button(this.userGrant ? "權限已授權" : "申請相機權限")
.fontSize(18)
.margin(10)
.padding(12)
.backgroundColor(this.userGrant ? Color.Green : Color.Blue)
.onClick(() = > this.requestPermissions())
// 動作數量選擇
Row({ space: 20 }) {
Text("動作數量:")
.fontSize(16)
Button("3個動作")
.backgroundColor(this.actionCount === 3 ? Color.Blue : Color.White)
.border({ width: 1, color: Color.Gray })
.onClick(() = > this.actionCount = 3)
Button("4個動作")
.backgroundColor(this.actionCount === 4 ? Color.Blue : Color.White)
.border({ width: 1, color: Color.Gray })
.onClick(() = > this.actionCount = 4)
}
// 語音播報開關
Toggle({ type: ToggleType.Checkbox, isOn: this.speechEnabled })
.onChange((isOn: boolean)= >{
this.speechEnabled = isOn;
})
// 跳轉模式選擇
Row({ space: 20 }) {
Text("跳轉模式:")
.fontSize(16)
Button("替換頁面")
.backgroundColor(this.routeMode === "replace" ? Color.Blue : Color.White)
.border({ width: 1, color: Color.Gray })
.onClick(() = > {
this.routeMode = interactiveLiveness.RouteRedirectionMode.REPLACE_MODE;
})
Button("返回上頁")
.backgroundColor(this.routeMode === "back" ? Color.Blue : Color.White)
.border({ width: 1, color: Color.Gray })
.onClick(() = > {
this.routeMode = interactiveLiveness.RouteRedirectionMode.BACK_MODE;
})
}
// 啟動檢測按鈕
Button("開始人臉活體檢測")
.fontSize(20)
.padding(16)
.backgroundColor(Color.Orange)
.onClick(() = > this.startDetection())
// 結果顯示
Text(this.detectionResult)
.fontSize(16)
.margin({
top: 30
})
.foregroundColor(this.detectionResult.includes("通過") ? Color.Green : Color.Red)
}
.width("100%")
.height("100%")
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}
注意:
1. 人臉活體檢測支持兩種模式
INTERACTIVE_MODE(動作活體檢測):默認模式,需用戶完成 3 或 4 個隨機動作(如眨眼、點頭等),通過動作組合驗證活體,規則限制避免相鄰動作重復或特定組合(如眨眼和注視不相鄰)。
SILENT_MODE(靜默活體檢測):暫未支持,無需用戶做動作,通過其他技術(如微表情、光線反射)檢測活體。
2. 配置人臉活體檢測的動作數量和跳轉邏輯
通過InteractiveLivenessConfig中的actionsNum配置,可選值為 3(默認)或 4,3 個動作時(眨眼,注視) 不同時存在且不相鄰,4 個動作時眨眼僅 1 次,注視最多 1 次。
通過routeMode配置跳轉模式(BACK_MODE 返回上一頁或 REPLACE_MODE 替換跳轉,默認 REPLACE_MODE)。
successfulRouteUrl和failedRouteUrl設置成功 / 失敗后的自定義跳轉路徑(未填則用系統默認頁面)。
3. 常見錯誤及處理:
201(Permission denied):未申請ohos.permission.CAMERA權限
1008301002(Route switching failed):路由配置錯誤,檢查successfulRouteUrl/failedRouteUrl路徑是否正確,或routeMode是否與頁面路由匹配。
1008302000-1008302004(檢測相關錯誤):檢測過程中算法初始化失敗、超時或動作不符合規則,可通過回調或 Promise 的 catch 捕獲錯誤碼,提示用戶重新檢測并檢查動作合規性。
審核編輯 黃宇
-
鴻蒙
+關注
關注
59文章
2562瀏覽量
43864 -
HarmonyOS
+關注
關注
80文章
2092瀏覽量
32420
發布評論請先 登錄
【HarmonyOS 5】桌面快捷方式功能實現詳解

HarmonyOS 5 makeObserved接口詳解

筑牢人臉信息安全防線|安全芯片如何賦能《人臉識別技術應用安全管理辦法》落地

氣體檢漏儀如何操作?注意事項有哪些?
使用OpenVINO?模型的OpenCV進行人臉檢測,檢測到多張人臉時,伺服電機和步入器電機都發生移動是為什么?
遠峰科技UWB活體檢測方案優勢顯著,上市發布后獲廣泛關注

安帕爾:可燃氣體檢測儀怎么樣選擇
可存儲500張人臉的雙目3D人臉識別模塊

低功耗藍牙模塊+氣體檢測儀藍牙方案介紹

評論