Android Studio에서 MNN을 사용하여 모델 배포

1. 사전 환경 준비

1.1 MNN 환경 컴파일

자세한 내용은 이전에 작성한 기사를 참조하십시오. 기사 주소

1.2 안드로이드용 opencv 설치

opencv의 공식 웹 사이트에 들어가 설치 패키지를 다운로드합니다: 다운로드 주소를 다운로드
하고 다운로드가 완료되면 압축을 풉니다.
여기에 이미지 설명 삽입

2. 안드로이드 프로젝트 환경 구성

2.1 안드로이드 프로젝트 생성

Android Studio를 열고 새 Native C++ 프로젝트를 만듭니다.
여기에 이미지 설명 삽입

2.2 MNN 환경 구성

  • Android의 이전 MNN 컴파일에서 생성된 build_64 폴더 아래의 libMNN.so 파일을 Android 프로젝트 아래의 app/libs/arm64-v8a 폴더에 복사합니다(arm64-v8a 폴더는 자체적으로 생성됨).

libs 폴더를 찾을 수 없음 프로젝트로 모드 전환
여기에 이미지 설명 삽입

여기에 이미지 설명 삽입

  • CMakeLists.txt를 사용하여 컴파일
    하고 cpp 폴더 아래의 CMakeLists.txt를 편집하여
    다음 콘텐츠를 추가합니다.
#----------------MNN环境---------------------
# MNN_DIR为自己安装的MNN的路径
set(MNN_DIR D:/APP/MNN)
# mnn的头文件
include_directories(${
    
    MNN_DIR}/include)
include_directories(${
    
    MNN_DIR}/include/MNN)
include_directories(${
    
    MNN_DIR}/tools)
include_directories(${
    
    MNN_DIR}/tools/cpp)
include_directories(${
    
    MNN_DIR}/source)
include_directories(${
    
    MNN_DIR}/source/backend)
include_directories(${
    
    MNN_DIR}/source/core)

set(dis_DIR ../../../../libs)
add_library(
        MNN
        SHARED
        IMPORTED
)
set_target_properties(
        MNN
        PROPERTIES IMPORTED_LOCATION
        ${
    
    dis_DIR}/arm64-v8a/libMNN.so
)
#----------------------------------------------
  • 앱에서 build.gradle 파일 수정
plugins {
    
    
    id 'com.android.application'
}

android {
    
    
    compileSdk 32

    defaultConfig {
    
    
        applicationId "com.cjpnice.lcnet_mnn"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
    
    
            cmake {
    
    
                cppFlags '-std=c++14'
                arguments "-DANDROID_STL=c++_shared"
                abiFilters  "arm64-v8a"
            }
        }
    }

    buildTypes {
    
    
        release {
    
    
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
    
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    externalNativeBuild {
    
    
        cmake {
    
    
            path file('src/main/cpp/CMakeLists.txt')
            version '3.18.1'
        }
    }
    buildFeatures {
    
    
        viewBinding true
    }
}

dependencies {
    
    
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

OpenCV 환경 구성

  • cpp 폴더 아래의 CMakeLists.txt 편집
#-----------opencv环境配置-----------------------
#设置OpenCV-android-sdk路径
set( OpenCV_DIR D:/APP/OpenCV-android-sdk/sdk/native/jni )
find_package(OpenCV REQUIRED )
if(OpenCV_FOUND)
    include_directories(${OpenCV_INCLUDE_DIRS})
    message(STATUS "OpenCV library status:")
    message(STATUS "    version: ${OpenCV_VERSION}")
    message(STATUS "    libraries: ${OpenCV_LIBS}")
    message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")
else(OpenCV_FOUND)
    message(FATAL_ERROR "OpenCV library not found")
endif(OpenCV_FOUND)
#-----------------------------------------------

CMakeLists.txt 완료

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.18.1)

# Declares and names the project.

project("lcnet_mnn")

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
#----------------MNN环境---------------------
# MNN_DIR为自己安装的MNN的路径
set(MNN_DIR D:/APP/MNN)
# mnn的头文件
include_directories(${
    
    MNN_DIR}/include)
include_directories(${
    
    MNN_DIR}/include/MNN)
include_directories(${
    
    MNN_DIR}/tools)
include_directories(${
    
    MNN_DIR}/tools/cpp)
include_directories(${
    
    MNN_DIR}/source)
include_directories(${
    
    MNN_DIR}/source/backend)
include_directories(${
    
    MNN_DIR}/source/core)

set(dis_DIR ../../../../libs)
add_library(
        MNN
        SHARED
        IMPORTED
)
set_target_properties(
        MNN
        PROPERTIES IMPORTED_LOCATION
        ${
    
    dis_DIR}/arm64-v8a/libMNN.so
)
#----------------------------------------------

#-----------opencv环境配置-----------------------
#设置OpenCV-android-sdk路径
set( OpenCV_DIR D:/APP/OpenCV-android-sdk/sdk/native/jni )
find_package(OpenCV REQUIRED )
if(OpenCV_FOUND)
    include_directories(${
    
    OpenCV_INCLUDE_DIRS})
    message(STATUS "OpenCV library status:")
    message(STATUS "    version: ${OpenCV_VERSION}")
    message(STATUS "    libraries: ${OpenCV_LIBS}")
    message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")
else(OpenCV_FOUND)
    message(FATAL_ERROR "OpenCV library not found")
endif(OpenCV_FOUND)
#-----------------------------------------------



aux_source_directory(. SRCS)
add_library( # Sets the name of the library.
        lcnet_mnn
        # Sets the library as a shared library.
        SHARED
        # Provides a relative path to your source file(s).
        ${
    
    SRCS})

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
        log-lib
        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
        lcnet_mnn
        # Links the target library to the log library
        # included in the NDK.
        MNN
        jnigraphics
        ${
    
    OpenCV_LIBS}
        ${
    
    log-lib})

3. 모델 추론을 위한 MNN 작성

자신의 모델에 따라 모델 추론을 위해 MNN을 호출하는 jni를 작성합니다.
자세한 내용은 향후 업데이트될 예정입니다.

Supongo que te gusta

Origin blog.csdn.net/qq_40042726/article/details/123818928
Recomendado
Clasificación