I need to write some C++ code which uses OpenCV, and the Flutter code will call those C++ code.
There are tutorials about writing C++ with Flutter, but I cannot find any up-to-date and easy-to-deploy solution about working with OpenCV. How to do that?
Here is my solution.
Features
Getting Started
NOTE: If you already have an app, you can skip this section :) This section assumes that you have no code at all.
Sample code can be downloaded from here.
step 0: Ensure you have Flutter environment, and have followed the official "writing C++ with Flutter" tutorial.
NOTE: It is a must to follow the step of "On iOS, you need to tell Xcode to statically link the file: ...". Otherwise, at our last step iOS will complain the symbol cannot be found.
step 1: Write whatever code you like using OpenCV. For instance, I change
ios/Classes/native_add.cpp
to the following silly code, which is almost identical as in the official tutorial:Android
Step 0: Download the Android OpenCV sdk from the official website. Say I put it in
/Users/tom/Others/OpenCVRelease/OpenCV-android-sdk
in my desktop.Step 1.1: Change the
android/CMakeLists.txt
to the following. NOTE: First change theOPENCV_BASE_DIR
to your folder.Of course, the
lib/native_with_opencv.dart
should change the.so
file name to"libnative_with_opencv.so"
.Step 1.2: Change the
android/build.gradle
as following:Of course, the
minSdkVersion
in your actual project (native_with_opencv/example/android/app/build.gradle
) should also change to 21.**Done! **Compile and enjoy it (and go to the next section for iOS)! If you see
1 + 2 == 3
, then everything is fine.Bonus: If you build in release mode and look at the apk size, you will see our
.so
file is less than 1MB. Thus static linking and file size reduction does work :)iOS
Step 0: In
ios/native_with_opencv.podspec
, add:Step 1: Compile and enjoy. NOTE: You may first need to run
pod install
undernative_with_opencv/example/ios
to let Cocoapod initialize.(Optional) Explanations of how does the Android configuration work: (1) Originally, I just link the
core
, but there are hundreds of linking errors. Then I search and fix for each group of them. For instance,error: undefined reference to 'carotene_o4t::...'
means I need to link withlibtegra_hal
, thus I add several lines. (2) Strangely, thetbb
should be put aftercore
, otherwise it still does not link. (3) TheabiFilters
is needed, sincetegra_hal
does not supportx86
(thus no.a
file exists). (4)minSdkVersion
needs to be raised up, otherwisefegetenv
will not be found.