Seguimiento del cuerpo humano con AR Engine

Preview

Introducción

HUAWEI AR Engine tiene soporte para detectar objetos en el mundo real que se llama “Seguimiento del entorno” y con él puede registrar iluminación, plano, imagen, objeto, superficie y otra información ambiental para ayudar a sus aplicaciones a fusionar objetos virtuales en escenarios físicos. mundo.

Body tracking

Esta función identifica y rastrea ubicaciones 2D para 23 puntos del esqueleto corporal (o ubicaciones 3D de 15 puntos del esqueleto corporal) y admite el seguimiento de una o dos personas a la vez.

AR Engine reconoce cuerpos humanos y genera coordenadas 2D y 3D (basadas en SLAM) de puntos del esqueleto, y es capaz de cambiar entre las cámaras delantera y trasera.

La capacidad de seguimiento del cuerpo le permite superponer objetos virtuales en el cuerpo con un alto grado de precisión, como en el hombro izquierdo o el tobillo derecho. También puede realizar una mayor cantidad de acciones precisas en el avatar, dotando a sus aplicaciones de AR con una funcionalidad divertida.

Ejemplo de aplicación de Android

Para este ejemplo, trabajaremos en el seguimiento del entorno para que podamos detectar una mano e interactuar con ella.

Proceso de desarrollo

Crear una aplicación

Cree una aplicación siguiendo las instrucciones de Creating an AppGallery Connect Project y Adding an App to the Project.

  • Platforma: Android
  • Dispositivo: Mobile phone
  • App category: App or Game

Integración de HUAWEI AR Engine SDK

Antes del desarrollo, integre HUAWEI AR Engine SDK a través del repositorio de Maven en su entorno de desarrollo.

  1. Abra el archivo build.gradle en el directorio raíz de su proyecto de Android Studio.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath 'com.huawei.agconnect:agcp:1.3.2.301'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
maven {url 'https://developer.huawei.com/repo/'}
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Abra el archivo build.gradle en el directorio de la aplicación de su proyecto

apply plugin: 'com.android.application'android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.vsm.myarapplication"
minSdkVersion 27
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
//
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.301'
//
implementation 'com.huawei.hms:arenginesdk:2.15.0.1'
//
implementation 'de.javagl:obj:0.3.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
apply plugin: 'com.huawei.agconnect'

Creas tu actividad en la que trabajarás (activity_body.xml):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".body.BodyActivity">
<android.opengl.GLSurfaceView
android:id="@+id/bodySurfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/bodyTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="@color/red"
tools:layout_editor_absoluteX="315dp"
tools:layout_editor_absoluteY="4dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

AR Engine no es para todos los dispositivos, por lo que primero debemos validar si el dispositivo es compatible con AR Engine y está disponible, aquí está la lista de dispositivos compatibles

Utilizará estos métodos para comprobar si un dispositivo es compatible:

Metodos

private void setMessageWhenError(Exception catchException) {
if (catchException instanceof ARUnavailableServiceNotInstalledException) {
startActivity(new Intent(getApplicationContext(), ConnectAppMarketActivity.class));
} else if (catchException instanceof ARUnavailableServiceApkTooOldException) {
message = "Please update HuaweiARService.apk";
} else if (catchException instanceof ARUnavailableClientSdkTooOldException) {
message = "Please update this app";
} else if (catchException instanceof ARUnSupportedConfigurationException) {
message = "The configuration is not supported by the device!";
} else {
message = "exception throw";
}
}

En nuestro BodyActivity.java llamarás a la detección de superficie:

