Search code examples
bazelandroidopencv

How to import OpenCV android-sdk to my project which is using Bazel?


I have been trying to import opencv-android-sdk to my Bazel project but I am not able to do it.

I tried the this answer on SO but while building my project I get errors that

error: package org.opencv.android does not exist


Solution

  • I see that there's an opencv-android artifact on Maven.

    You can depend on this using rules_jvm_external.

    In your WORKSPACE file, specify the dependency along with the other external dependencies:

    load("@rules_jvm_external//:defs.bzl", "maven_install")
    
    maven_install(
        artifacts = [
            "org.opencv:opencv-android:1.0.1",
            # ...
        ],
        repositories = [
            "https://maven.google.com",
            "https://jcenter.bintray.com",
        ],
    )
    

    Then, in your BUILD file containing your Android targets, depend on the OpenCV target:

    android_library(
         name = "my_lib",
         custom_package = "com.example.bazel",
         srcs = glob(["java/com/example/bazel/*.java"]),
         manifest = "java/AndroidManifest.xml",
         resource_files = glob(["res/**"]),
         deps = [
             "@maven//:org_opencv_opencv_android",
         ],
         visibility = ["//src/test:__subpackages__"]
    )
    

    Finally, you should be able to reference classes like org.opencv.core.Core in your Android Java code.

    P.S. consider switching all your maven_jar and gmaven_rules/gmaven_artifact to use rules_jvm_external. The former Maven rules have been deprecated in favor of rules_jvm_external.