feat: 切换后端至PaddleOCR-NCNN,切换工程为CMake

1.项目后端整体迁移至PaddleOCR-NCNN算法,已通过基本的兼容性测试
2.工程改为使用CMake组织,后续为了更好地兼容第三方库,不再提供QMake工程
3.重整权利声明文件,重整代码工程,确保最小化侵权风险

Log: 切换后端至PaddleOCR-NCNN,切换工程为CMake
Change-Id: I4d5d2c5d37505a4a24b389b1a4c5d12f17bfa38c
This commit is contained in:
wangzhengyang
2022-05-10 09:54:44 +08:00
parent ecdd171c6f
commit 718c41634f
10018 changed files with 3593797 additions and 186748 deletions

View File

@ -0,0 +1 @@
See http://opencv.org/platforms/android

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,459 @@
#!/usr/bin/env python
import os, sys
import argparse
import glob
import re
import shutil
import subprocess
import time
import logging as log
import xml.etree.ElementTree as ET
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
class Fail(Exception):
def __init__(self, text=None):
self.t = text
def __str__(self):
return "ERROR" if self.t is None else self.t
def execute(cmd, shell=False):
try:
log.debug("Executing: %s" % cmd)
log.info('Executing: ' + ' '.join(cmd))
retcode = subprocess.call(cmd, shell=shell)
if retcode < 0:
raise Fail("Child was terminated by signal: %s" % -retcode)
elif retcode > 0:
raise Fail("Child returned: %s" % retcode)
except OSError as e:
raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))
def rm_one(d):
d = os.path.abspath(d)
if os.path.exists(d):
if os.path.isdir(d):
log.info("Removing dir: %s", d)
shutil.rmtree(d)
elif os.path.isfile(d):
log.info("Removing file: %s", d)
os.remove(d)
def check_dir(d, create=False, clean=False):
d = os.path.abspath(d)
log.info("Check dir %s (create: %s, clean: %s)", d, create, clean)
if os.path.exists(d):
if not os.path.isdir(d):
raise Fail("Not a directory: %s" % d)
if clean:
for x in glob.glob(os.path.join(d, "*")):
rm_one(x)
else:
if create:
os.makedirs(d)
return d
def check_executable(cmd):
try:
log.debug("Executing: %s" % cmd)
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
if not isinstance(result, str):
result = result.decode("utf-8")
log.debug("Result: %s" % (result+'\n').split('\n')[0])
return True
except Exception as e:
log.debug('Failed: %s' % e)
return False
def determine_opencv_version(version_hpp_path):
# version in 2.4 - CV_VERSION_EPOCH.CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION
# version in master - CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION-CV_VERSION_STATUS
with open(version_hpp_path, "rt") as f:
data = f.read()
major = re.search(r'^#define\W+CV_VERSION_MAJOR\W+(\d+)$', data, re.MULTILINE).group(1)
minor = re.search(r'^#define\W+CV_VERSION_MINOR\W+(\d+)$', data, re.MULTILINE).group(1)
revision = re.search(r'^#define\W+CV_VERSION_REVISION\W+(\d+)$', data, re.MULTILINE).group(1)
version_status = re.search(r'^#define\W+CV_VERSION_STATUS\W+"([^"]*)"$', data, re.MULTILINE).group(1)
return "%(major)s.%(minor)s.%(revision)s%(version_status)s" % locals()
# shutil.move fails if dst exists
def move_smart(src, dst):
def move_recurse(subdir):
s = os.path.join(src, subdir)
d = os.path.join(dst, subdir)
if os.path.exists(d):
if os.path.isdir(d):
for item in os.listdir(s):
move_recurse(os.path.join(subdir, item))
elif os.path.isfile(s):
shutil.move(s, d)
else:
shutil.move(s, d)
move_recurse('')
# shutil.copytree fails if dst exists
def copytree_smart(src, dst):
def copy_recurse(subdir):
s = os.path.join(src, subdir)
d = os.path.join(dst, subdir)
if os.path.exists(d):
if os.path.isdir(d):
for item in os.listdir(s):
copy_recurse(os.path.join(subdir, item))
elif os.path.isfile(s):
shutil.copy2(s, d)
else:
if os.path.isdir(s):
shutil.copytree(s, d)
elif os.path.isfile(s):
shutil.copy2(s, d)
copy_recurse('')
def get_highest_version(subdirs):
return max(subdirs, key=lambda dir: [int(comp) for comp in os.path.split(dir)[-1].split('.')])
#===================================================================================================
class ABI:
def __init__(self, platform_id, name, toolchain, ndk_api_level = None, cmake_vars = dict()):
self.platform_id = platform_id # platform code to add to apk version (for cmake)
self.name = name # general name (official Android ABI identifier)
self.toolchain = toolchain # toolchain identifier (for cmake)
self.cmake_vars = dict(
ANDROID_STL="gnustl_static",
ANDROID_ABI=self.name,
ANDROID_PLATFORM_ID=platform_id,
)
if toolchain is not None:
self.cmake_vars['ANDROID_TOOLCHAIN_NAME'] = toolchain
else:
self.cmake_vars['ANDROID_TOOLCHAIN'] = 'clang'
self.cmake_vars['ANDROID_STL'] = 'c++_shared'
if ndk_api_level:
self.cmake_vars['ANDROID_NATIVE_API_LEVEL'] = ndk_api_level
self.cmake_vars.update(cmake_vars)
def __str__(self):
return "%s (%s)" % (self.name, self.toolchain)
def haveIPP(self):
return self.name == "x86" or self.name == "x86_64"
#===================================================================================================
class Builder:
def __init__(self, workdir, opencvdir, config):
self.workdir = check_dir(workdir, create=True)
self.opencvdir = check_dir(opencvdir)
self.config = config
self.libdest = check_dir(os.path.join(self.workdir, "o4a"), create=True, clean=True)
self.resultdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk'), create=True, clean=True)
self.docdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk', 'sdk', 'java', 'javadoc'), create=True, clean=True)
self.extra_packs = []
self.opencv_version = determine_opencv_version(os.path.join(self.opencvdir, "modules", "core", "include", "opencv2", "core", "version.hpp"))
self.use_ccache = False if config.no_ccache else True
self.cmake_path = self.get_cmake()
self.ninja_path = self.get_ninja()
self.debug = True if config.debug else False
self.debug_info = True if config.debug_info else False
self.no_samples_build = True if config.no_samples_build else False
self.opencl = True if config.opencl else False
self.no_kotlin = True if config.no_kotlin else False
def get_cmake(self):
if not self.config.use_android_buildtools and check_executable(['cmake', '--version']):
log.info("Using cmake from PATH")
return 'cmake'
# look to see if Android SDK's cmake is installed
android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
if os.path.exists(android_cmake):
cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'cmake'), '--version'])]
if len(cmake_subdirs) > 0:
# there could be more than one - get the most recent
cmake_from_sdk = os.path.join(android_cmake, get_highest_version(cmake_subdirs), 'bin', 'cmake')
log.info("Using cmake from Android SDK: %s", cmake_from_sdk)
return cmake_from_sdk
raise Fail("Can't find cmake")
def get_ninja(self):
if not self.config.use_android_buildtools and check_executable(['ninja', '--version']):
log.info("Using ninja from PATH")
return 'ninja'
# Android SDK's cmake includes a copy of ninja - look to see if its there
android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
if os.path.exists(android_cmake):
cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'ninja'), '--version'])]
if len(cmake_subdirs) > 0:
# there could be more than one - just take the first one
ninja_from_sdk = os.path.join(android_cmake, cmake_subdirs[0], 'bin', 'ninja')
log.info("Using ninja from Android SDK: %s", ninja_from_sdk)
return ninja_from_sdk
raise Fail("Can't find ninja")
def get_toolchain_file(self):
if not self.config.force_opencv_toolchain:
toolchain = os.path.join(os.environ['ANDROID_NDK'], 'build', 'cmake', 'android.toolchain.cmake')
if os.path.exists(toolchain):
return toolchain
toolchain = os.path.join(SCRIPT_DIR, "android.toolchain.cmake")
if os.path.exists(toolchain):
return toolchain
else:
raise Fail("Can't find toolchain")
def get_engine_apk_dest(self, engdest):
return os.path.join(engdest, "platforms", "android", "service", "engine", ".build")
def add_extra_pack(self, ver, path):
if path is None:
return
self.extra_packs.append((ver, check_dir(path)))
def clean_library_build_dir(self):
for d in ["CMakeCache.txt", "CMakeFiles/", "bin/", "libs/", "lib/", "package/", "install/samples/"]:
rm_one(d)
def build_library(self, abi, do_install):
cmd = [self.cmake_path, "-GNinja"]
cmake_vars = dict(
CMAKE_TOOLCHAIN_FILE=self.get_toolchain_file(),
INSTALL_CREATE_DISTRIB="ON",
WITH_OPENCL="OFF",
BUILD_KOTLIN_EXTENSIONS="ON",
WITH_IPP=("ON" if abi.haveIPP() else "OFF"),
WITH_TBB="ON",
BUILD_EXAMPLES="OFF",
BUILD_TESTS="OFF",
BUILD_PERF_TESTS="OFF",
BUILD_DOCS="OFF",
BUILD_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
INSTALL_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
)
if self.ninja_path != 'ninja':
cmake_vars['CMAKE_MAKE_PROGRAM'] = self.ninja_path
if self.debug:
cmake_vars['CMAKE_BUILD_TYPE'] = "Debug"
if self.debug_info: # Release with debug info
cmake_vars['BUILD_WITH_DEBUG_INFO'] = "ON"
if self.opencl:
cmake_vars['WITH_OPENCL'] = "ON"
if self.no_kotlin:
cmake_vars['BUILD_KOTLIN_EXTENSIONS'] = "OFF"
if self.config.modules_list is not None:
cmd.append("-DBUILD_LIST='%s'" % self.config.modules_list)
if self.config.extra_modules_path is not None:
cmd.append("-DOPENCV_EXTRA_MODULES_PATH='%s'" % self.config.extra_modules_path)
if self.use_ccache == True:
cmd.append("-DNDK_CCACHE=ccache")
if do_install:
cmd.extend(["-DBUILD_TESTS=ON", "-DINSTALL_TESTS=ON"])
cmake_vars.update(abi.cmake_vars)
cmd += [ "-D%s='%s'" % (k, v) for (k, v) in cmake_vars.items() if v is not None]
cmd.append(self.opencvdir)
execute(cmd)
# full parallelism for C++ compilation tasks
execute([self.ninja_path, "opencv_modules"])
# limit parallelism for building samples (avoid huge memory consumption)
if self.no_samples_build:
execute([self.ninja_path, "install" if (self.debug_info or self.debug) else "install/strip"])
else:
execute([self.ninja_path, "-j1" if (self.debug_info or self.debug) else "-j3", "install" if (self.debug_info or self.debug) else "install/strip"])
def build_javadoc(self):
classpaths = []
for dir, _, files in os.walk(os.environ["ANDROID_SDK"]):
for f in files:
if f == "android.jar" or f == "annotations.jar":
classpaths.append(os.path.join(dir, f))
srcdir = os.path.join(self.resultdest, 'sdk', 'java', 'src')
dstdir = self.docdest
# synchronize with modules/java/jar/build.xml.in
shutil.copy2(os.path.join(SCRIPT_DIR, '../../doc/mymath.js'), dstdir)
cmd = [
"javadoc",
'-windowtitle', 'OpenCV %s Java documentation' % self.opencv_version,
'-doctitle', 'OpenCV Java documentation (%s)' % self.opencv_version,
"-nodeprecated",
"-public",
'-sourcepath', srcdir,
'-encoding', 'UTF-8',
'-charset', 'UTF-8',
'-docencoding', 'UTF-8',
'--allow-script-in-comments',
'-header',
'''
<script>
var url = window.location.href;
var pos = url.lastIndexOf('/javadoc/');
url = pos >= 0 ? (url.substring(0, pos) + '/javadoc/mymath.js') : (window.location.origin + '/mymath.js');
var script = document.createElement('script');
script.src = '%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML,' + url;
document.getElementsByTagName('head')[0].appendChild(script);
</script>
''' % 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0',
'-bottom', 'Generated on %s / OpenCV %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), self.opencv_version),
"-d", dstdir,
"-classpath", ":".join(classpaths),
'-subpackages', 'org.opencv',
]
execute(cmd)
def gather_results(self):
# Copy all files
root = os.path.join(self.libdest, "install")
for item in os.listdir(root):
src = os.path.join(root, item)
dst = os.path.join(self.resultdest, item)
if os.path.isdir(src):
log.info("Copy dir: %s", item)
if self.config.force_copy:
copytree_smart(src, dst)
else:
move_smart(src, dst)
elif os.path.isfile(src):
log.info("Copy file: %s", item)
if self.config.force_copy:
shutil.copy2(src, dst)
else:
shutil.move(src, dst)
def get_ndk_dir():
# look to see if Android NDK is installed
android_sdk_ndk = os.path.join(os.environ["ANDROID_SDK"], 'ndk')
android_sdk_ndk_bundle = os.path.join(os.environ["ANDROID_SDK"], 'ndk-bundle')
if os.path.exists(android_sdk_ndk):
ndk_subdirs = [f for f in os.listdir(android_sdk_ndk) if os.path.exists(os.path.join(android_sdk_ndk, f, 'package.xml'))]
if len(ndk_subdirs) > 0:
# there could be more than one - get the most recent
ndk_from_sdk = os.path.join(android_sdk_ndk, get_highest_version(ndk_subdirs))
log.info("Using NDK (side-by-side) from Android SDK: %s", ndk_from_sdk)
return ndk_from_sdk
if os.path.exists(os.path.join(android_sdk_ndk_bundle, 'package.xml')):
log.info("Using NDK bundle from Android SDK: %s", android_sdk_ndk_bundle)
return android_sdk_ndk_bundle
return None
#===================================================================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Build OpenCV for Android SDK')
parser.add_argument("work_dir", nargs='?', default='.', help="Working directory (and output)")
parser.add_argument("opencv_dir", nargs='?', default=os.path.join(SCRIPT_DIR, '../..'), help="Path to OpenCV source dir")
parser.add_argument('--config', default='ndk-18-api-level-21.config.py', type=str, help="Package build configuration", )
parser.add_argument('--ndk_path', help="Path to Android NDK to use for build")
parser.add_argument('--sdk_path', help="Path to Android SDK to use for build")
parser.add_argument('--use_android_buildtools', action="store_true", help='Use cmake/ninja build tools from Android SDK')
parser.add_argument("--modules_list", help="List of modules to include for build")
parser.add_argument("--extra_modules_path", help="Path to extra modules to use for build")
parser.add_argument('--sign_with', help="Certificate to sign the Manager apk")
parser.add_argument('--build_doc', action="store_true", help="Build javadoc")
parser.add_argument('--no_ccache', action="store_true", help="Do not use ccache during library build")
parser.add_argument('--force_copy', action="store_true", help="Do not use file move during library build (useful for debug)")
parser.add_argument('--force_opencv_toolchain', action="store_true", help="Do not use toolchain from Android NDK")
parser.add_argument('--debug', action="store_true", help="Build 'Debug' binaries (CMAKE_BUILD_TYPE=Debug)")
parser.add_argument('--debug_info', action="store_true", help="Build with debug information (useful for Release mode: BUILD_WITH_DEBUG_INFO=ON)")
parser.add_argument('--no_samples_build', action="store_true", help="Do not build samples (speeds up build)")
parser.add_argument('--opencl', action="store_true", help="Enable OpenCL support")
parser.add_argument('--no_kotlin', action="store_true", help="Disable Kotlin extensions")
args = parser.parse_args()
log.basicConfig(format='%(message)s', level=log.DEBUG)
log.debug("Args: %s", args)
if args.ndk_path is not None:
os.environ["ANDROID_NDK"] = args.ndk_path
if args.sdk_path is not None:
os.environ["ANDROID_SDK"] = args.sdk_path
if not 'ANDROID_HOME' in os.environ and 'ANDROID_SDK' in os.environ:
os.environ['ANDROID_HOME'] = os.environ["ANDROID_SDK"]
if not 'ANDROID_SDK' in os.environ:
raise Fail("SDK location not set. Either pass --sdk_path or set ANDROID_SDK environment variable")
# look for an NDK installed with the Android SDK
if not 'ANDROID_NDK' in os.environ and 'ANDROID_SDK' in os.environ:
sdk_ndk_dir = get_ndk_dir()
if sdk_ndk_dir:
os.environ['ANDROID_NDK'] = sdk_ndk_dir
if not 'ANDROID_NDK' in os.environ:
raise Fail("NDK location not set. Either pass --ndk_path or set ANDROID_NDK environment variable")
show_samples_build_warning = False
#also set ANDROID_NDK_HOME (needed by the gradle build)
if not 'ANDROID_NDK_HOME' in os.environ and 'ANDROID_NDK' in os.environ:
os.environ['ANDROID_NDK_HOME'] = os.environ["ANDROID_NDK"]
show_samples_build_warning = True
if not check_executable(['ccache', '--version']):
log.info("ccache not found - disabling ccache support")
args.no_ccache = True
if os.path.realpath(args.work_dir) == os.path.realpath(SCRIPT_DIR):
raise Fail("Specify workdir (building from script directory is not supported)")
if os.path.realpath(args.work_dir) == os.path.realpath(args.opencv_dir):
raise Fail("Specify workdir (building from OpenCV source directory is not supported)")
# Relative paths become invalid in sub-directories
if args.opencv_dir is not None and not os.path.isabs(args.opencv_dir):
args.opencv_dir = os.path.abspath(args.opencv_dir)
if args.extra_modules_path is not None and not os.path.isabs(args.extra_modules_path):
args.extra_modules_path = os.path.abspath(args.extra_modules_path)
cpath = args.config
if not os.path.exists(cpath):
cpath = os.path.join(SCRIPT_DIR, cpath)
if not os.path.exists(cpath):
raise Fail('Config "%s" is missing' % args.config)
with open(cpath, 'r') as f:
cfg = f.read()
print("Package configuration:")
print('=' * 80)
print(cfg.strip())
print('=' * 80)
ABIs = None # make flake8 happy
exec(compile(cfg, cpath, 'exec'))
log.info("Android NDK path: %s", os.environ["ANDROID_NDK"])
log.info("Android SDK path: %s", os.environ["ANDROID_SDK"])
builder = Builder(args.work_dir, args.opencv_dir, args)
log.info("Detected OpenCV version: %s", builder.opencv_version)
for i, abi in enumerate(ABIs):
do_install = (i == 0)
log.info("=====")
log.info("===== Building library for %s", abi)
log.info("=====")
os.chdir(builder.libdest)
builder.clean_library_build_dir()
builder.build_library(abi, do_install)
builder.gather_results()
if args.build_doc:
builder.build_javadoc()
log.info("=====")
log.info("===== Build finished")
log.info("=====")
if show_samples_build_warning:
#give a hint how to solve "Gradle sync failed: NDK not configured."
log.info("ANDROID_NDK_HOME environment variable required by the samples project is not set")
log.info("SDK location: %s", builder.resultdest)
log.info("Documentation location: %s", builder.docdest)

