【Android】OpenCVのSDKをセットアップしてみた

Camera Xを使って画像解析をしたいと思いOpenCVをAndroidに導入してみた。

android用のsdkを以下のGithubからダウンロードする。

opencv-4.7.0-android-sdk.zip

https://github.com/opencv/opencv/releases

適当なディレクトリに解凍しておく。

次にAndroid StudioでFile -> New -> Import Module で、OpenCV-android-sdk/sdk の場所を指定する。

sdkのインポートが終わると以下のようにsdkフォルダが追加される。

次に追加したフォルダがビルド対象になるようにgradleのdependenciesに追記してsyncする。

dependencies {

    :

    implementation project(":sdk")
}

以下は私の環境だけだと思うが、プロジェクトをビルドすると以下のメッセージが出た。

Android Studio-- Cause: error=86, Bad CPU type in executable

M1 Macの場合に発生するエラー。

以下のコマンドをターミナルに入れて解決。

nokkun@nokkunnoMacBook-Air ~ % softwareupdate --install-rosetta
I have read and agree to the terms of the software license agreement. A list of Apple SLAs may be found here: http://www.apple.com/legal/sla/
Type A and press return to agree: A
2023-01-05 09:37:44.149 softwareupdate[35657:2595547] Package Authoring Error: 012-42730: Package reference com.apple.pkg.RosettaUpdateAuto is missing installKBytes attribute
Install of Rosetta 2 finished successfully

https://stackoverflow.com/questions/56553879/android-studio-cause-error-86-bad-cpu-type-in-executable

ビルドに時間がかかるかと思ったが、M1Macだからかすぐにビルドが終わった。

最後にOnCreateの中に以下のデバッグコードを入れてログが出ればよい。

 OpenCVLoader.initDebug()
LogCatのログにOpenCV関係のログが出力される

エラーが出てるように見えるが動作には影響がない。

参考

https://qiita.com/iwatake2222/items/c0ebe6d84afdef57aab3

https://philipplies.medium.com/setting-up-latest-opencv-for-android-studio-and-kotlin-2021-edition-259be404b133

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog