ToB企服应用市场:ToB评测及商务社交产业平台

标题: 如何使用HarmonyOS面部识别能力_deveco studio 人脸识别 [打印本页]

作者: 星球的眼睛    时间: 2024-8-2 05:38
标题: 如何使用HarmonyOS面部识别能力_deveco studio 人脸识别
先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7
深知大多数程序员,想要提升技能,往往是自己摸索发展,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术故步自封!
因此收集整理了一份《2024年最新HarmonyOS鸿蒙全套学习资料》,初志也很简朴,就是希望能够资助到想自学提升又不知道该从何学起的朋友。





既有适合小白学习的零基础资料,也有适合3年以上履历的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习条记、源码讲义、实战项目、大纲蹊径、解说视频,并且后续会持续更新
如果你必要这些资料,可以添加V获取:vip204888 (备注鸿蒙)

正文

/**

@Override
protected void processEvent(InnerEvent event) {
super.processEvent(event);
int eventId = event.eventId;
getAndSetText(ResourceTable.Id_text_status, eventId, true);
}
}
取消人脸识别
点击取消人脸识别Button,触发取消人脸识别操作,代码示例如下:
private void createCancelBtn() {
// 创建点击事件
Component component = findComponentById(ResourceTable.Id_button_cancel);
// 创建按钮
Button cancelBtn = null;
if (component != null && component instanceof Button) {
cancelBtn = (Button) component;
cancelBtn.setClickedListener(view -> {
if (mBiometricAuthentication != null) {
// 调用取消接口
int result = mBiometricAuthentication.cancelAuthenticationAction();
LogUtils.info(“createCancelBtn:”, result + “”);
}
});
}
}
页面跳转
人脸识别乐成后,跳转到模仿相机页面,代码示例如下:
private void toAuthAfterPage() {
Intent secondIntent = new Intent();
// 指定待启动FA的bundleName和abilityName
Operation operation = new Intent.OperationBuilder()
.withDeviceId(“”)
.withBundleName(getBundleName())
.withAbilityName(OpenCamera.class.getName())
.build();
secondIntent.setOperation(operation);
// startAbility接口实现启动另一个页面
startAbility(secondIntent);
}
7. 相机相干业务逻辑
在模仿相机页面(ability_open_camera.xml)中,包含打开相机和切换前后置摄像头的功能,我们下面将逐一介绍。
初始化SurfaceProvider
用户授权后,开始初始化SurfaceProvider,代码示例如下:
private void initSurface() {
surfaceProvider = new SurfaceProvider(this);
DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig(
ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
surfaceProvider.setLayoutConfig(params);
surfaceProvider.pinToZTop(false);
// 添加SurfaceCallBack回调
surfaceProvider.getSurfaceOps().get().addCallback(new SurfaceCallBack());
// 将SurfaceProvider参加到结构中
Component component = findComponentById(ResourceTable.Id_surface_container);
if (component instanceof ComponentContainer) {
((ComponentContainer) component).addComponent(surfaceProvider);
}
}
实现SurfaceOps.Callback回调,当Surface创建时,执行打开相机的操作,代码示例如下:
/**

@Override
public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
}
}
打开相机
创建surface后触发surfaceCreated回调,执行打开相机的操作。打开相机并添加相片接收的监听,代码示例如下:
private void openCamera() {
CameraKit cameraKit = CameraKit.getInstance(getApplicationContext());
String[] cameraLists = cameraKit.getCameraIds();
String cameraId = cameraLists.length > 1 && isCameraRear ? cameraLists[1] : cameraLists[0];
CameraStateCallbackImpl cameraStateCallback = new CameraStateCallbackImpl();
cameraKit.createCamera(cameraId, cameraStateCallback, creamEventHandler);
}
/**

@Override
public void onCreated(Camera camera) {
// 获取预览
previewSurface = surfaceProvider.getSurfaceOps().get().getSurface();
if (previewSurface == null) {
LogUtils.error(TAG, “create camera filed, preview surface is null”);
return;
}
// Wait until the preview surface is created.
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException exception) {
LogUtils.warn(TAG, “Waiting to be interrupted”);
}
CameraConfig.Builder cameraConfigBuilder = camera.getCameraConfigBuilder();
// 设置预览
cameraConfigBuilder.addSurface(previewSurface);
camera.configure(cameraConfigBuilder.build());
cameraDevice = camera;
enableImageGroup();
}
@Override
public void onConfigured(Camera camera) {
FrameConfig.Builder framePreviewConfigBuilder
= camera.getFrameConfigBuilder(Camera.FrameConfigType.FRAME_CONFIG_PREVIEW);
framePreviewConfigBuilder.addSurface(previewSurface);
// 开启循环捕捉
camera.triggerLoopingCapture(framePreviewConfigBuilder.build());
}
private void enableImageGroup() {
if (!exitImage.isEnabled()) {
exitImage.setEnabled(true);
switchCameraImage.setEnabled(true);
}
}
}
切换前后置摄像头
点击切换摄像头图标后,执行切换前后置摄像头操作,代码示例如下:
private void switchClicked() {
isCameraRear = !isCameraRear;
openCamera();
}
8. 效果展示
人脸识别FA(MainAbilitySlice)完成了检验设备是否支持人脸识别,人脸识别,人脸识别效果表现,乐成后跳转到打开相机的FA(OpenCameraSlice);相机FA实现了相机的打开,照相,相片存储,摄像头切换的功能。具体效果图如下:
人脸识别初始页面:

人脸识别效果表现:

相机页面:

9. 完整代码示例
编写结构与样式
1.base/graphic/background_ability_main.xml
<?xml version="1.0" encoding="UTF-8" ?>


2.base/graphic/button_element.xml
<?xml version="1.0" encoding="utf-8"?>



3.base/layout/ability_main.xml
<?xml version="1.0" encoding="utf-8"?>
   
   



4.base/layout/ability_open_camera.xml
<?xml version="1.0" encoding="utf-8"?>









功能逻辑代码
1.com/huawei/cookbook/slice/MainAbilitySlice.java
package com.huawei.cookbook.slice;
import com.huawei.cookbook.MainAbility;
import com.huawei.cookbook.OpenCamera;
import com.huawei.cookbook.ResourceTable;
import com.huawei.cookbook.util.FaceAuthResult;
import com.huawei.cookbook.util.LogUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.biometrics.authentication.BiometricAuthentication;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**

@Override
public void run() {
// 初始化myEventHandle
initHandler();
// 开始认证
startAuth();
}
};
/**

/**

/**

private void createStartListener() {
// 提示用户人脸识别时将人脸对准摄像头
getAndSetText(ResourceTable.Id_text_status, NO_FACE_RET, true);
try {
// 创建生物识别对象
mBiometricAuthentication = BiometricAuthentication.getInstance(MainAbility.getMainAbility());
// 检验设备是否有人脸识别功能
// BiometricAuthentication.AuthType中有三个类别
// 分别为AUTH_TYPE_BIOMETRIC_FINGERPRINT_ONLY指纹识别
// AUTH_TYPE_BIOMETRIC_FACE_ONLY脸部识别
// AUTH_TYPE_BIOMETRIC_ALL指纹和面部
// BiometricAuthentication.SecureLevel 2D人脸识别建议使用SECURE_LEVEL_S2,3D人脸识别建议使用SECURE_LEVEL_S3
int hasAuth = mBiometricAuthentication.checkAuthenticationAvailability(
BiometricAuthentication.AuthType.AUTH_TYPE_BIOMETRIC_FACE_ONLY,
BiometricAuthentication.SecureLevel.SECURE_LEVEL_S2, true);
// hasAuth 0是支持,1是不支持,2安全级别不支持 3不是当地认证 4无人脸录入
if (hasAuth == 0) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
POOL_CORE_SIZE, POOL_MAX_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(QUEUE_SIZE), new ThreadPoolExecutor.DiscardOldestPolicy());
pool.submit(runnable);
} else {
// 人脸识别不支持或存在其他问题 ,直接回显页面,
// 在主线程不必要通过EventHandler发送回显任务
int retExcAuth = getRetExcAuth(hasAuth);
getAndSetText(ResourceTable.Id_text_status, retExcAuth, true);
}
} catch (IllegalAccessException e) {
LogUtils.error(“createStartBtn”, “IllegalAccessException when start auth”);
}
}
/**

/**

/**

/**

/**

private void toAuthAfterPage() {
Intent secondIntent = new Intent();
// 指定待启动FA的bundleName和abilityName
Operation operation = new Intent.OperationBuilder()
.withDeviceId(“”)
.withBundleName(getBundleName())
.withAbilityName(OpenCamera.class.getName())
.build();
secondIntent.setOperation(operation);
// 通过AbilitySlice的startAbility接口实现启动另一个页面
startAbility(secondIntent);
}
/**

@Override
protected void processEvent(InnerEvent event) {
super.processEvent(event);
int eventId = event.eventId;
getAndSetText(ResourceTable.Id_text_status, eventId, true);
}
}
@Override
public void onStop() {
mBiometricAuthentication.cancelAuthenticationAction();
BiometricAuthentication.AuthenticationTips authenticationTips
= mBiometricAuthentication.getAuthenticationTips();
String tips = authenticationTips.tipInfo;
}
}
2.com/huawei/cookbook/slice/OpenCameraSlice.java
package com.huawei.cookbook.slice;
import com.huawei.cookbook.ResourceTable;
import com.huawei.cookbook.util.LogUtils;
import com.huawei.cookbook.util.PermissionBridge;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.Camera;
import ohos.media.camera.device.CameraConfig;
import ohos.media.camera.device.CameraStateCallback;
import ohos.media.camera.device.FrameConfig;
/**

private static final int SCREEN_WIDTH = 1080;
private static final int SCREEN_HEIGHT = 1920;
private static final int SLEEP_TIME = 200;
private EventHandler creamEventHandler;
private Image exitImage;
private SurfaceProvider surfaceProvider;
private Image switchCameraImage;
private boolean isCameraRear;
private Camera cameraDevice;
private Surface previewSurface;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_open_camera);
new PermissionBridge().setOnPermissionStateListener(this);
}
private void initSurface() {
surfaceProvider = new SurfaceProvider(this);
DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig(
ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
surfaceProvider.setLayoutConfig(params);
surfaceProvider.pinToZTop(false);
// 添加SurfaceCallBack回调
surfaceProvider.getSurfaceOps().get().addCallback(new SurfaceCallBack());
// 将SurfaceProvider参加到结构中
Component component = findComponentById(ResourceTable.Id_surface_container);
if (component instanceof ComponentContainer) {
((ComponentContainer) component).addComponent(surfaceProvider);
}
}
private void initControlComponents() {
// 退出照相页面图标
Component exitImageCom = findComponentById(ResourceTable.Id_exit);
if (exitImageCom instanceof Image) {
exitImage = (Image) exitImageCom;
exitImage.setClickedListener(component -> terminate());
}
// 切换前后置摄像头图标
Component switchCameraImageCom = findComponentById(ResourceTable.Id_switch_camera_btn);
if (switchCameraImageCom instanceof Image) {
switchCameraImage = (Image) switchCameraImageCom;
switchCameraImage.setClickedListener(component -> switchClicked());
}
}
private void switchClicked() {
isCameraRear = !isCameraRear;
openCamera();
}
private void openCamera() {
CameraKit cameraKit = CameraKit.getInstance(getApplicationContext());
String[] cameraLists = cameraKit.getCameraIds();
String cameraId = cameraLists.length > 1 && isCameraRear ? cameraLists[1] : cameraLists[0];
CameraStateCallbackImpl cameraStateCallback = new CameraStateCallbackImpl();
cameraKit.createCamera(cameraId, cameraStateCallback, creamEventHandler);
}
private void showTips(Context context, String message) {
getUITaskDispatcher().asyncDispatch(() -> {
ToastDialog toastDialog = new ToastDialog(context);
toastDialog.setAutoClosable(false);
toastDialog.setContentText(message);
toastDialog.show();
});
}
@Override
public void onPermissionGranted() {
getWindow().setTransparent(true);
initSurface();
initControlComponents();
creamEventHandler = new EventHandler(EventRunner.create(“======CameraBackground”));
}
@Override
public void onPermissionDenied() {
showTips(OpenCameraSlice.this, “=======No permission”);
}
/**

@Override
public void onCreated(Camera camera) {
// 获取预览
previewSurface = surfaceProvider.getSurfaceOps().get().getSurface();
if (previewSurface == null) {
LogUtils.error(TAG, “create camera filed, preview surface is null”);
return;
}
// Wait until the preview surface is created.
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException exception) {
LogUtils.warn(TAG, “Waiting to be interrupted”);
}
CameraConfig.Builder cameraConfigBuilder = camera.getCameraConfigBuilder();
// 设置预览
cameraConfigBuilder.addSurface(previewSurface);
camera.configure(cameraConfigBuilder.build());
cameraDevice = camera;
enableImageGroup();
}
@Override
public void onConfigured(Camera camera) {
FrameConfig.Builder framePreviewConfigBuilder
= camera.getFrameConfigBuilder(Camera.FrameConfigType.FRAME_CONFIG_PREVIEW);
framePreviewConfigBuilder.addSurface(previewSurface);
// 开启循环捕捉
camera.triggerLoopingCapture(framePreviewConfigBuilder.build());
}
private void enableImageGroup() {
if (!exitImage.isEnabled()) {
exitImage.setEnabled(true);
switchCameraImage.setEnabled(true);
}
}
}
/**

@Override
public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
}
}
@Override
public void onStop() {
cameraDevice.release();
}
}
3.com/huawei/cookbook/util/FaceAuthResult.java
package com.huawei.cookbook.util;
/**

private FaceAuthResult() {
super();
}
}
4.com/huawei/cookbook/util/LogUtils.java
package com.huawei.cookbook.util;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
/**

private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtils.TAG_LOG);
private static final String LOG_FORMAT = “%{public}s: %{public}s”;
private LogUtils() {
}
/**

/**

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
必要这份体系化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感爱好的新人,都欢迎参加我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习发展!
.huawei.cookbook.util;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
/**

private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtils.TAG_LOG);
private static final String LOG_FORMAT = “%{public}s: %{public}s”;
private LogUtils() {
}
/**

/**

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
必要这份体系化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)
[外链图片转存中…(img-AQoaMLra-1713187175498)]
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感爱好的新人,都欢迎参加我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习发展!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4