View File

@ -0,0 +1,17 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2g
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-@GRADLE_VERSION@-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,9 @@
ABIs = [
ABI("2", "armeabi-v7a", "arm-linux-androideabi-4.8", cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("1", "armeabi", "arm-linux-androideabi-4.8"),
ABI("3", "arm64-v8a", "aarch64-linux-android-4.9"),
ABI("5", "x86_64", "x86_64-4.9"),
ABI("4", "x86", "x86-4.8"),
ABI("7", "mips64", "mips64el-linux-android-4.9"),
ABI("6", "mips", "mipsel-linux-android-4.8")
]

View File

@ -0,0 +1,7 @@
ABIs = [
ABI("2", "armeabi-v7a", "arm-linux-androideabi-4.9", cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("1", "armeabi", "arm-linux-androideabi-4.9", cmake_vars=dict(WITH_TBB='OFF')),
ABI("3", "arm64-v8a", "aarch64-linux-android-4.9"),
ABI("5", "x86_64", "x86_64-4.9"),
ABI("4", "x86", "x86-4.9"),
]

View File

@ -0,0 +1,6 @@
ABIs = [
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("3", "arm64-v8a", None),
ABI("5", "x86_64", None),
ABI("4", "x86", None),
]

View File

@ -0,0 +1,6 @@
ABIs = [
ABI("2", "armeabi-v7a", None, 21, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("3", "arm64-v8a", None, 21),
ABI("5", "x86_64", None, 21),
ABI("4", "x86", None, 21),
]

View File

@ -0,0 +1,6 @@
ABIs = [
ABI("2", "armeabi-v7a", None, 24, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("3", "arm64-v8a", None, 24),
ABI("5", "x86_64", None, 24),
ABI("4", "x86", None, 24),
]

View File

@ -0,0 +1,6 @@
ABIs = [
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
ABI("3", "arm64-v8a", None),
ABI("5", "x86_64", None),
ABI("4", "x86", None),
]

View File

@ -0,0 +1,6 @@
ABIs = [
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON', ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
ABI("3", "arm64-v8a", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
ABI("5", "x86_64", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
ABI("4", "x86", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
]

View File

@ -0,0 +1,10 @@
if(NOT ANDROID_PROJECTS_BUILD_TYPE STREQUAL "ANT")
message(STATUS "Android OpenCV Manager is ignored")
return()
endif()
if(BUILD_ANDROID_SERVICE)
add_subdirectory(engine)
endif()
install(FILES "readme.txt" DESTINATION "apk/" COMPONENT libs)

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.opencv.engine"
android:versionCode="345@ANDROID_PLATFORM_ID@"
android:versionName="3.45">
<uses-sdk android:minSdkVersion="@ANDROID_NATIVE_API_LEVEL@" android:targetSdkVersion="22"/>
<uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" android:allowBackup="true">
<service android:exported="true" android:name="OpenCVEngineService" android:process=":OpenCVEngineProcess">
<intent-filter>
<action android:name="org.opencv.engine.BIND"></action>
</intent-filter>
</service>
<activity
android:name="org.opencv.engine.manager.ManagerActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,3 @@
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${ANDROID_MANIFEST_FILE}" "${OpenCV_BINARY_DIR}/platforms/android/service/engine/.build/${ANDROID_MANIFEST_FILE}" @ONLY)
unset(__android_project_chain CACHE)
add_android_project(opencv_engine "${CMAKE_CURRENT_SOURCE_DIR}" SDK_TARGET 9 ${ANDROID_SDK_TARGET} IGNORE_JAVA ON IGNORE_MANIFEST ON COPY_LIBS ON)

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollBox"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:scrollbarStyle="insideInset" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/about"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textViewIntro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="@string/intro"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="@+id/CheckEngineUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="@string/checkUpdate" />
</LinearLayout>
</ScrollView>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OpenCV Manager</string>
<string name="about">About</string>
<string name="checkUpdate">Check for update</string>
<string name="intro">OpenCV library is used by other applications for image enhancement, panorama stitching, object detection, recognition and tracking and so on. OpenCV Manager provides the best version of the OpenCV for your hardware. See opencv.org for details.</string>
</resources>

View File

@ -0,0 +1,118 @@
package org.opencv.engine;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
public class HardwareDetector {
private static String TAG = "OpenCVEngine/HardwareDetector";
public static final int ARCH_UNKNOWN = -1;
public static final int ARCH_X86 = 0x01000000;
public static final int ARCH_X86_64 = 0x02000000;
public static final int ARCH_ARM = 0x04000000;
public static final int ARCH_ARMv7 = 0x10000000;
public static final int ARCH_ARMv8 = 0x20000000;
public static final int ARCH_MIPS = 0x40000000;
public static final int ARCH_MIPS_64 = 0x80000000;
// Return CPU flags list
public static List<String> getFlags() {
Map<String, String> raw = getRawCpuInfo();
String f = raw.get("flags");
if (f == null)
f = raw.get("Features");
if (f == null)
return Arrays.asList();
return Arrays.asList(TextUtils.split(f, " "));
}
// Return CPU arch
public static int getAbi() {
List<String> abis = Arrays.asList(Build.CPU_ABI, Build.CPU_ABI2);
Log.i(TAG, "ABIs: " + abis.toString());
if (abis.contains("x86_64")) {
return ARCH_X86_64;
} else if (abis.contains("x86")) {
return ARCH_X86;
} else if (abis.contains("arm64-v8a")) {
return ARCH_ARMv8;
} else if (abis.contains("armeabi-v7a")
|| abis.contains("armeabi-v7a-hard")) {
return ARCH_ARMv7;
} else if (abis.contains("armeabi")) {
return ARCH_ARM;
} else if (abis.contains("mips64")) {
return ARCH_MIPS_64;
} else if (abis.contains("mips")) {
return ARCH_MIPS;
}
return ARCH_UNKNOWN;
}
// Return hardware platform name
public static String getHardware() {
Map<String, String> raw = getRawCpuInfo();
return raw.get("Hardware");
}
// Return processor count
public static int getProcessorCount() {
int result = 0;
try {
Pattern pattern = Pattern.compile("(\\d)+(-(\\d+))?");
Scanner s = new Scanner(
new File("/sys/devices/system/cpu/possible"));
if (s.hasNextLine()) {
String line = s.nextLine();
Log.d(TAG, "Got CPUs: " + line);
Matcher m = pattern.matcher(line);
while (m.find()) {
int start = Integer.parseInt(m.group(1));
int finish = start;
if (m.group(3) != null) {
finish = Integer.parseInt(m.group(3));
}
result += finish - start + 1;
Log.d(TAG, "Got CPU range " + start + " ~ " + finish);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to read cpu count");
e.printStackTrace();
}
return result;
}
// Return parsed cpuinfo contents
public static Map<String, String> getRawCpuInfo() {
Map<String, String> map = new HashMap<String, String>();
try {
Scanner s = new Scanner(new File("/proc/cpuinfo"));
while (s.hasNextLine()) {
String line = s.nextLine();
String[] vals = line.split(": ");
if (vals.length > 1) {
map.put(vals[0].trim(), vals[1].trim());
} else {
Log.d(TAG, "Failed to parse cpuinfo: " + line);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to read cpuinfo");
e.printStackTrace();
}
return map;
}
}

View File

@ -0,0 +1,31 @@
package org.opencv.engine;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
public class MarketConnector {
protected static final String OpenCVPackageNamePreffix = "org.opencv.lib";
private static final String TAG = "OpenCVEngine/MarketConnector";
protected Context mContext;
public MarketConnector(Context context) {
mContext = context;
}
public boolean InstallAppFromMarket(String AppID) {
Log.d(TAG, "Installing app: " + AppID);
boolean result = true;
try {
Uri uri = Uri.parse("market://details?id=" + AppID);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Installation failed");
result = false;
}
return result;
}
}

View File

@ -0,0 +1,33 @@
package org.opencv.engine;
/**
* Class provides Java interface to OpenCV Engine Service. Is synchronous with native OpenCVEngine class.
*/
interface OpenCVEngineInterface
{
/**
* @return Return service version
*/
int getEngineVersion();
/**
* Find installed OpenCV library
* @param OpenCV version
* @return Returns path to OpenCV native libs or empty string if OpenCV was not found
*/
String getLibPathByVersion(String version);
/**
* Try to install defined version of OpenCV from Google Play (Android Market).
* @param OpenCV version
* @return Returns true if installation was successful or OpenCV package has been already installed
*/
boolean installVersion(String version);
/**
* Return list of libraries in loading order separated by ";" symbol
* @param OpenCV version
* @return Returns OpenCV libraries names separated by symbol ";" in loading order
*/
String getLibraryList(String version);
}

View File

@ -0,0 +1,165 @@
package org.opencv.engine;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.XmlResourceParser;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.text.TextUtils;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
public class OpenCVEngineService extends Service {
private static final String TAG = "OpenCVEngine/Service";
private IBinder mEngineInterface = null;
private List<LibVariant> variants = new ArrayList<LibVariant>();
private class LibVariant {
public String version;
public List<String> files;
public void parseFile(XmlResourceParser p) {
try {
int eventType = p.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (p.getName().equals("library")) {
parseLibraryTag(p);
} else if (p.getName().equals("file")) {
parseFileTag(p);
}
}
eventType = p.next();
}
} catch (Exception e) {
Log.e(TAG, "Failed to parse xml library descriptor");
}
}
private void parseLibraryTag(XmlResourceParser p) {
version = p.getAttributeValue(null, "version");
files = new ArrayList<String>();
}
private void parseFileTag(XmlResourceParser p) {
files.add(p.getAttributeValue(null, "name"));
}
public boolean hasAllFiles(String path) {
boolean result = true;
List<String> actualFiles = Arrays.asList((new File(path)).list());
for (String f : files)
result &= actualFiles.contains(f);
return result;
}
public boolean isCompatible(String v) {
String[] expected = v.split("\\.");
String[] actual = version.split("\\.");
int i = 0;
for (; i < Math.min(expected.length, actual.length); ++i) {
int diff = Integer.valueOf(expected[i])
- Integer.valueOf(actual[i]);
if (diff > 0 || (diff != 0 && i == 0)) {
// requested version is greater than actual OR major version differs
return false;
} else if (diff < 0) {
// version is compatible
return true;
}
}
if (expected.length > i) {
// requested version is longer than actual - 2.4.11.2 and 2.4.11
return false;
}
return true;
}
public String getFileList() {
return TextUtils.join(";", files);
}
}
public void onCreate() {
Log.d(TAG, "Service starting");
for (Field field : R.xml.class.getDeclaredFields()) { // Build error here means that all config.xml files are missing (configuration problem)
Log.d(TAG, "Found config: " + field.getName());
final LibVariant lib = new LibVariant();
try {
final int id = field.getInt(R.xml.class);
final XmlResourceParser p = getResources().getXml(id);
lib.parseFile(p);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (lib.version != null
&& lib.files.size() != 0
&& lib.hasAllFiles(getApplication().getApplicationInfo().nativeLibraryDir)) {
variants.add(lib);
Log.d(TAG, "Added config: " + lib.version);
}
}
super.onCreate();
mEngineInterface = new OpenCVEngineInterface.Stub() {
@Override
public boolean installVersion(String version)
throws RemoteException {
// DO NOTHING
return false;
}
@Override
public String getLibraryList(String version) throws RemoteException {
Log.i(TAG, "getLibraryList(" + version + ")");
for (LibVariant lib : variants) {
Log.i(TAG, "checking " + lib.version + " ...");
if (lib.isCompatible(version))
return lib.getFileList();
}
return null;
}
@Override
public String getLibPathByVersion(String version)
throws RemoteException {
// TODO: support API 8
return getApplication().getApplicationInfo().nativeLibraryDir;
}
@Override
public int getEngineVersion() throws RemoteException {
int version = 3450;
try {
version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return version / 1000;
}
};
}
public IBinder onBind(Intent intent) {
Log.i(TAG, "Service onBind called for intent " + intent.toString());
return mEngineInterface;
}
public boolean onUnbind(Intent intent) {
Log.i(TAG, "Service onUnbind called for intent " + intent.toString());
return true;
}
public void OnDestroy() {
Log.i(TAG, "OpenCV Engine service destruction");
}
}

View File

@ -0,0 +1,113 @@
package org.opencv.engine.manager;
import org.opencv.engine.MarketConnector;
import org.opencv.engine.HardwareDetector;
import org.opencv.engine.OpenCVEngineInterface;
import org.opencv.engine.OpenCVEngineService;
import org.opencv.engine.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ManagerActivity extends Activity {
protected static final String TAG = "OpenCVEngine/Activity";
protected MarketConnector mMarket;
protected TextView mVersionText;
protected boolean mExtraInfo = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Class<OpenCVEngineService> c = OpenCVEngineService.class;
final String packageName = c.getPackage().getName();
mMarket = new MarketConnector(this);
Button updateButton = (Button) findViewById(R.id.CheckEngineUpdate);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!mMarket.InstallAppFromMarket(packageName)) {
Toast toast = Toast.makeText(getApplicationContext(),
"Google Play is not available", Toast.LENGTH_SHORT);
toast.show();
}
}
});
TextView aboutText = (TextView) findViewById(R.id.textView4);
aboutText.setText("About (" + packageName + ")");
if (mExtraInfo) {
TextView extraText = (TextView) findViewById(R.id.textView6);
extraText.setText(
"CPU count: "
+ HardwareDetector.getProcessorCount()
+ "\nABI: 0x"
+ Integer.toHexString(HardwareDetector.getAbi())
+ "\nFlags: "
+ TextUtils.join(";", HardwareDetector.getFlags())
+ "\nHardware: "
+ HardwareDetector.getHardware());
}
mVersionText = (TextView) findViewById(R.id.textView5);
if (!bindService(new Intent(this, c),
new OpenCVEngineServiceConnection(), Context.BIND_AUTO_CREATE)) {
Log.e(TAG, "Failed to bind to service:" + c.getName());
mVersionText.setText("not available");
} else {
Log.d(TAG, "Successfully bound to service:" + c.getName());
mVersionText.setText("available");
}
}
protected class OpenCVEngineServiceConnection implements ServiceConnection {
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "Handle: service disconnected");
}
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "Handle: service connected");
OpenCVEngineInterface engine = OpenCVEngineInterface.Stub
.asInterface(service);
if (engine == null) {
Log.e(TAG, "Cannot connect to OpenCV Manager Service!");
unbindService(this);
return;
}
Log.d(TAG, "Successful connection");
try {
String[] vars = { "2.4", "3.0" };
String res = new String();
for (String piece : vars) {
res += "\n\t" + piece + " -> "
+ engine.getLibraryList(piece);
}
mVersionText.setText("Path: "
+ engine.getLibPathByVersion(null) + res);
} catch (RemoteException e) {
e.printStackTrace();
Log.e(TAG, "Call failed");
}
unbindService(this);
}
};
}

View File

@ -0,0 +1,25 @@
How to select the proper version of OpenCV Manager
--------------------------------------------------
Since version 1.7 several packages of OpenCV Manager are built. Every package is targeted for some
specific hardware platform and includes corresponding OpenCV binaries. So, in all cases OpenCV
Manager uses built-in version of OpenCV. The new package selection logic in most cases simplifies
OpenCV installation on end user devices. In most cases OpenCV Manager may be installed automatically
from Google Play.
If Google Play is not available (i.e. on emulator, developer board, etc), you can install it
manually using adb tool:
adb install <path-to-OpenCV-sdk>/apk/OpenCV_<version>_Manager_<app_version>_<platform>.apk
Example: OpenCV_3.4.5-dev_Manager_3.45_armeabi-v7a.apk
Use the list of platforms below to determine proper OpenCV Manager package for your device:
- armeabi (ARMv5, ARMv6)
- armeabi-v7a (ARMv7-A + NEON)
- arm64-v8a
- mips
- mips64
- x86
- x86_64