package com.vsm.myarapplication.body;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.huawei.hiar.ARBodyTrackingConfig;
import com.huawei.hiar.ARConfigBase;
import com.huawei.hiar.AREnginesApk;
import com.huawei.hiar.ARSession;
import com.huawei.hiar.exceptions.ARCameraNotAvailableException;
import com.huawei.hiar.exceptions.ARUnSupportedConfigurationException;
import com.huawei.hiar.exceptions.ARUnavailableClientSdkTooOldException;
import com.huawei.hiar.exceptions.ARUnavailableServiceApkTooOldException;
import com.huawei.hiar.exceptions.ARUnavailableServiceNotInstalledException;
import com.vsm.myarapplication.R;
import com.vsm.myarapplication.body.rendering.BodyRenderManager;
import com.vsm.myarapplication.common.ConnectAppMarketActivity;
import com.vsm.myarapplication.common.DisplayRotationManager;
public class BodyActivity extends AppCompatActivity {
private static final String TAG = BodyActivity.class.getSimpleName();
private ARSession mArSession;private GLSurfaceView mSurfaceView;private BodyRenderManager mBodyRenderManager;private DisplayRotationManager mDisplayRotationManager;// Used for the display of recognition data.
private TextView mTextView;
private String message = null;private boolean isRemindInstall = false;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body);
mTextView = findViewById(R.id.bodyTextView);
mSurfaceView = findViewById(R.id.bodySurfaceview);
mDisplayRotationManager = new DisplayRotationManager(this);
// Keep the OpenGL ES running context.
mSurfaceView.setPreserveEGLContextOnPause(true);
// Set the OpenGLES version.
mSurfaceView.setEGLContextClientVersion(2);
// Set the EGL configuration chooser, including for the
// number of bits of the color buffer and the number of depth bits.
mSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mBodyRenderManager = new BodyRenderManager(this);
mBodyRenderManager.setDisplayRotationManage(mDisplayRotationManager);
mBodyRenderManager.setTextView(mTextView);
mSurfaceView.setRenderer(mBodyRenderManager);
mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
Exception exception = null;
message = null;
if (mArSession == null) {
try {
if (!arEngineAbilityCheck()) {
finish();
return;
}
mArSession = new ARSession(this);
ARBodyTrackingConfig config = new ARBodyTrackingConfig(mArSession);
config.setEnableItem(ARConfigBase.ENABLE_DEPTH | ARConfigBase.ENABLE_MASK);
mArSession.configure(config);
mBodyRenderManager.setArSession(mArSession);
} catch (Exception capturedException) {
exception = capturedException;
setMessageWhenError(capturedException);
}
if (message != null) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Log.e(TAG, "Creating session", exception);
if (mArSession != null) {
mArSession.stop();
mArSession = null;
}
return;
}
}
try {
mArSession.resume();
} catch (ARCameraNotAvailableException e) {
Toast.makeText(this, "Camera open failed, please restart the app", Toast.LENGTH_LONG).show();
mArSession = null;
return;
}
mSurfaceView.onResume();
mDisplayRotationManager.registerDisplayListener();
}
/**
* Check whether HUAWEI AR Engine server (com.huawei.arengine.service) is installed on the current device.
* If not, redirect the user to HUAWEI AppGallery for installation.
*/
private boolean arEngineAbilityCheck() {
boolean isInstallArEngineApk = AREnginesApk.isAREngineApkReady(this);
if (!isInstallArEngineApk && isRemindInstall) {
Toast.makeText(this, "Please agree to install.", Toast.LENGTH_LONG).show();
finish();
}
Log.d(TAG, "Is Install AR Engine Apk: " + isInstallArEngineApk);
if (!isInstallArEngineApk) {
startActivity(new Intent(this, ConnectAppMarketActivity.class));
isRemindInstall = true;
}
return AREnginesApk.isAREngineApkReady(this);
}
private void setMessageWhenError(Exception catchException) {
if (catchException instanceof ARUnavailableServiceNotInstalledException) {
startActivity(new Intent(this, ConnectAppMarketActivity.class));
} else if (catchException instanceof ARUnavailableServiceApkTooOldException) {
message = "Please update HuaweiARService.apk";
} else if (catchException instanceof ARUnavailableClientSdkTooOldException) {
message = "Please update this app";
} else if (catchException instanceof ARUnSupportedConfigurationException) {
message = "The configuration is not supported by the device!";
} else {
message = "exception throw";
}
}
@Override
protected void onPause() {
Log.i(TAG, "onPause start.");
super.onPause();
if (mArSession != null) {
mDisplayRotationManager.unregisterDisplayListener();
mSurfaceView.onPause();
mArSession.pause();
}
Log.i(TAG, "onPause end.");
}
@Override
protected void onDestroy() {
Log.i(TAG, "onDestroy start.");
super.onDestroy();
if (mArSession != null) {
mArSession.stop();
mArSession = null;
}
Log.i(TAG, "onDestroy end.");
}
@Override
public void onWindowFocusChanged(boolean isHasFocus) {
Log.d(TAG, "onWindowFocusChanged");
super.onWindowFocusChanged(isHasFocus);
if (isHasFocus) {
getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
}

Conclusión

Con HUAWEI AR Engine puedes identificar puntos del esqueleto del cuerpo y características del cuerpo humano de salida, como puntos finales de las extremidades, postura corporal y esqueleto.

Documentación:

https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050130900

Codelab:

https://developer.huawei.com/consumer/en/codelab/HWAREngine/index.html#0

Code Sample:

https://github.com/spartdark/hms-arengine-myarapplication

--

--