📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
Add RapidOcrAndroidOnnx submodule
SWHLb08d8d0b951c
diff --git a/.gitmodules b/.gitmodulesnew file mode 100644index 0000000..3cff5a6--- /dev/null+++ b/.gitmodules@@ -0,0 +1,3 @@+[submodule "android/RapidOcrAndroidOnnx"]+ path = android/RapidOcrAndroidOnnx+ url = [email protected]:RapidAI/RapidOcrAndroidOnnx.gitdiff --git a/android/BaiPiaoOcrAndroidOnnx/.gitignore b/android/BaiPiaoOcrAndroidOnnx/.gitignoredeleted file mode 100755index 4aa86f7..0000000--- a/android/BaiPiaoOcrAndroidOnnx/.gitignore+++ /dev/null@@ -1,88 +0,0 @@-# Built application files-#*.apk-*.ap_-*.aab--# Files for the ART/Dalvik VM-*.dex--# Java class files-*.class--# Generated files-bin/-gen/-out/--# Gradle files-.gradle/-build/--# Local configuration file (sdk path, etc)-local.properties--# Proguard folder generated by Eclipse-proguard/--# Log Files-*.log--# Android Studio Navigation editor temp files-.navigation/--# Android Studio captures folder-captures/--# IntelliJ-*.iml-.idea-.idea/workspace.xml-.idea/tasks.xml-.idea/gradle.xml-.idea/assetWizardSettings.xml-.idea/dictionaries-.idea/libraries-.idea/caches-.idea/modules.xml-.idea/caches/build_file_checksums.ser-.idea/encodings.xml-.idea/vcs.xml-.idea/misc.xml-.idea/codeStyles--# Keystore files-# Uncomment the following lines if you do not want to check your keystore files in.-#*.jks-#*.keystore--# External native build folder generated in Android Studio 2.2 and later-.externalNativeBuild--# Google Services (e.g. APIs or Firebase)-# google-services.json--# Freeline-freeline.py-freeline/-freeline_project_description.json--# fastlane-fastlane/report.xml-fastlane/Preview.html-fastlane/screenshots-fastlane/test_output-fastlane/readme.md--# Version control-vcs.xml--# lint-lint/intermediates/-lint/generated/-lint/outputs/-lint/tmp/-# lint/reports/--.DS_Store-~*.xlsx-other/~*.xlsx\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/.gitignore b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/.gitignoredeleted file mode 100755index 449bc8e..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-/build-/.cxx-/src/main/sharedLibs-/src/main/assets-/src/sdk-/src/main/onnx\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/build.gradle b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/build.gradledeleted file mode 100755index 652528d..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/build.gradle+++ /dev/null@@ -1,58 +0,0 @@-apply plugin: 'com.android.library'-apply plugin: 'kotlin-android'-apply plugin: 'kotlin-android-extensions'--android {- compileSdkVersion 30- buildToolsVersion "30.0.2"-- defaultConfig {- minSdkVersion 21- targetSdkVersion 30- versionCode 2- versionName "1.1"-- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"- consumerProguardFiles "consumer-rules.pro"-- externalNativeBuild {- cmake {- abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64', 'x86'- }- }- }-- buildTypes {- release {- minifyEnabled false- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'- }- }-- externalNativeBuild {- cmake {- path "src/main/cpp/CMakeLists.txt"- version "3.10.2"- }- }-- libraryVariants.all {- variant ->- variant.outputs.all {- outputFileName = "${project.name}-${defaultConfig.versionName}.aar"- }- }-}--dependencies {- implementation fileTree(dir: "libs", include: ["*.jar"])- //Test- testImplementation 'junit:junit:4.12'- androidTestImplementation 'androidx.test.ext:junit:1.1.2'- androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'- //Kotlin- implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"- //Android- implementation 'androidx.core:core-ktx:1.3.2'- implementation 'androidx.appcompat:appcompat:1.2.0'-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/consumer-rules.pro b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/consumer-rules.prodeleted file mode 100755index e69de29..0000000diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/proguard-rules.pro b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/proguard-rules.prodeleted file mode 100755index 481bb43..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/proguard-rules.pro+++ /dev/null@@ -1,21 +0,0 @@-# Add project specific ProGuard rules here.-# You can control the set of applied configuration files using the-# proguardFiles setting in build.gradle.-#-# For more details, see-# http://developer.android.com/guide/developing/tools/proguard.html--# If your project uses WebView with JS, uncomment the following-# and specify the fully qualified class name to the JavaScript interface-# class:-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {-# public *;-#}--# Uncomment this to preserve the line number information for-# debugging stack traces.-#-keepattributes SourceFile,LineNumberTable--# If you keep the line number information, uncomment this to-# hide the original source file name.-#-renamesourcefileattribute SourceFile\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/androidTest/java/com/benjaminwan/ocrlibrary/ExampleInstrumentedTest.kt b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/androidTest/java/com/benjaminwan/ocrlibrary/ExampleInstrumentedTest.ktdeleted file mode 100755index a6f84fd..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/androidTest/java/com/benjaminwan/ocrlibrary/ExampleInstrumentedTest.kt+++ /dev/null@@ -1,24 +0,0 @@-package com.benjaminwan.ocrlibrary--import androidx.test.platform.app.InstrumentationRegistry-import androidx.test.ext.junit.runners.AndroidJUnit4--import org.junit.Test-import org.junit.runner.RunWith--import org.junit.Assert.*--/**- * Instrumented test, which will execute on an Android device.- *- * See [testing documentation](http://d.android.com/tools/testing).- */-@RunWith(AndroidJUnit4::class)-class ExampleInstrumentedTest {- @Test- fun useAppContext() {- // Context of the app under test.- val appContext = InstrumentationRegistry.getInstrumentation().targetContext- assertEquals("com.benjaminwan.ocrlibrary.test", appContext.packageName)- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/AndroidManifest.xml b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/AndroidManifest.xmldeleted file mode 100755index 0a3cce1..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/AndroidManifest.xml+++ /dev/null@@ -1,5 +0,0 @@-<manifest xmlns:android="http://schemas.android.com/apk/res/android"- package="com.benjaminwan.ocrlibrary">-- /-</manifest>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/CMakeLists.txt b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/CMakeLists.txtdeleted file mode 100755index a35cc13..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/CMakeLists.txt+++ /dev/null@@ -1,71 +0,0 @@-cmake_minimum_required(VERSION 3.4.1)--option(OCR_OPENMP "Enable OpenMP" ON)-set(OCR_OPENMP ON)--#ONNX-set(ONNX_DIR "${CMAKE_SOURCE_DIR}/../onnx")-find_package(ONNX REQUIRED)-if (ONNX_FOUND)- message(STATUS "ONNX_LIBS: ${ONNX_LIBS}")- message(STATUS "ONNX_INCLUDE_DIRS: ${ONNX_INCLUDE_DIRS}")-else ()- message(FATAL_ERROR "onnxruntime Not Found!")-endif (ONNX_FOUND)--## opencv 库-set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/../../sdk/native/jni")-find_package(OpenCV REQUIRED)-if (OpenCV_FOUND)- message(STATUS "OpenCV_LIBS: ${OpenCV_LIBS}")- message(STATUS "OpenCV_INCLUDE_DIRS: ${OpenCV_INCLUDE_DIRS}")-else ()- message(FATAL_ERROR "opencv Not Found!")-endif (OpenCV_FOUND)--# openmp-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fopenmp")-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")-set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fopenmp")--if (DEFINED ANDROID_NDK_MAJOR AND ${ANDROID_NDK_MAJOR} GREATER 20)- set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -static-openmp")-endif ()--set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fomit-frame-pointer -fstrict-aliasing -ffast-math")-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fomit-frame-pointer -fstrict-aliasing -ffast-math")--set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden")-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden")--# disable rtti and exceptions-#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions")--include_directories(include)-file(GLOB OCR_SRC src/*.cpp)-set(OCR_COMPILE_CODE ${OCR_SRC})--add_library(BaiPiaoOcr SHARED ${OCR_COMPILE_CODE})--if (OCR_OPENMP)- target_compile_definitions(BaiPiaoOcr PRIVATE __OPENMP__)-endif ()--find_library( # Sets the name of the path variable.- log-lib- log)--find_library(- android-lib- android-)--target_link_libraries(- BaiPiaoOcr- ${ONNX_LIBS}- ${OpenCV_LIBS}- android- z- ${log-lib}- ${android-lib}- jnigraphics)diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/AngleNet.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/AngleNet.hdeleted file mode 100755index cd678dd..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/AngleNet.h+++ /dev/null@@ -1,40 +0,0 @@-#ifndef __OCR_ANGLENET_H__-#define __OCR_ANGLENET_H__--#include "OcrStruct.h"-#include "onnx/onnxruntime_cxx_api.h"-#include <opencv/cv.hpp>-#include <android/asset_manager.h>-#include <android/asset_manager_jni.h>--class AngleNet {-public:- AngleNet();-- ~AngleNet();-- void setNumThread(int numOfThread);-- void initModel(AAssetManager *mgr, const std::string &name);-- std::vector<Angle> getAngles(std::vector<cv::Mat> &partImgs, bool doAngle, bool mostAngle);--private:- Ort::Session *session;- Ort::Env ortEnv = Ort::Env(ORT_LOGGING_LEVEL_ERROR, "AngleNet");- Ort::SessionOptions sessionOptions = Ort::SessionOptions();- int numThread = 0;-- std::vector<char *> inputNames;- std::vector<char *> outputNames;-- const float meanValues[3] = {127.5, 127.5, 127.5};- const float normValues[3] = {1.0 / 127.5, 1.0 / 127.5, 1.0 / 127.5};- const int dstWidth = 192;- const int dstHeight = 48;-- Angle getAngle(cv::Mat &src);-};---#endif //__OCR_ANGLENET_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/BitmapUtils.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/BitmapUtils.hdeleted file mode 100755index 31f3cc6..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/BitmapUtils.h+++ /dev/null@@ -1,13 +0,0 @@-#ifndef __OCR_LITE_BITMAP_UTILS_H__-#define __OCR_LITE_BITMAP_UTILS_H__--#include <jni.h>-#include "opencv2/core.hpp"-#include "opencv2/imgproc.hpp"--void bitmapToMat(JNIEnv *env, jobject bitmap, cv::Mat &dst);--void matToBitmap(JNIEnv *env, cv::Mat &src, jobject bitmap);---#endif //__OCR_LITE_BITMAP_UTILS_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/CrnnNet.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/CrnnNet.hdeleted file mode 100755index 6f6a81b..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/CrnnNet.h+++ /dev/null@@ -1,43 +0,0 @@-#ifndef __OCR_CRNNNET_H__-#define __OCR_CRNNNET_H__--#include "OcrStruct.h"-#include "onnx/onnxruntime_cxx_api.h"-#include <opencv/cv.hpp>-#include <android/asset_manager.h>-#include <android/asset_manager_jni.h>--class CrnnNet {-public:-- CrnnNet();-- ~CrnnNet();-- void setNumThread(int numOfThread);-- void initModel(AAssetManager *mgr, const std::string &name, const std::string &keysName);-- std::vector<TextLine> getTextLines(std::vector<cv::Mat> &partImg);--private:- Ort::Session *session;- Ort::Env ortEnv = Ort::Env(ORT_LOGGING_LEVEL_ERROR, "CrnnNet");- Ort::SessionOptions sessionOptions = Ort::SessionOptions();- int numThread = 0;- std::vector<char *> inputNames;- std::vector<char *> outputNames;-- const float meanValues[3] = {127.5, 127.5, 127.5};- const float normValues[3] = {1.0 / 127.5, 1.0 / 127.5, 1.0 / 127.5};- const int dstHeight = 32;-- std::vector<std::string> keys;-- TextLine scoreToTextLine(const std::vector<float> &outputData, int h, int w);-- TextLine getTextLine(cv::Mat &src);-};---#endif //__OCR_CRNNNET_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/DbNet.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/DbNet.hdeleted file mode 100755index 405212e..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/DbNet.h+++ /dev/null@@ -1,36 +0,0 @@-#ifndef __OCR_DBNET_H__-#define __OCR_DBNET_H__--#include "OcrStruct.h"-#include "onnx/onnxruntime_cxx_api.h"-#include <opencv/cv.hpp>-#include <android/asset_manager.h>-#include <android/asset_manager_jni.h>--class DbNet {-public:- DbNet();-- ~DbNet();-- void setNumThread(int numOfThread);-- void initModel(AAssetManager *mgr, const std::string &name);-- std::vector<TextBox> getTextBoxes(cv::Mat &src, ScaleParam &s, float boxScoreThresh,- float boxThresh, float unClipRatio);--private:- Ort::Session *session;- Ort::Env ortEnv = Ort::Env(ORT_LOGGING_LEVEL_ERROR, "DbNet");- Ort::SessionOptions sessionOptions = Ort::SessionOptions();- int numThread = 0;- std::vector<char *> inputNames;- std::vector<char *> outputNames;-- const float meanValues[3] = {0.485 * 255, 0.456 * 255, 0.406 * 255};- const float normValues[3] = {1.0 / 0.229 / 255.0, 1.0 / 0.224 / 255.0, 1.0 / 0.225 / 255.0};-};---#endif //__OCR_DBNET_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrLite.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrLite.hdeleted file mode 100755index 955e507..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrLite.h+++ /dev/null@@ -1,36 +0,0 @@-#ifndef __OCR_LITE_H__-#define __OCR_LITE_H__--#include "opencv2/core.hpp"-#include "onnx/onnxruntime_cxx_api.h"-#include "OcrStruct.h"-#include "DbNet.h"-#include "AngleNet.h"-#include "CrnnNet.h"--class OcrLite {-public:- OcrLite();-- ~OcrLite();-- void init(JNIEnv *jniEnv, jobject assetManager, int numOfThread, std::string detName,- std::string clsName, std::string recName, std::string keysName);-- //void initLogger(bool isDebug);-- //void Logger(const char *format, ...);-- OcrResult detect(cv::Mat &src, cv::Rect &originRect, ScaleParam &scale,- float boxScoreThresh, float boxThresh,- float unClipRatio, bool doAngle, bool mostAngle);--private:- bool isLOG = true;- DbNet dbNet;- AngleNet angleNet;- CrnnNet crnnNet;-};---#endif\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrResultUtils.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrResultUtils.hdeleted file mode 100755index f548ff4..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrResultUtils.h+++ /dev/null@@ -1,36 +0,0 @@-#ifndef __OCR_RESULT_UTILS_H__-#define __OCR_RESULT_UTILS_H__--#include <jni.h>-#include "OcrStruct.h"--class OcrResultUtils {-public:- OcrResultUtils(JNIEnv *env, OcrResult &ocrResult, jobject boxImg);-- ~OcrResultUtils();-- jobject getJObject();--private:- JNIEnv *jniEnv;- jobject jOcrResult;-- jclass newJListClass();-- jmethodID getListConstructor(jclass clazz);-- jobject getTextBlock(TextBlock &textBlock);-- jobject getTextBlocks(std::vector<TextBlock> &textBlocks);-- jobject newJPoint(cv::Point &point);-- jobject newJBoxPoint(std::vector<cv::Point> &boxPoint);-- jfloatArray newJScoreArray(std::vector<float> &scores);--};---#endif //__OCR_RESULT_UTILS_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrStruct.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrStruct.hdeleted file mode 100755index e51638c..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrStruct.h+++ /dev/null@@ -1,53 +0,0 @@-#ifndef __OCR_STRUCT_H__-#define __OCR_STRUCT_H__--#include "opencv2/core.hpp"-#include <vector>--struct ScaleParam {- int srcWidth;- int srcHeight;- int dstWidth;- int dstHeight;- float ratioWidth;- float ratioHeight;-};--struct TextBox {- std::vector<cv::Point> boxPoint;- float score;-};--struct Angle {- int index;- float score;- double time;-};--struct TextLine {- std::string text;- std::vector<float> charScores;- double time;-};--struct TextBlock {- std::vector<cv::Point> boxPoint;- float boxScore;- int angleIndex;- float angleScore;- double angleTime;- std::string text;- std::vector<float> charScores;- double crnnTime;- double blockTime;-};--struct OcrResult {- double dbNetTime;- std::vector<TextBlock> textBlocks;- cv::Mat boxImg;- double detectTime;- std::string strRes;-};--#endif //__OCR_STRUCT_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrUtils.h b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrUtils.hdeleted file mode 100755index ec0f536..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/OcrUtils.h+++ /dev/null@@ -1,98 +0,0 @@-#ifndef __OCR_UTILS_H__-#define __OCR_UTILS_H__--#include <opencv2/core.hpp>-#include "OcrStruct.h"-#include "onnx/onnxruntime_cxx_api.h"-#include <android/log.h>-#include <android/asset_manager.h>-#include <android/asset_manager_jni.h>--#define TAG "OcrLite"-#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,TAG,__VA_ARGS__)-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__)-#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG,__VA_ARGS__)-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)--#define __ENABLE_CONSOLE__ false-#define Logger(format, ...) {\- if(__ENABLE_CONSOLE__) LOGI(format,##__VA_ARGS__); \-}--template<typename T, typename... Ts>-static std::unique_ptr<T> makeUnique(Ts &&... params) {- return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));-}--template<typename T>-static double getMean(std::vector<T> &input) {- auto sum = accumulate(input.begin(), input.end(), 0.0);- return sum / input.size();-}--template<typename T>-static double getStdev(std::vector<T> &input, double mean) {- if (input.size() <= 1) return 0;- double accum = 0.0;- for_each(input.begin(), input.end(), [&](const double d) {- accum += (d - mean) * (d - mean);- });- double stdev = sqrt(accum / (input.size() - 1));- return stdev;-}--template<class T>-inline T clamp(T x, T min, T max) {- if (x > max)- return max;- if (x < min)- return min;- return x;-}--double getCurrentTime();--ScaleParam getScaleParam(cv::Mat &src, const float scale);--ScaleParam getScaleParam(cv::Mat &src, const int targetSize);--cv::RotatedRect getPartRect(std::vector<cv::Point> &box, float scaleWidth, float scaleHeight);--int getThickness(cv::Mat &boxImg);--std::vector<cv::Point2f> getBox(const cv::RotatedRect &rect);--void drawTextBox(cv::Mat &boxImg, cv::RotatedRect &rect, int thickness);--void drawTextBox(cv::Mat &boxImg, const std::vector<cv::Point> &box, int thickness);--void drawTextBoxes(cv::Mat &boxImg, std::vector<TextBox> &textBoxes, int thickness);--cv::Mat matRotateClockWise180(cv::Mat src);--cv::Mat matRotateClockWise90(cv::Mat src);--cv::Mat GetRotateCropImage(const cv::Mat &src, std::vector<cv::Point> box);--cv::Mat adjustTargetImg(cv::Mat &src, int dstWidth, int dstHeight);--std::vector<cv::Point2f> getMinBoxes(const cv::RotatedRect &boxRect, float &maxSideLen);--float boxScoreFast(const std::vector<cv::Point2f> &boxes, const cv::Mat &pred);--cv::RotatedRect unClip(std::vector<cv::Point2f> box, float unClipRatio);--std::vector<float> substractMeanNormalize(cv::Mat &src, const float *meanVals, const float *normVals);--std::vector<int> getAngleIndexes(std::vector<Angle> &angles);--std::vector<char *> getInputNames(Ort::Session *session);--std::vector<char *> getOutputNames(Ort::Session *session);--void *getModelDataFromAssets(AAssetManager *mgr, const char *modelName, int &size);--std::string jstringTostring(JNIEnv *env, jstring input);--#endif //__OCR_UTILS_H__diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/clipper.hpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/clipper.hppdeleted file mode 100755index cbe30db..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/include/clipper.hpp+++ /dev/null@@ -1,406 +0,0 @@-/*******************************************************************************-* *-* Author : Angus Johnson *-* Version : 6.4.2 *-* Date : 27 February 2017 *-* Website : http://www.angusj.com *-* Copyright : Angus Johnson 2010-2017 *-* *-* License: *-* Use, modification & distribution is subject to Boost Software License Ver 1. *-* http://www.boost.org/LICENSE_1_0.txt *-* *-* Attributions: *-* The code in this library is an extension of Bala Vatti's clipping algorithm: *-* "A generic solution to polygon clipping" *-* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *-* http://portal.acm.org/citation.cfm?id=129906 *-* *-* Computer graphics and geometric modeling: implementation and algorithms *-* By Max K. Agoston *-* Springer; 1 edition (January 4, 2005) *-* http://books.google.com/books?q=vatti+clipping+agoston *-* *-* See also: *-* "Polygon Offsetting by Computing Winding Numbers" *-* Paper no. DETC2005-85513 pp. 565-575 *-* ASME 2005 International Design Engineering Technical Conferences *-* and Computers and Information in Engineering Conference (IDETC/CIE2005) *-* September 24-28, 2005 , Long Beach, California, USA *-* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *-* *-*******************************************************************************/--#ifndef clipper_hpp-#define clipper_hpp--#define CLIPPER_VERSION "6.4.2"--//use_int32: When enabled 32bit ints are used instead of 64bit ints. This-//improve performance but coordinate values are limited to the range +/- 46340-//#define use_int32--//use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.-//#define use_xyz--//use_lines: Enables line clipping. Adds a very minor cost to performance.-#define use_lines--//use_deprecated: Enables temporary support for the obsolete functions-//#define use_deprecated--#include <vector>-#include <list>-#include <set>-#include <stdexcept>-#include <cstring>-#include <cstdlib>-#include <ostream>-#include <functional>-#include <queue>--namespace ClipperLib {-- enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };- enum PolyType { ptSubject, ptClip };-//By far the most widely used winding rules for polygon filling are-//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)-//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)-//see http://glprogramming.com/red/chapter11.html- enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };--#ifdef use_int32- typedef int cInt;- static cInt const loRange = 0x7FFF;- static cInt const hiRange = 0x7FFF;-#else- typedef signed long long cInt;- static cInt const loRange = 0x3FFFFFFF;- static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;- typedef signed long long long64; //used by Int128 class- typedef unsigned long long ulong64;--#endif-- struct IntPoint {- cInt X;- cInt Y;-#ifdef use_xyz- cInt Z;- IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};-#else- IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};-#endif-- friend inline bool operator== (const IntPoint& a, const IntPoint& b)- {- return a.X == b.X && a.Y == b.Y;- }- friend inline bool operator!= (const IntPoint& a, const IntPoint& b)- {- return a.X != b.X || a.Y != b.Y;- }- };-//-------------------------------------------------------------------------------- typedef std::vector< IntPoint > Path;- typedef std::vector< Path > Paths;-- inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}- inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}-- std::ostream& operator <<(std::ostream &s, const IntPoint &p);- std::ostream& operator <<(std::ostream &s, const Path &p);- std::ostream& operator <<(std::ostream &s, const Paths &p);-- struct DoublePoint- {- double X;- double Y;- DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}- DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}- };-//--------------------------------------------------------------------------------#ifdef use_xyz- typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);-#endif-- enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};- enum JoinType {jtSquare, jtRound, jtMiter};- enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};-- class PolyNode;- typedef std::vector< PolyNode* > PolyNodes;-- class PolyNode- {- public:- PolyNode();- virtual ~PolyNode(){};- Path Contour;- PolyNodes Childs;- PolyNode* Parent;- PolyNode* GetNext() const;- bool IsHole() const;- bool IsOpen() const;- int ChildCount() const;- private:- //PolyNode& operator =(PolyNode& other);- unsigned Index; //node index in Parent.Childs- bool m_IsOpen;- JoinType m_jointype;- EndType m_endtype;- PolyNode* GetNextSiblingUp() const;- void AddChild(PolyNode& child);- friend class Clipper; //to access Index- friend class ClipperOffset;- };-- class PolyTree: public PolyNode- {- public:- ~PolyTree(){ Clear(); };- PolyNode* GetFirst() const;- void Clear();- int Total() const;- private:- //PolyTree& operator =(PolyTree& other);- PolyNodes AllNodes;- friend class Clipper; //to access AllNodes- };-- bool Orientation(const Path &poly);- double Area(const Path &poly);- int PointInPolygon(const IntPoint &pt, const Path &path);-- void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);- void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);- void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);-- void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);- void CleanPolygon(Path& poly, double distance = 1.415);- void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);- void CleanPolygons(Paths& polys, double distance = 1.415);-- void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);- void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);- void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);-- void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);- void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);- void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);-- void ReversePath(Path& p);- void ReversePaths(Paths& p);-- struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };--//enums that are used internally ...- enum EdgeSide { esLeft = 1, esRight = 2};--//forward declarations (for stuff used internally) ...- struct TEdge;- struct IntersectNode;- struct LocalMinimum;- struct OutPt;- struct OutRec;- struct Join;-- typedef std::vector < OutRec* > PolyOutList;- typedef std::vector < TEdge* > EdgeList;- typedef std::vector < Join* > JoinList;- typedef std::vector < IntersectNode* > IntersectList;--//--------------------------------------------------------------------------------//ClipperBase is the ancestor to the Clipper class. It should not be-//instantiated directly. This class simply abstracts the conversion of sets of-//polygon coordinates into edge objects that are stored in a LocalMinima list.- class ClipperBase- {- public:- ClipperBase();- virtual ~ClipperBase();- virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);- bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);- virtual void Clear();- IntRect GetBounds();- bool PreserveCollinear() {return m_PreserveCollinear;};- void PreserveCollinear(bool value) {m_PreserveCollinear = value;};- protected:- void DisposeLocalMinimaList();- TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);- virtual void Reset();- TEdge* ProcessBound(TEdge* E, bool IsClockwise);- void InsertScanbeam(const cInt Y);- bool PopScanbeam(cInt &Y);- bool LocalMinimaPending();- bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);- OutRec* CreateOutRec();- void DisposeAllOutRecs();- void DisposeOutRec(PolyOutList::size_type index);- void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);- void DeleteFromAEL(TEdge *e);- void UpdateEdgeIntoAEL(TEdge *&e);-- typedef std::vector<LocalMinimum> MinimaList;- MinimaList::iterator m_CurrentLM;- MinimaList m_MinimaList;-- bool m_UseFullRange;- EdgeList m_edges;- bool m_PreserveCollinear;- bool m_HasOpenPaths;- PolyOutList m_PolyOuts;- TEdge *m_ActiveEdges;-- typedef std::priority_queue<cInt> ScanbeamList;- ScanbeamList m_Scanbeam;- };-//-------------------------------------------------------------------------------- class Clipper : public virtual ClipperBase- {- public:- Clipper(int initOptions = 0);- bool Execute(ClipType clipType,- Paths &solution,- PolyFillType fillType = pftEvenOdd);- bool Execute(ClipType clipType,- Paths &solution,- PolyFillType subjFillType,- PolyFillType clipFillType);- bool Execute(ClipType clipType,- PolyTree &polytree,- PolyFillType fillType = pftEvenOdd);- bool Execute(ClipType clipType,- PolyTree &polytree,- PolyFillType subjFillType,- PolyFillType clipFillType);- bool ReverseSolution() { return m_ReverseOutput; };- void ReverseSolution(bool value) {m_ReverseOutput = value;};- bool StrictlySimple() {return m_StrictSimple;};- void StrictlySimple(bool value) {m_StrictSimple = value;};- //set the callback function for z value filling on intersections (otherwise Z is 0)-#ifdef use_xyz- void ZFillFunction(ZFillCallback zFillFunc);-#endif- protected:- virtual bool ExecuteInternal();- private:- JoinList m_Joins;- JoinList m_GhostJoins;- IntersectList m_IntersectList;- ClipType m_ClipType;- typedef std::list<cInt> MaximaList;- MaximaList m_Maxima;- TEdge *m_SortedEdges;- bool m_ExecuteLocked;- PolyFillType m_ClipFillType;- PolyFillType m_SubjFillType;- bool m_ReverseOutput;- bool m_UsingPolyTree;- bool m_StrictSimple;-#ifdef use_xyz- ZFillCallback m_ZFill; //custom callback-#endif- void SetWindingCount(TEdge& edge);- bool IsEvenOddFillType(const TEdge& edge) const;- bool IsEvenOddAltFillType(const TEdge& edge) const;- void InsertLocalMinimaIntoAEL(const cInt botY);- void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);- void AddEdgeToSEL(TEdge *edge);- bool PopEdgeFromSEL(TEdge *&edge);- void CopyAELToSEL();- void DeleteFromSEL(TEdge *e);- void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);- bool IsContributing(const TEdge& edge) const;- bool IsTopHorz(const cInt XPos);- void DoMaxima(TEdge *e);- void ProcessHorizontals();- void ProcessHorizontal(TEdge *horzEdge);- void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);- OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);- OutRec* GetOutRec(int idx);- void AppendPolygon(TEdge *e1, TEdge *e2);- void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);- OutPt* AddOutPt(TEdge *e, const IntPoint &pt);- OutPt* GetLastOutPt(TEdge *e);- bool ProcessIntersections(const cInt topY);- void BuildIntersectList(const cInt topY);- void ProcessIntersectList();- void ProcessEdgesAtTopOfScanbeam(const cInt topY);- void BuildResult(Paths& polys);- void BuildResult2(PolyTree& polytree);- void SetHoleState(TEdge *e, OutRec *outrec);- void DisposeIntersectNodes();- bool FixupIntersectionOrder();- void FixupOutPolygon(OutRec &outrec);- void FixupOutPolyline(OutRec &outrec);- bool IsHole(TEdge *e);- bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);- void FixHoleLinkage(OutRec &outrec);- void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);- void ClearJoins();- void ClearGhostJoins();- void AddGhostJoin(OutPt *op, const IntPoint offPt);- bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);- void JoinCommonEdges();- void DoSimplePolygons();- void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);- void FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec);- void FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec);-#ifdef use_xyz- void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);-#endif- };-//-------------------------------------------------------------------------------- class ClipperOffset- {- public:- ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);- ~ClipperOffset();- void AddPath(const Path& path, JoinType joinType, EndType endType);- void AddPaths(const Paths& paths, JoinType joinType, EndType endType);- void Execute(Paths& solution, double delta);- void Execute(PolyTree& solution, double delta);- void Clear();- double MiterLimit;- double ArcTolerance;- private:- Paths m_destPolys;- Path m_srcPoly;- Path m_destPoly;- std::vector<DoublePoint> m_normals;- double m_delta, m_sinA, m_sin, m_cos;- double m_miterLim, m_StepsPerRad;- IntPoint m_lowest;- PolyNode m_polyNodes;-- void FixOrientations();- void DoOffset(double delta);- void OffsetPoint(int j, int& k, JoinType jointype);- void DoSquare(int j, int k);- void DoMiter(int j, int k, double r);- void DoRound(int j, int k);- };-//-------------------------------------------------------------------------------- class clipperException : public std::exception- {- public:- clipperException(const char* description): m_descr(description) {}- virtual ~clipperException() throw() {}- virtual const char* what() const throw() {return m_descr.c_str();}- private:- std::string m_descr;- };-//--------------------------------------------------------------------------------} //ClipperLib namespace--#endif //clipper_hpp--diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/AngleNet.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/AngleNet.cppdeleted file mode 100755index 66bab73..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/AngleNet.cpp+++ /dev/null@@ -1,132 +0,0 @@-#include "AngleNet.h"-#include "OcrUtils.h"-#include <numeric>--AngleNet::AngleNet() {}--AngleNet::~AngleNet() {- delete session;- for (auto name : inputNames) {- free(name);- }- for (auto name : outputNames) {- free(name);- }-}--void AngleNet::setNumThread(int numOfThread) {- numThread = numOfThread;- //===session options===- // Sets the number of threads used to parallelize the execution within nodes- // A value of 0 means ORT will pick a default- //sessionOptions.SetIntraOpNumThreads(numThread);- //set OMP_NUM_THREADS=16-- // Sets the number of threads used to parallelize the execution of the graph (across nodes)- // If sequential execution is enabled this value is ignored- // A value of 0 means ORT will pick a default- sessionOptions.SetInterOpNumThreads(numThread);-- // Sets graph optimization level- // ORT_DISABLE_ALL -> To disable all optimizations- // ORT_ENABLE_BASIC -> To enable basic optimizations (Such as redundant node removals)- // ORT_ENABLE_EXTENDED -> To enable extended optimizations (Includes level 1 + more complex optimizations like node fusions)- // ORT_ENABLE_ALL -> To Enable All possible opitmizations- sessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);-}--void AngleNet::initModel(AAssetManager *mgr, const std::string &name) {- int dbModelDataLength = 0;- void *dbModelData = getModelDataFromAssets(mgr, name.c_str(), dbModelDataLength);- session = new Ort::Session(ortEnv, dbModelData, dbModelDataLength,- sessionOptions);- free(dbModelData);- inputNames = getInputNames(session);- outputNames = getOutputNames(session);-}--Angle scoreToAngle(const std::vector<float> &outputData) {- int maxIndex = 0;- float maxScore = 0;- for (int i = 0; i < outputData.size(); i++) {- if (outputData[i] > maxScore) {- maxScore = outputData[i];- maxIndex = i;- }- }- return {maxIndex, maxScore};-}--Angle AngleNet::getAngle(cv::Mat &src) {-- std::vector<float> inputTensorValues = substractMeanNormalize(src, meanValues, normValues);-- std::array<int64_t, 4> inputShape{1, src.channels(), src.rows, src.cols};-- auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);-- Ort::Value inputTensor = Ort::Value::CreateTensor<float>(memoryInfo, inputTensorValues.data(),- inputTensorValues.size(),- inputShape.data(),- inputShape.size());- assert(inputTensor.IsTensor());-- auto outputTensor = session->Run(Ort::RunOptions{nullptr}, inputNames.data(), &inputTensor,- inputNames.size(), outputNames.data(), outputNames.size());-- assert(outputTensor.size() == 1 && outputTensor.front().IsTensor());-- std::vector<int64_t> outputShape = outputTensor[0].GetTensorTypeAndShapeInfo().GetShape();-- int64_t outputCount = std::accumulate(outputShape.begin(), outputShape.end(), 1,- std::multiplies<int64_t>());-- float *floatArray = outputTensor.front().GetTensorMutableData<float>();- std::vector<float> outputData(floatArray, floatArray + outputCount);- return scoreToAngle(outputData);-}--std::vector<Angle> AngleNet::getAngles(std::vector<cv::Mat> &partImgs,- bool doAngle, bool mostAngle) {- int size = partImgs.size();- std::vector<Angle> angles(size);- if (doAngle) {-#ifdef __OPENMP__-#pragma omp parallel for num_threads(numThread)-#endif- for (int i = 0; i < size; ++i) {- double startAngle = getCurrentTime();- auto angleImg = adjustTargetImg(partImgs[i], dstWidth, dstHeight);- Angle angle = getAngle(angleImg);- double endAngle = getCurrentTime();- angle.time = endAngle - startAngle;-- angles[i] = angle;-- }- } else {- for (int i = 0; i < size; ++i) {- angles[i] = Angle{-1, 0.f};- }- }- //Most Possible AngleIndex- if (doAngle && mostAngle) {- auto angleIndexes = getAngleIndexes(angles);- double sum = std::accumulate(angleIndexes.begin(), angleIndexes.end(), 0.0);- double halfPercent = angles.size() / 2.0f;- int mostAngleIndex;- if (sum < halfPercent) {//all angle set to 0- mostAngleIndex = 0;- } else {//all angle set to 1- mostAngleIndex = 1;- }- Logger("Set All Angle to mostAngleIndex(%d)", mostAngleIndex);- for (int i = 0; i < angles.size(); ++i) {- Angle angle = angles[i];- angle.index = mostAngleIndex;- angles.at(i) = angle;- }- }-- return angles;-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/BitmapUtils.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/BitmapUtils.cppdeleted file mode 100755index 286f3cb..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/BitmapUtils.cpp+++ /dev/null@@ -1,107 +0,0 @@-#include "BitmapUtils.h"-#include <android/bitmap.h>-#include <OcrUtils.h>--using namespace cv;--void bitmapToMat(JNIEnv *env, jobject bitmap, Mat &dst) {- AndroidBitmapInfo info;- void *pixels = 0;-- try {- LOGI("nBitmapToMat");- CV_Assert(AndroidBitmap_getInfo(env, bitmap, &info) >= 0);- CV_Assert(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 ||- info.format == ANDROID_BITMAP_FORMAT_RGB_565);- CV_Assert(AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0);- CV_Assert(pixels);- dst.create(info.height, info.width, CV_8UC4);- if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {- LOGI("nBitmapToMat: RGBA_8888 -> CV_8UC4");- Mat tmp(info.height, info.width, CV_8UC4, pixels);- //if (needUnPremultiplyAlpha) cvtColor(tmp, dst, COLOR_mRGBA2RGBA);- //else- tmp.copyTo(dst);- } else {- // info.format == ANDROID_BITMAP_FORMAT_RGB_565- LOGI("nBitmapToMat: RGB_565 -> CV_8UC4");- Mat tmp(info.height, info.width, CV_8UC2, pixels);- cvtColor(tmp, dst, COLOR_BGR5652RGBA);- }- AndroidBitmap_unlockPixels(env, bitmap);- return;- } catch (const cv::Exception &e) {- AndroidBitmap_unlockPixels(env, bitmap);- LOGE("nBitmapToMat caught cv::Exception: %s", e.what());- jclass je = env->FindClass("java/lang/Exception");- if (!je) je = env->FindClass("java/lang/Exception");- env->ThrowNew(je, e.what());- return;- } catch (...) {- AndroidBitmap_unlockPixels(env, bitmap);- LOGE("nBitmapToMat caught unknown exception (...)");- jclass je = env->FindClass("java/lang/Exception");- env->ThrowNew(je, "Unknown exception in JNI code {nBitmapToMat}");- return;- }-}--void matToBitmap(JNIEnv *env, cv::Mat &src, jobject bitmap) {- AndroidBitmapInfo info;- void *pixels = 0;-- try {- LOGI("nMatToBitmap");- CV_Assert(AndroidBitmap_getInfo(env, bitmap, &info) >= 0);- CV_Assert(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 ||- info.format == ANDROID_BITMAP_FORMAT_RGB_565);- CV_Assert(src.dims == 2 && info.height == (uint32_t) src.rows &&- info.width == (uint32_t) src.cols);- CV_Assert(src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4);- CV_Assert(AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0);- CV_Assert(pixels);- if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {- Mat tmp(info.height, info.width, CV_8UC4, pixels);- if (src.type() == CV_8UC1) {- LOGI("nMatToBitmap: CV_8UC1 -> RGBA_8888");- cvtColor(src, tmp, COLOR_GRAY2RGBA);- } else if (src.type() == CV_8UC3) {- LOGI("nMatToBitmap: CV_8UC3 -> RGBA_8888");- cvtColor(src, tmp, COLOR_RGB2RGBA);- } else if (src.type() == CV_8UC4) {- LOGI("nMatToBitmap: CV_8UC4 -> RGBA_8888");- //if (needPremultiplyAlpha) cvtColor(src, tmp, COLOR_RGBA2mRGBA);- //else- src.copyTo(tmp);- }- } else {- // info.format == ANDROID_BITMAP_FORMAT_RGB_565- Mat tmp(info.height, info.width, CV_8UC2, pixels);- if (src.type() == CV_8UC1) {- LOGI("nMatToBitmap: CV_8UC1 -> RGB_565");- cvtColor(src, tmp, COLOR_GRAY2BGR565);- } else if (src.type() == CV_8UC3) {- LOGI("nMatToBitmap: CV_8UC3 -> RGB_565");- cvtColor(src, tmp, COLOR_RGB2BGR565);- } else if (src.type() == CV_8UC4) {- LOGI("nMatToBitmap: CV_8UC4 -> RGB_565");- cvtColor(src, tmp, COLOR_RGBA2BGR565);- }- }- AndroidBitmap_unlockPixels(env, bitmap);- return;- } catch (const cv::Exception &e) {- AndroidBitmap_unlockPixels(env, bitmap);- LOGE("nMatToBitmap caught cv::Exception: %s", e.what());- jclass je = env->FindClass("java/lang/Exception");- if (!je) je = env->FindClass("java/lang/Exception");- env->ThrowNew(je, e.what());- return;- } catch (...) {- AndroidBitmap_unlockPixels(env, bitmap);- LOGE("nMatToBitmap caught unknown exception (...)");- jclass je = env->FindClass("java/lang/Exception");- env->ThrowNew(je, "Unknown exception in JNI code {nMatToBitmap}");- return;- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/CrnnNet.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/CrnnNet.cppdeleted file mode 100755index 8ec23ab..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/CrnnNet.cpp+++ /dev/null@@ -1,168 +0,0 @@-#include "CrnnNet.h"-#include "OcrUtils.h"-#include <numeric>--CrnnNet::CrnnNet() {}--CrnnNet::~CrnnNet() {- delete session;- for (auto name : inputNames) {- free(name);- }- for (auto name : outputNames) {- free(name);- }-}--void CrnnNet::setNumThread(int numOfThread) {- numThread = numOfThread;- //===session options===- // Sets the number of threads used to parallelize the execution within nodes- // A value of 0 means ORT will pick a default- //sessionOptions.SetIntraOpNumThreads(numThread);- //set OMP_NUM_THREADS=16-- // Sets the number of threads used to parallelize the execution of the graph (across nodes)- // If sequential execution is enabled this value is ignored- // A value of 0 means ORT will pick a default- sessionOptions.SetInterOpNumThreads(numThread);-- // Sets graph optimization level- // ORT_DISABLE_ALL -> To disable all optimizations- // ORT_ENABLE_BASIC -> To enable basic optimizations (Such as redundant node removals)- // ORT_ENABLE_EXTENDED -> To enable extended optimizations (Includes level 1 + more complex optimizations like node fusions)- // ORT_ENABLE_ALL -> To Enable All possible opitmizations- sessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);-}--char *readKeysFromAssets(AAssetManager *mgr, const std::string &keysName) {- //LOGI("readKeysFromAssets start...");- if (mgr == NULL) {- LOGE(" %s", "AAssetManager==NULL");- return NULL;- }- char *buffer;- /*获取文件名并打开*/- AAsset *asset = AAssetManager_open(mgr, keysName.c_str(), AASSET_MODE_UNKNOWN);- if (asset == NULL) {- LOGE(" %s", "asset==NULL");- return NULL;- }- /*获取文件大小*/- off_t bufferSize = AAsset_getLength(asset);- //LOGI("file size : %d", bufferSize);- buffer = (char *) malloc(bufferSize + 1);- buffer[bufferSize] = 0;- int numBytesRead = AAsset_read(asset, buffer, bufferSize);- //LOGI("readKeysFromAssets: %d", numBytesRead);- /*关闭文件*/- AAsset_close(asset);- //LOGI("readKeysFromAssets exit...");- return buffer;-}--void CrnnNet::initModel(AAssetManager *mgr, const std::string &name, const std::string &keysName) {- int dbModelDataLength = 0;- void *dbModelData = getModelDataFromAssets(mgr, name.c_str(), dbModelDataLength);- session = new Ort::Session(ortEnv, dbModelData, dbModelDataLength,- sessionOptions);- free(dbModelData);- inputNames = getInputNames(session);- outputNames = getOutputNames(session);-- //load keys- char *buffer = readKeysFromAssets(mgr, keysName);- if (buffer != NULL) {- std::istringstream inStr(buffer);- std::string line;- while (getline(inStr, line)) {- keys.emplace_back(line);- }- free(buffer);- } else {- LOGE(" txt file not found");- return;- }- keys.insert(keys.begin(),- "#"); // blank char for ctc- keys.emplace_back(" ");- LOGI("keys size(%d)", keys.size());-}--template<class ForwardIterator>-inline static size_t argmax(ForwardIterator first, ForwardIterator last) {- return std::distance(first, std::max_element(first, last));-}--TextLine CrnnNet::scoreToTextLine(const std::vector<float> &outputData, int h, int w) {- int keySize = keys.size();- std::string strRes;- std::vector<float> scores;- int lastIndex = 0;- int maxIndex;- float maxValue;-- for (int i = 0; i < h; i++) {- maxIndex = int(argmax(&outputData[i * w], &outputData[(i + 1) * w]));- maxValue = float(*std::max_element(&outputData[i * w], &outputData[(i + 1) * w]));-- if (maxIndex > 0 && maxIndex < keySize && (!(i > 0 && maxIndex == lastIndex))) {- scores.emplace_back(maxValue);- strRes.append(keys[maxIndex]);- }- lastIndex = maxIndex;- }- return {strRes, scores};-}--TextLine CrnnNet::getTextLine(cv::Mat &src) {- float scale = (float) dstHeight / (float) src.rows;- int dstWidth = int((float) src.cols * scale);-- cv::Mat srcResize;- resize(src, srcResize, cv::Size(dstWidth, dstHeight));-- std::vector<float> inputTensorValues = substractMeanNormalize(srcResize, meanValues,- normValues);-- std::array<int64_t, 4> inputShape{1, srcResize.channels(), srcResize.rows, srcResize.cols};-- auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);-- Ort::Value inputTensor = Ort::Value::CreateTensor<float>(memoryInfo, inputTensorValues.data(),- inputTensorValues.size(),- inputShape.data(),- inputShape.size());- assert(inputTensor.IsTensor());-- auto outputTensor = session->Run(Ort::RunOptions{nullptr}, inputNames.data(), &inputTensor,- inputNames.size(), outputNames.data(), outputNames.size());-- assert(outputTensor.size() == 1 && outputTensor.front().IsTensor());-- std::vector<int64_t> outputShape = outputTensor[0].GetTensorTypeAndShapeInfo().GetShape();-- int64_t outputCount = std::accumulate(outputShape.begin(), outputShape.end(), 1,- std::multiplies<int64_t>());-- float *floatArray = outputTensor.front().GetTensorMutableData<float>();- std::vector<float> outputData(floatArray, floatArray + outputCount);- return scoreToTextLine(outputData, outputShape[1], outputShape[2]);-}--std::vector<TextLine> CrnnNet::getTextLines(std::vector<cv::Mat> &partImg) {- int size = partImg.size();- std::vector<TextLine> textLines(size);-#ifdef __OPENMP__-#pragma omp parallel for num_threads(numThread)-#endif- for (int i = 0; i < size; ++i) {- //getTextLine- double startCrnnTime = getCurrentTime();- TextLine textLine = getTextLine(partImg[i]);- double endCrnnTime = getCurrentTime();- textLine.time = endCrnnTime - startCrnnTime;- textLines[i] = textLine;- }- return textLines;-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/DbNet.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/DbNet.cppdeleted file mode 100755index 6941142..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/DbNet.cpp+++ /dev/null@@ -1,160 +0,0 @@-#include "DbNet.h"-#include "OcrUtils.h"-#include <numeric>--DbNet::DbNet() {}--DbNet::~DbNet() {- delete session;- for (auto name : inputNames) {- free(name);- }- for (auto name : outputNames) {- free(name);- }-}--void DbNet::setNumThread(int numOfThread) {- numThread = numOfThread;- //===session options===- // Sets the number of threads used to parallelize the execution within nodes- // A value of 0 means ORT will pick a default- //sessionOptions.SetIntraOpNumThreads(numThread);- //set OMP_NUM_THREADS=16-- // Sets the number of threads used to parallelize the execution of the graph (across nodes)- // If sequential execution is enabled this value is ignored- // A value of 0 means ORT will pick a default- sessionOptions.SetInterOpNumThreads(numThread);-- // Sets graph optimization level- // ORT_DISABLE_ALL -> To disable all optimizations- // ORT_ENABLE_BASIC -> To enable basic optimizations (Such as redundant node removals)- // ORT_ENABLE_EXTENDED -> To enable extended optimizations (Includes level 1 + more complex optimizations like node fusions)- // ORT_ENABLE_ALL -> To Enable All possible opitmizations- sessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);-}--void DbNet::initModel(AAssetManager *mgr, const std::string &name) {- int dbModelDataLength = 0;- void *dbModelData = getModelDataFromAssets(mgr, name.c_str(), dbModelDataLength);- session = new Ort::Session(ortEnv, dbModelData, dbModelDataLength, sessionOptions);- free(dbModelData);- inputNames = getInputNames(session);- outputNames = getOutputNames(session);-}--std::vector<TextBox> findRsBoxes(const cv::Mat &predMat, const cv::Mat &dilateMat, ScaleParam &s,- const float boxScoreThresh, const float unClipRatio) {- const int longSideThresh = 3;//minBox 长边门限- const int maxCandidates = 1000;-- std::vector<std::vector<cv::Point>> contours;- std::vector<cv::Vec4i> hierarchy;-- cv::findContours(dilateMat, contours, hierarchy, cv::RETR_LIST,- cv::CHAIN_APPROX_SIMPLE);-- int numContours = contours.size() >= maxCandidates ? maxCandidates : contours.size();-- std::vector<TextBox> rsBoxes;-- for (int i = 0; i < numContours; i++) {- if (contours[i].size() <= 2) {- continue;- }- cv::RotatedRect minAreaRect = cv::minAreaRect(contours[i]);-- float longSide;- std::vector<cv::Point2f> minBoxes = getMinBoxes(minAreaRect, longSide);-- if (longSide < longSideThresh) {- continue;- }-- float boxScore = boxScoreFast(minBoxes, predMat);- if (boxScore < boxScoreThresh)- continue;-- //-----unClip------ cv::RotatedRect clipRect = unClip(minBoxes, unClipRatio);- if (clipRect.size.height < 1.001 && clipRect.size.width < 1.001) {- continue;- }- //-----unClip------- std::vector<cv::Point2f> clipMinBoxes = getMinBoxes(clipRect, longSide);- if (longSide < longSideThresh + 2)- continue;-- std::vector<cv::Point> intClipMinBoxes;-- for (int p = 0; p < clipMinBoxes.size(); p++) {- float x = clipMinBoxes[p].x / s.ratioWidth;- float y = clipMinBoxes[p].y / s.ratioHeight;- int ptX = (std::min)((std::max)(int(x), 0), s.srcWidth - 1);- int ptY = (std::min)((std::max)(int(y), 0), s.srcHeight - 1);- cv::Point point{ptX, ptY};- intClipMinBoxes.push_back(point);- }- rsBoxes.push_back(TextBox{intClipMinBoxes, boxScore});- }- reverse(rsBoxes.begin(), rsBoxes.end());- return rsBoxes;-}--std::vector<TextBox>-DbNet::getTextBoxes(cv::Mat &src, ScaleParam &s, float boxScoreThresh, float boxThresh,- float unClipRatio) {- cv::Mat srcResize;- resize(src, srcResize, cv::Size(s.dstWidth, s.dstHeight));- std::vector<float> inputTensorValues = substractMeanNormalize(srcResize, meanValues,- normValues);-- std::array<int64_t, 4> inputShape{1, srcResize.channels(), srcResize.rows, srcResize.cols};-- auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);-- Ort::Value inputTensor = Ort::Value::CreateTensor<float>(memoryInfo, inputTensorValues.data(),- inputTensorValues.size(),- inputShape.data(),- inputShape.size());- assert(inputTensor.IsTensor());- auto outputTensor = session->Run(Ort::RunOptions{nullptr}, inputNames.data(), &inputTensor,- inputNames.size(), outputNames.data(), outputNames.size());- assert(outputTensor.size() == 1 && outputTensor.front().IsTensor());- std::vector<int64_t> outputShape = outputTensor[0].GetTensorTypeAndShapeInfo().GetShape();- int64_t outputCount = std::accumulate(outputShape.begin(), outputShape.end(), 1,- std::multiplies<int64_t>());- float *floatArray = outputTensor.front().GetTensorMutableData<float>();- std::vector<float> outputData(floatArray, floatArray + outputCount);-- //-----Data preparation------ int outHeight = outputShape[2];- int outWidth = outputShape[3];- int area = outHeight * outWidth;-- std::vector<float> predData(area, 0.0);- std::vector<unsigned char> cbufData(area, ' ');-- for (int i = 0; i < area; i++) {- predData[i] = float(outputData[i]);- cbufData[i] = (unsigned char) ((outputData[i]) * 255);- }-- cv::Mat predMat(outHeight, outWidth, CV_32F, (float *) predData.data());- cv::Mat cBufMat(outHeight, outWidth, CV_8UC1, (unsigned char *) cbufData.data());-- //-----boxThresh------ const double maxValue = 255;- const double threshold = boxThresh * 255;- cv::Mat thresholdMat;- cv::threshold(cBufMat, thresholdMat, threshold, maxValue, cv::THRESH_BINARY);-- //-----dilate------ cv::Mat dilateMat;- cv::Mat dilateElement = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2, 2));- cv::dilate(thresholdMat, dilateMat, dilateElement);-- return findRsBoxes(predMat, dilateMat, s, boxScoreThresh, unClipRatio);-}diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrLite.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrLite.cppdeleted file mode 100755index 7c462b6..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrLite.cpp+++ /dev/null@@ -1,159 +0,0 @@-#include <android/asset_manager.h>-#include <android/asset_manager_jni.h>-#include "OcrLite.h"-#include "OcrUtils.h"--OcrLite::OcrLite() {}--OcrLite::~OcrLite() {}--void OcrLite::init(JNIEnv *jniEnv, jobject assetManager, int numThread, std::string detName,- std::string clsName, std::string recName, std::string keysName) {- AAssetManager *mgr = AAssetManager_fromJava(jniEnv, assetManager);- if (mgr == NULL) {- LOGE(" %s", "AAssetManager==NULL");- }-- Logger("--- Init DbNet ---\n");- dbNet.setNumThread(numThread);- dbNet.initModel(mgr, detName);-- Logger("--- Init AngleNet ---\n");- angleNet.setNumThread(numThread);- angleNet.initModel(mgr, clsName);-- Logger("--- Init CrnnNet ---\n");- crnnNet.setNumThread(numThread);- crnnNet.initModel(mgr, recName, keysName);-- LOGI("初始化完成!");-}--/*void OcrLite::initLogger(bool isDebug) {- isLOG = isDebug;-}--void OcrLite::Logger(const char *format, ...) {- if (!isLOG) return;- char *buffer = (char *) malloc(8192);- va_list args;- va_start(args, format);- vsprintf(buffer, format, args);- va_end(args);- if (isLOG) LOGI("%s", buffer);- free(buffer);-}*/--std::vector<cv::Mat> getPartImages(cv::Mat &src, std::vector<TextBox> &textBoxes) {- std::vector<cv::Mat> partImages;- for (int i = 0; i < textBoxes.size(); ++i) {- cv::Mat partImg = GetRotateCropImage(src, textBoxes[i].boxPoint);- partImages.emplace_back(partImg);- }- return partImages;-}--OcrResult OcrLite::detect(cv::Mat &src, cv::Rect &originRect, ScaleParam &scale,- float boxScoreThresh, float boxThresh,- float unClipRatio, bool doAngle, bool mostAngle) {-- cv::Mat textBoxPaddingImg = src.clone();- int thickness = getThickness(src);-- Logger("=====Start detect=====");- Logger("ScaleParam(sw:%d,sh:%d,dw:%d,dh:%d,%f,%f)", scale.srcWidth, scale.srcHeight,- scale.dstWidth, scale.dstHeight,- scale.ratioWidth, scale.ratioHeight);-- Logger("---------- step: dbNet getTextBoxes ----------");- double startTime = getCurrentTime();- std::vector<TextBox> textBoxes = dbNet.getTextBoxes(src, scale, boxScoreThresh, boxThresh, unClipRatio);- Logger("TextBoxesSize(%ld)", textBoxes.size());- double endDbNetTime = getCurrentTime();- double dbNetTime = endDbNetTime - startTime;- Logger("dbNetTime(%fms)", dbNetTime);-- for (int i = 0; i < textBoxes.size(); ++i) {- Logger("TextBox[%d][score(%f),[x: %d, y: %d], [x: %d, y: %d], [x: %d, y: %d], [x: %d, y: %d]]",- i,- textBoxes[i].score,- textBoxes[i].boxPoint[0].x, textBoxes[i].boxPoint[0].y,- textBoxes[i].boxPoint[1].x, textBoxes[i].boxPoint[1].y,- textBoxes[i].boxPoint[2].x, textBoxes[i].boxPoint[2].y,- textBoxes[i].boxPoint[3].x, textBoxes[i].boxPoint[3].y);- }-- Logger("---------- step: drawTextBoxes ----------");- drawTextBoxes(textBoxPaddingImg, textBoxes, thickness);-- //---------- getPartImages ----------- std::vector<cv::Mat> partImages = getPartImages(src, textBoxes);-- Logger("---------- step: angleNet getAngles ----------");- std::vector<Angle> angles;- angles = angleNet.getAngles(partImages, doAngle, mostAngle);-- //Log Angles- for (int i = 0; i < angles.size(); ++i) {- Logger("angle[%d][index(%d), score(%f), time(%fms)]", i, angles[i].index, angles[i].score, angles[i].time);- }-- //Rotate partImgs- for (int i = 0; i < partImages.size(); ++i) {- if (angles[i].index == 1) {- partImages.at(i) = matRotateClockWise180(partImages[i]);- }- }-- Logger("---------- step: crnnNet getTextLine ----------");- std::vector<TextLine> textLines = crnnNet.getTextLines(partImages);- //Log TextLines- for (int i = 0; i < textLines.size(); ++i) {- Logger("textLine[%d](%s)", i, textLines[i].text.c_str());- std::ostringstream txtScores;- for (int s = 0; s < textLines[i].charScores.size(); ++s) {- if (s == 0) {- txtScores << textLines[i].charScores[s];- } else {- txtScores << " ," << textLines[i].charScores[s];- }- }- Logger("textScores[%d]{%s}", i, std::string(txtScores.str()).c_str());- Logger("crnnTime[%d](%fms)", i, textLines[i].time);- }-- std::vector<TextBlock> textBlocks;- for (int i = 0; i < textLines.size(); ++i) {- std::vector<cv::Point> boxPoint = std::vector<cv::Point>(4);- int padding = originRect.x;//padding conversion- boxPoint[0] = cv::Point(textBoxes[i].boxPoint[0].x - padding, textBoxes[i].boxPoint[0].y - padding);- boxPoint[1] = cv::Point(textBoxes[i].boxPoint[1].x - padding, textBoxes[i].boxPoint[1].y - padding);- boxPoint[2] = cv::Point(textBoxes[i].boxPoint[2].x - padding, textBoxes[i].boxPoint[2].y - padding);- boxPoint[3] = cv::Point(textBoxes[i].boxPoint[3].x - padding, textBoxes[i].boxPoint[3].y - padding);- TextBlock textBlock{boxPoint, textBoxes[i].score, angles[i].index, angles[i].score,- angles[i].time, textLines[i].text, textLines[i].charScores, textLines[i].time,- angles[i].time + textLines[i].time};- textBlocks.emplace_back(textBlock);- }-- double endTime = getCurrentTime();- double fullTime = endTime - startTime;- Logger("=====End detect=====");- Logger("FullDetectTime(%fms)", fullTime);-- //cropped to original size- cv::Mat textBoxImg;- if (originRect.x > 0 && originRect.y > 0) {- textBoxPaddingImg(originRect).copyTo(textBoxImg);- } else {- textBoxImg = textBoxPaddingImg;- }-- std::string strRes;- for (int i = 0; i < textBlocks.size(); ++i) {- strRes.append(textBlocks[i].text);- strRes.append("\n");- }-- return OcrResult{dbNetTime, textBlocks, textBoxImg, fullTime, strRes};-}diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrResultUtils.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrResultUtils.cppdeleted file mode 100755index af718a9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrResultUtils.cpp+++ /dev/null@@ -1,111 +0,0 @@-#include <OcrUtils.h>-#include "OcrResultUtils.h"--OcrResultUtils::OcrResultUtils(JNIEnv *env, OcrResult &ocrResult, jobject boxImg) {- jniEnv = env;-- jclass jOcrResultClass = env->FindClass("com/benjaminwan/ocrlibrary/OcrResult");-- if (jOcrResultClass == NULL) {- LOGE("OcrResult class is null");- }-- jmethodID jOcrResultConstructor = env->GetMethodID(jOcrResultClass, "<init>",- "(DLjava/util/ArrayList;Landroid/graphics/Bitmap;DLjava/lang/String;)V");-- jobject textBlocks = getTextBlocks(ocrResult.textBlocks);- jdouble dbNetTime = (jdouble) ocrResult.dbNetTime;- jdouble detectTime = (jdouble) ocrResult.detectTime;- jstring jStrRest = jniEnv->NewStringUTF(ocrResult.strRes.c_str());-- jOcrResult = env->NewObject(jOcrResultClass, jOcrResultConstructor, dbNetTime,- textBlocks, boxImg, detectTime, jStrRest);-}--OcrResultUtils::~OcrResultUtils() {- jniEnv = NULL;-}--jobject OcrResultUtils::getJObject() {- return jOcrResult;-}--jclass OcrResultUtils::newJListClass() {- jclass clazz = jniEnv->FindClass("java/util/ArrayList");- if (clazz == NULL) {- LOGE("ArrayList class is null");- return NULL;- }- return clazz;-}--jmethodID OcrResultUtils::getListConstructor(jclass clazz) {- jmethodID constructor = jniEnv->GetMethodID(clazz, "<init>", "()V");- return constructor;-}--jobject OcrResultUtils::newJPoint(cv::Point &point) {- jclass clazz = jniEnv->FindClass("com/benjaminwan/ocrlibrary/Point");- if (clazz == NULL) {- LOGE("Point class is null");- return NULL;- }- jmethodID constructor = jniEnv->GetMethodID(clazz, "<init>", "(II)V");- jobject obj = jniEnv->NewObject(clazz, constructor, point.x, point.y);- return obj;-}--jobject OcrResultUtils::newJBoxPoint(std::vector<cv::Point> &boxPoint) {- jclass jListClass = newJListClass();- jmethodID jListConstructor = getListConstructor(jListClass);- jobject jList = jniEnv->NewObject(jListClass, jListConstructor);- jmethodID jListAdd = jniEnv->GetMethodID(jListClass, "add", "(Ljava/lang/Object;)Z");-- for (auto point : boxPoint) {- jobject jPoint = newJPoint(point);- jniEnv->CallBooleanMethod(jList, jListAdd, jPoint);- }- return jList;-}--jobject OcrResultUtils::getTextBlock(TextBlock &textBlock) {- jobject jBoxPint = newJBoxPoint(textBlock.boxPoint);- jfloat jBoxScore = (jfloat) textBlock.boxScore;- jfloat jAngleScore = (jfloat) textBlock.angleScore;- jdouble jAngleTime = (jdouble) textBlock.angleTime;- jstring jText = jniEnv->NewStringUTF(textBlock.text.c_str());- jobject jCharScores = newJScoreArray(textBlock.charScores);- jdouble jCrnnTime = (jdouble) textBlock.crnnTime;- jdouble jBlockTime = (jdouble) textBlock.blockTime;- jclass clazz = jniEnv->FindClass("com/benjaminwan/ocrlibrary/TextBlock");- if (clazz == NULL) {- LOGE("TextBlock class is null");- return NULL;- }- jmethodID constructor = jniEnv->GetMethodID(clazz, "<init>",- "(Ljava/util/ArrayList;FIFDLjava/lang/String;[FDD)V");- jobject obj = jniEnv->NewObject(clazz, constructor, jBoxPint, jBoxScore, textBlock.angleIndex,- jAngleScore, jAngleTime, jText, jCharScores, jCrnnTime,- jBlockTime);- return obj;-}--jobject OcrResultUtils::getTextBlocks(std::vector<TextBlock> &textBlocks) {- jclass jListClass = newJListClass();- jmethodID jListConstructor = getListConstructor(jListClass);- jobject jList = jniEnv->NewObject(jListClass, jListConstructor);- jmethodID jListAdd = jniEnv->GetMethodID(jListClass, "add", "(Ljava/lang/Object;)Z");-- for (int i = 0; i < textBlocks.size(); ++i) {- auto textBlock = textBlocks[i];- jobject jTextBlock = getTextBlock(textBlock);- jniEnv->CallBooleanMethod(jList, jListAdd, jTextBlock);- }- return jList;-}--jfloatArray OcrResultUtils::newJScoreArray(std::vector<float> &scores) {- jfloatArray jScores = jniEnv->NewFloatArray(scores.size());- jniEnv->SetFloatArrayRegion(jScores, 0, scores.size(), (jfloat *) scores.data());- return jScores;-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrUtils.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrUtils.cppdeleted file mode 100755index 5ca31c9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/OcrUtils.cpp+++ /dev/null@@ -1,414 +0,0 @@-#include <opencv2/imgproc.hpp>-#include <opencv2/imgcodecs.hpp>-#include "OcrUtils.h"-#include "clipper.hpp"--double getCurrentTime() {- return (static_cast<double>(cv::getTickCount())) / cv::getTickFrequency() * 1000;//单位毫秒-}--ScaleParam getScaleParam(cv::Mat &src, const float scale) {- int srcWidth = src.cols;- int srcHeight = src.rows;- int dstWidth = int((float) srcWidth * scale);- int dstHeight = int((float) srcHeight * scale);- if (dstWidth % 32 != 0) {- dstWidth = (dstWidth / 32 - 1) * 32;- dstWidth = (std::max)(dstWidth, 32);- }- if (dstHeight % 32 != 0) {- dstHeight = (dstHeight / 32 - 1) * 32;- dstHeight = (std::max)(dstHeight, 32);- }- float scaleWidth = (float) dstWidth / (float) srcWidth;- float scaleHeight = (float) dstHeight / (float) srcHeight;- return {srcWidth, srcHeight, dstWidth, dstHeight, scaleWidth, scaleHeight};-}--ScaleParam getScaleParam(cv::Mat &src, const int targetSize) {- int srcWidth, srcHeight, dstWidth, dstHeight;- srcWidth = dstWidth = src.cols;- srcHeight = dstHeight = src.rows;-- float scale = 1.f;- if (dstWidth > dstHeight) {- scale = (float) targetSize / (float) dstWidth;- dstWidth = targetSize;- dstHeight = int((float) dstHeight * scale);- } else {- scale = (float) targetSize / (float) dstHeight;- dstHeight = targetSize;- dstWidth = int((float) dstWidth * scale);- }- if (dstWidth % 32 != 0) {- dstWidth = (dstWidth / 32 - 1) * 32;- dstWidth = (std::max)(dstWidth, 32);- }- if (dstHeight % 32 != 0) {- dstHeight = (dstHeight / 32 - 1) * 32;- dstHeight = (std::max)(dstHeight, 32);- }- float scaleWidth = (float) dstWidth / (float) srcWidth;- float scaleHeight = (float) dstHeight / (float) srcHeight;- return {srcWidth, srcHeight, dstWidth, dstHeight, scaleWidth, scaleHeight};-}--cv::RotatedRect getPartRect(std::vector<cv::Point> &box, float scaleWidth, float scaleHeight) {- cv::RotatedRect rect = cv::minAreaRect(box);- int minSize = rect.size.width > rect.size.height ? rect.size.height : rect.size.width;- if (rect.size.width > rect.size.height) {- rect.size.width = rect.size.width + (float) minSize * scaleWidth;- rect.size.height = rect.size.height + (float) minSize * scaleHeight;- } else {- rect.size.width = rect.size.width + (float) minSize * scaleHeight;- rect.size.height = rect.size.height + (float) minSize * scaleWidth;- }- return rect;-}--int getThickness(cv::Mat &boxImg) {- int minSize = boxImg.cols > boxImg.rows ? boxImg.rows : boxImg.cols;- int thickness = minSize / 1000 + 2;- return thickness;-}--std::vector<cv::Point2f> getBox(const cv::RotatedRect &rect) {- cv::Point2f vertices[4];- rect.points(vertices);- //std::vector<cv::Point2f> ret(4);- std::vector<cv::Point2f> ret2(vertices, vertices + sizeof(vertices) / sizeof(vertices[0]));- //memcpy(vertices, &ret[0], ret.size() * sizeof(ret[0]));- return ret2;-}--void drawTextBox(cv::Mat &boxImg, cv::RotatedRect &rect, int thickness) {- cv::Point2f vertices[4];- rect.points(vertices);- for (int i = 0; i < 4; i++)- cv::line(boxImg, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 0, 255), thickness);- //cv::polylines(srcmat, textpoint, true, cv::Scalar(0, 255, 0), 2);-}--void drawTextBox(cv::Mat &boxImg, const std::vector<cv::Point> &box, int thickness) {- auto color = cv::Scalar(0, 0, 255);// B(0) G(0) R(255)- cv::line(boxImg, box[0], box[1], color, thickness);- cv::line(boxImg, box[1], box[2], color, thickness);- cv::line(boxImg, box[2], box[3], color, thickness);- cv::line(boxImg, box[3], box[0], color, thickness);-}--void drawTextBoxes(cv::Mat &boxImg, std::vector<TextBox> &textBoxes, int thickness) {- for (int i = 0; i < textBoxes.size(); ++i) {- drawTextBox(boxImg, textBoxes[i].boxPoint, thickness);- }-}--cv::Mat matRotateClockWise180(cv::Mat src) {- flip(src, src, 0);- flip(src, src, 1);- return src;-}--cv::Mat matRotateClockWise90(cv::Mat src) {- transpose(src, src);- flip(src, src, 1);- return src;-}--cv::Mat GetRotateCropImage(const cv::Mat &src, std::vector<cv::Point> box) {- cv::Mat image;- src.copyTo(image);- std::vector<cv::Point> points = box;-- int collectX[4] = {box[0].x, box[1].x, box[2].x, box[3].x};- int collectY[4] = {box[0].y, box[1].y, box[2].y, box[3].y};- int left = int(*std::min_element(collectX, collectX + 4));- int right = int(*std::max_element(collectX, collectX + 4));- int top = int(*std::min_element(collectY, collectY + 4));- int bottom = int(*std::max_element(collectY, collectY + 4));-- cv::Mat imgCrop;- image(cv::Rect(left, top, right - left, bottom - top)).copyTo(imgCrop);-- for (int i = 0; i < points.size(); i++) {- points[i].x -= left;- points[i].y -= top;- }-- int imgCropWidth = int(sqrt(pow(points[0].x - points[1].x, 2) +- pow(points[0].y - points[1].y, 2)));- int imgCropHeight = int(sqrt(pow(points[0].x - points[3].x, 2) +- pow(points[0].y - points[3].y, 2)));-- cv::Point2f ptsDst[4];- ptsDst[0] = cv::Point2f(0., 0.);- ptsDst[1] = cv::Point2f(imgCropWidth, 0.);- ptsDst[2] = cv::Point2f(imgCropWidth, imgCropHeight);- ptsDst[3] = cv::Point2f(0.f, imgCropHeight);-- cv::Point2f ptsSrc[4];- ptsSrc[0] = cv::Point2f(points[0].x, points[0].y);- ptsSrc[1] = cv::Point2f(points[1].x, points[1].y);- ptsSrc[2] = cv::Point2f(points[2].x, points[2].y);- ptsSrc[3] = cv::Point2f(points[3].x, points[3].y);-- cv::Mat M = cv::getPerspectiveTransform(ptsSrc, ptsDst);-- cv::Mat partImg;- cv::warpPerspective(imgCrop, partImg, M,- cv::Size(imgCropWidth, imgCropHeight),- cv::BORDER_REPLICATE);-- if (float(partImg.rows) >= float(partImg.cols) * 1.5) {- cv::Mat srcCopy = cv::Mat(partImg.rows, partImg.cols, partImg.depth());- cv::transpose(partImg, srcCopy);- cv::flip(srcCopy, srcCopy, 0);- return srcCopy;- } else {- return partImg;- }-}--cv::Mat adjustTargetImg(cv::Mat &src, int dstWidth, int dstHeight) {- cv::Mat srcResize;- float scale = (float) dstHeight / (float) src.rows;- int angleWidth = int((float) src.cols * scale);- cv::resize(src, srcResize, cv::Size(angleWidth, dstHeight));- cv::Mat srcFit = cv::Mat(dstHeight, dstWidth, CV_8UC3, cv::Scalar(255, 255, 255));- if (angleWidth < dstWidth) {- cv::Rect rect(0, 0, srcResize.cols, srcResize.rows);- srcResize.copyTo(srcFit(rect));- } else {- cv::Rect rect(0, 0, dstWidth, dstHeight);- srcResize(rect).copyTo(srcFit);- }- return srcFit;-}--bool cvPointCompare(cv::Point a, cv::Point b) {- return a.x < b.x;-}--std::vector<cv::Point2f> getMinBoxes(const cv::RotatedRect &boxRect, float &maxSideLen) {- maxSideLen = std::max(boxRect.size.width, boxRect.size.height);- std::vector<cv::Point2f> boxPoint = getBox(boxRect);- std::sort(boxPoint.begin(), boxPoint.end(), cvPointCompare);- int index1, index2, index3, index4;- if (boxPoint[1].y > boxPoint[0].y) {- index1 = 0;- index4 = 1;- } else {- index1 = 1;- index4 = 0;- }- if (boxPoint[3].y > boxPoint[2].y) {- index2 = 2;- index3 = 3;- } else {- index2 = 3;- index3 = 2;- }- std::vector<cv::Point2f> minBox(4);- minBox[0] = boxPoint[index1];- minBox[1] = boxPoint[index2];- minBox[2] = boxPoint[index3];- minBox[3] = boxPoint[index4];- return minBox;-}--float boxScoreFast(const std::vector<cv::Point2f> &boxes, const cv::Mat &pred) {- int width = pred.cols;- int height = pred.rows;-- float arrayX[4] = {boxes[0].x, boxes[1].x, boxes[2].x, boxes[3].x};- float arrayY[4] = {boxes[0].y, boxes[1].y, boxes[2].y, boxes[3].y};-- int minX = clamp(int(std::floor(*(std::min_element(arrayX, arrayX + 4)))), 0, width - 1);- int maxX = clamp(int(std::ceil(*(std::max_element(arrayX, arrayX + 4)))), 0, width - 1);- int minY = clamp(int(std::floor(*(std::min_element(arrayY, arrayY + 4)))), 0, height - 1);- int maxY = clamp(int(std::ceil(*(std::max_element(arrayY, arrayY + 4)))), 0, height - 1);-- cv::Mat mask = cv::Mat::zeros(maxY - minY + 1, maxX - minX + 1, CV_8UC1);-- cv::Point box[4];- box[0] = cv::Point(int(boxes[0].x) - minX, int(boxes[0].y) - minY);- box[1] = cv::Point(int(boxes[1].x) - minX, int(boxes[1].y) - minY);- box[2] = cv::Point(int(boxes[2].x) - minX, int(boxes[2].y) - minY);- box[3] = cv::Point(int(boxes[3].x) - minX, int(boxes[3].y) - minY);- const cv::Point *pts[1] = {box};- int npts[] = {4};- cv::fillPoly(mask, pts, npts, 1, cv::Scalar(1));-- cv::Mat croppedImg;- pred(cv::Rect(minX, minY, maxX - minX + 1, maxY - minY + 1))- .copyTo(croppedImg);-- auto score = cv::mean(croppedImg, mask)[0];- return score;-}--float getContourArea(const std::vector<cv::Point2f> &box, float unClipRatio) {- int size = box.size();- float area = 0.0f;- float dist = 0.0f;- for (int i = 0; i < size; i++) {- area += box[i].x * box[(i + 1) % size].y -- box[i].y * box[(i + 1) % size].x;- dist += sqrtf((box[i].x - box[(i + 1) % size].x) *- (box[i].x - box[(i + 1) % size].x) +- (box[i].y - box[(i + 1) % size].y) *- (box[i].y - box[(i + 1) % size].y));- }- area = fabs(float(area / 2.0));-- return area * unClipRatio / dist;-}--cv::RotatedRect unClip(std::vector<cv::Point2f> box, float unClipRatio) {- float distance = getContourArea(box, unClipRatio);-- ClipperLib::ClipperOffset offset;- ClipperLib::Path p;- p << ClipperLib::IntPoint(int(box[0].x), int(box[0].y))- << ClipperLib::IntPoint(int(box[1].x), int(box[1].y))- << ClipperLib::IntPoint(int(box[2].x), int(box[2].y))- << ClipperLib::IntPoint(int(box[3].x), int(box[3].y));- offset.AddPath(p, ClipperLib::jtRound, ClipperLib::etClosedPolygon);-- ClipperLib::Paths soln;- offset.Execute(soln, distance);- std::vector<cv::Point2f> points;-- for (int j = 0; j < soln.size(); j++) {- for (int i = 0; i < soln[soln.size() - 1].size(); i++) {- points.emplace_back(soln[j][i].X, soln[j][i].Y);- }- }- cv::RotatedRect res;- if (points.empty()) {- res = cv::RotatedRect(cv::Point2f(0, 0), cv::Size2f(1, 1), 0);- } else {- res = cv::minAreaRect(points);- }- return res;-}--std::vector<float> substractMeanNormalize(cv::Mat &src, const float *meanVals, const float *normVals) {- auto inputTensorSize = src.cols * src.rows * src.channels();- std::vector<float> inputTensorValues(inputTensorSize);- size_t numChannels = src.channels();- size_t imageSize = src.cols * src.rows;-- for (size_t pid = 0; pid < imageSize; pid++) {- for (size_t ch = 0; ch < numChannels; ++ch) {- float data = (float) (src.data[pid * numChannels + ch] * normVals[ch] - meanVals[ch] * normVals[ch]);- inputTensorValues[ch * imageSize + pid] = data;- }- }- return inputTensorValues;-}--std::vector<int> getAngleIndexes(std::vector<Angle> &angles) {- std::vector<int> angleIndexes;- angleIndexes.reserve(angles.size());- for (int i = 0; i < angles.size(); ++i) {- angleIndexes.push_back(angles[i].index);- }- return angleIndexes;-}--std::vector<char *> getInputNames(Ort::Session *session) {- Ort::AllocatorWithDefaultOptions allocator;- size_t numInputNodes = session->GetInputCount();- std::vector<char *> inputNodeNames(numInputNodes);- std::vector<int64_t> inputNodeDims;-- //printf("Number of inputs = %zu\n", numInputNodes);-- for (int i = 0; i < numInputNodes; i++) {- // print input node names- char *inputName = session->GetInputName(i, allocator);- printf("InputName[%d]=%s\n", i, inputName);- inputNodeNames[i] = inputName;-- // print input node types- //Ort::TypeInfo typeInfo = session->GetInputTypeInfo(i);- //auto tensorInfo = typeInfo.GetTensorTypeAndShapeInfo();-- //ONNXTensorElementDataType type = tensorInfo.GetElementType();- //printf("Input[%d] type=%d\n", i, type);-- // print input shapes/dims- //inputNodeDims = tensorInfo.GetShape();- //printf("Input[%d] num_dims=%zu\n", i, inputNodeDims.size());- /*for (int j = 0; j < inputNodeDims.size(); j++)- printf("Input[%d] dim%d=%jd\n", i, j, inputNodeDims[j]);*/- }- return inputNodeNames;-}--std::vector<char *> getOutputNames(Ort::Session *session) {- Ort::AllocatorWithDefaultOptions allocator;- size_t numOutputNodes = session->GetOutputCount();- std::vector<char *> outputNodeNames(numOutputNodes);- //std::vector<int64_t> outputNodeDims;-- //printf("Number of outputs = %zu\n", numOutputNodes);-- for (int i = 0; i < numOutputNodes; i++) {- // print input node names- char *outputName = session->GetOutputName(i, allocator);- printf("OutputName[%d]=%s\n", i, outputName);- outputNodeNames[i] = outputName;-- // print input node types- //Ort::TypeInfo type_info = session->GetOutputTypeInfo(i);- //auto tensorInfo = type_info.GetTensorTypeAndShapeInfo();-- //ONNXTensorElementDataType type = tensorInfo.GetElementType();- //printf("Output %d : type=%d\n", i, type);-- // print input shapes/dims- //outputNodeDims = tensorInfo.GetShape();- //printf("Output %d : num_dims=%zu\n", i, outputNodeDims.size());- /*for (int j = 0; j < outputNodeDims.size(); j++)- printf("Output %d : dim %d=%jd\n", i, j, outputNodeDims[j]);*/- }- return outputNodeNames;-}--void *getModelDataFromAssets(AAssetManager *mgr, const char *modelName, int &size) {- if (mgr == NULL) {- LOGE(" %s", "AAssetManager==NULL");- return NULL;- }- AAsset *asset = AAssetManager_open(mgr, modelName, AASSET_MODE_UNKNOWN);- if (asset == NULL) {- LOGE(" %s", "asset==NULL");- return NULL;- }- off_t bufferSize = AAsset_getLength(asset);- void *modelData = malloc(bufferSize + 1);- size = AAsset_read(asset, modelData, bufferSize);- AAsset_close(asset);- LOGI("model=%s, numBytesRead=%d", modelName, size);- return modelData;-}--std::string jstringTostring(JNIEnv *env, jstring input) {- char *str = NULL;- jclass clsstring = env->FindClass("java/lang/String");- jstring strencode = env->NewStringUTF("utf-8");- jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");- jbyteArray barr = (jbyteArray) env->CallObjectMethod(input, mid, strencode);- jsize alen = env->GetArrayLength(barr);- jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);- if (alen > 0) {- str = (char *) malloc(alen + 1);- memcpy(str, ba, alen);- str[alen] = 0;- }- env->ReleaseByteArrayElements(barr, ba, 0);- std::string ret = str;- return ret;-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/clipper.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/clipper.cppdeleted file mode 100755index 20ab5a0..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/clipper.cpp+++ /dev/null@@ -1,4629 +0,0 @@-/*******************************************************************************-* *-* Author : Angus Johnson *-* Version : 6.4.2 *-* Date : 27 February 2017 *-* Website : http://www.angusj.com *-* Copyright : Angus Johnson 2010-2017 *-* *-* License: *-* Use, modification & distribution is subject to Boost Software License Ver 1. *-* http://www.boost.org/LICENSE_1_0.txt *-* *-* Attributions: *-* The code in this library is an extension of Bala Vatti's clipping algorithm: *-* "A generic solution to polygon clipping" *-* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *-* http://portal.acm.org/citation.cfm?id=129906 *-* *-* Computer graphics and geometric modeling: implementation and algorithms *-* By Max K. Agoston *-* Springer; 1 edition (January 4, 2005) *-* http://books.google.com/books?q=vatti+clipping+agoston *-* *-* See also: *-* "Polygon Offsetting by Computing Winding Numbers" *-* Paper no. DETC2005-85513 pp. 565-575 *-* ASME 2005 International Design Engineering Technical Conferences *-* and Computers and Information in Engineering Conference (IDETC/CIE2005) *-* September 24-28, 2005 , Long Beach, California, USA *-* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *-* *-*******************************************************************************/--/*******************************************************************************-* *-* This is a translation of the Delphi Clipper library and the naming style *-* used has retained a Delphi flavour. *-* *-*******************************************************************************/--#include "clipper.hpp"-#include <cmath>-#include <vector>-#include <algorithm>-#include <stdexcept>-#include <cstring>-#include <cstdlib>-#include <ostream>-#include <functional>--namespace ClipperLib {-- static double const pi = 3.141592653589793238;- static double const two_pi = pi *2;- static double const def_arc_tolerance = 0.25;-- enum Direction { dRightToLeft, dLeftToRight };-- static int const Unassigned = -1; //edge not currently 'owning' a solution- static int const Skip = -2; //edge that would otherwise close a path--#define HORIZONTAL (-1.0E+40)-#define TOLERANCE (1.0e-20)-#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))-- struct TEdge {- IntPoint Bot;- IntPoint Curr; //current (updated for every new scanbeam)- IntPoint Top;- double Dx;- PolyType PolyTyp;- EdgeSide Side; //side only refers to current side of solution poly- int WindDelta; //1 or -1 depending on winding direction- int WindCnt;- int WindCnt2; //winding count of the opposite polytype- int OutIdx;- TEdge *Next;- TEdge *Prev;- TEdge *NextInLML;- TEdge *NextInAEL;- TEdge *PrevInAEL;- TEdge *NextInSEL;- TEdge *PrevInSEL;- };-- struct IntersectNode {- TEdge *Edge1;- TEdge *Edge2;- IntPoint Pt;- };-- struct LocalMinimum {- cInt Y;- TEdge *LeftBound;- TEdge *RightBound;- };-- struct OutPt;--//OutRec: contains a path in the clipping solution. Edges in the AEL will-//carry a pointer to an OutRec when they are part of the clipping solution.- struct OutRec {- int Idx;- bool IsHole;- bool IsOpen;- OutRec *FirstLeft; //see comments in clipper.pas- PolyNode *PolyNd;- OutPt *Pts;- OutPt *BottomPt;- };-- struct OutPt {- int Idx;- IntPoint Pt;- OutPt *Next;- OutPt *Prev;- };-- struct Join {- OutPt *OutPt1;- OutPt *OutPt2;- IntPoint OffPt;- };-- struct LocMinSorter- {- inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)- {- return locMin2.Y < locMin1.Y;- }- };--//-------------------------------------------------------------------------------//-------------------------------------------------------------------------------- inline cInt Round(double val)- {- if ((val < 0)) return static_cast<cInt>(val - 0.5);- else return static_cast<cInt>(val + 0.5);- }-//-------------------------------------------------------------------------------- inline cInt Abs(cInt val)- {- return val < 0 ? -val : val;- }--//-------------------------------------------------------------------------------// PolyTree methods ...-//-------------------------------------------------------------------------------- void PolyTree::Clear()- {- for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)- delete AllNodes[i];- AllNodes.resize(0);- Childs.resize(0);- }-//-------------------------------------------------------------------------------- PolyNode* PolyTree::GetFirst() const- {- if (!Childs.empty())- return Childs[0];- else- return 0;- }-//-------------------------------------------------------------------------------- int PolyTree::Total() const- {- int result = (int)AllNodes.size();- //with negative offsets, ignore the hidden outer polygon ...- if (result > 0 && Childs[0] != AllNodes[0]) result--;- return result;- }--//-------------------------------------------------------------------------------// PolyNode methods ...-//-------------------------------------------------------------------------------- PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)- {- }-//-------------------------------------------------------------------------------- int PolyNode::ChildCount() const- {- return (int)Childs.size();- }-//-------------------------------------------------------------------------------- void PolyNode::AddChild(PolyNode& child)- {- unsigned cnt = (unsigned)Childs.size();- Childs.push_back(&child);- child.Parent = this;- child.Index = cnt;- }-//-------------------------------------------------------------------------------- PolyNode* PolyNode::GetNext() const- {- if (!Childs.empty())- return Childs[0];- else- return GetNextSiblingUp();- }-//-------------------------------------------------------------------------------- PolyNode* PolyNode::GetNextSiblingUp() const- {- if (!Parent) //protects against PolyTree.GetNextSiblingUp()- return 0;- else if (Index == Parent->Childs.size() - 1)- return Parent->GetNextSiblingUp();- else- return Parent->Childs[Index + 1];- }-//-------------------------------------------------------------------------------- bool PolyNode::IsHole() const- {- bool result = true;- PolyNode* node = Parent;- while (node)- {- result = !result;- node = node->Parent;- }- return result;- }-//-------------------------------------------------------------------------------- bool PolyNode::IsOpen() const- {- return m_IsOpen;- }-//--------------------------------------------------------------------------------#ifndef use_int32--//-------------------------------------------------------------------------------// Int128 class (enables safe math on signed 64bit integers)-// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1-// Int128 val2((long64)9223372036854775807);-// Int128 val3 = val1 * val2;-// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)-//-------------------------------------------------------------------------------- class Int128- {- public:- ulong64 lo;- long64 hi;-- Int128(long64 _lo = 0)- {- lo = (ulong64)_lo;- if (_lo < 0) hi = -1; else hi = 0;- }--- Int128(const Int128 &val): lo(val.lo), hi(val.hi){}-- Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}-- Int128& operator = (const long64 &val)- {- lo = (ulong64)val;- if (val < 0) hi = -1; else hi = 0;- return *this;- }-- bool operator == (const Int128 &val) const- {return (hi == val.hi && lo == val.lo);}-- bool operator != (const Int128 &val) const- { return !(*this == val);}-- bool operator > (const Int128 &val) const- {- if (hi != val.hi)- return hi > val.hi;- else- return lo > val.lo;- }-- bool operator < (const Int128 &val) const- {- if (hi != val.hi)- return hi < val.hi;- else- return lo < val.lo;- }-- bool operator >= (const Int128 &val) const- { return !(*this < val);}-- bool operator <= (const Int128 &val) const- { return !(*this > val);}-- Int128& operator += (const Int128 &rhs)- {- hi += rhs.hi;- lo += rhs.lo;- if (lo < rhs.lo) hi++;- return *this;- }-- Int128 operator + (const Int128 &rhs) const- {- Int128 result(*this);- result+= rhs;- return result;- }-- Int128& operator -= (const Int128 &rhs)- {- *this += -rhs;- return *this;- }-- Int128 operator - (const Int128 &rhs) const- {- Int128 result(*this);- result -= rhs;- return result;- }-- Int128 operator-() const //unary negation- {- if (lo == 0)- return Int128(-hi, 0);- else- return Int128(~hi, ~lo + 1);- }-- operator double() const- {- const double shift64 = 18446744073709551616.0; //2^64- if (hi < 0)- {- if (lo == 0) return (double)hi * shift64;- else return -(double)(~lo + ~hi * shift64);- }- else- return (double)(lo + hi * shift64);- }-- };-//-------------------------------------------------------------------------------- Int128 Int128Mul (long64 lhs, long64 rhs)- {- bool negate = (lhs < 0) != (rhs < 0);-- if (lhs < 0) lhs = -lhs;- ulong64 int1Hi = ulong64(lhs) >> 32;- ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);-- if (rhs < 0) rhs = -rhs;- ulong64 int2Hi = ulong64(rhs) >> 32;- ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);-- //nb: see comments in clipper.pas- ulong64 a = int1Hi * int2Hi;- ulong64 b = int1Lo * int2Lo;- ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;-- Int128 tmp;- tmp.hi = long64(a + (c >> 32));- tmp.lo = long64(c << 32);- tmp.lo += long64(b);- if (tmp.lo < b) tmp.hi++;- if (negate) tmp = -tmp;- return tmp;- };-#endif--//-------------------------------------------------------------------------------// Miscellaneous global functions-//-------------------------------------------------------------------------------- bool Orientation(const Path &poly)- {- return Area(poly) >= 0;- }-//-------------------------------------------------------------------------------- double Area(const Path &poly)- {- int size = (int)poly.size();- if (size < 3) return 0;-- double a = 0;- for (int i = 0, j = size -1; i < size; ++i)- {- a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);- j = i;- }- return -a * 0.5;- }-//-------------------------------------------------------------------------------- double Area(const OutPt *op)- {- const OutPt *startOp = op;- if (!op) return 0;- double a = 0;- do {- a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);- op = op->Next;- } while (op != startOp);- return a * 0.5;- }-//-------------------------------------------------------------------------------- double Area(const OutRec &outRec)- {- return Area(outRec.Pts);- }-//-------------------------------------------------------------------------------- bool PointIsVertex(const IntPoint &Pt, OutPt *pp)- {- OutPt *pp2 = pp;- do- {- if (pp2->Pt == Pt) return true;- pp2 = pp2->Next;- }- while (pp2 != pp);- return false;- }-//--------------------------------------------------------------------------------//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos-//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf- int PointInPolygon(const IntPoint &pt, const Path &path)- {- //returns 0 if false, +1 if true, -1 if pt ON polygon boundary- int result = 0;- size_t cnt = path.size();- if (cnt < 3) return 0;- IntPoint ip = path[0];- for(size_t i = 1; i <= cnt; ++i)- {- IntPoint ipNext = (i == cnt ? path[0] : path[i]);- if (ipNext.Y == pt.Y)- {- if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&- ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;- }- if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))- {- if (ip.X >= pt.X)- {- if (ipNext.X > pt.X) result = 1 - result;- else- {- double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -- (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);- if (!d) return -1;- if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;- }- } else- {- if (ipNext.X > pt.X)- {- double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -- (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);- if (!d) return -1;- if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;- }- }- }- ip = ipNext;- }- return result;- }-//-------------------------------------------------------------------------------- int PointInPolygon (const IntPoint &pt, OutPt *op)- {- //returns 0 if false, +1 if true, -1 if pt ON polygon boundary- int result = 0;- OutPt* startOp = op;- for(;;)- {- if (op->Next->Pt.Y == pt.Y)- {- if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&- ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;- }- if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))- {- if (op->Pt.X >= pt.X)- {- if (op->Next->Pt.X > pt.X) result = 1 - result;- else- {- double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -- (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);- if (!d) return -1;- if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;- }- } else- {- if (op->Next->Pt.X > pt.X)- {- double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -- (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);- if (!d) return -1;- if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;- }- }- }- op = op->Next;- if (startOp == op) break;- }- return result;- }-//-------------------------------------------------------------------------------- bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)- {- OutPt* op = OutPt1;- do- {- //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon- int res = PointInPolygon(op->Pt, OutPt2);- if (res >= 0) return res > 0;- op = op->Next;- }- while (op != OutPt1);- return true;- }-//------------------------------------------------------------------------ bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)- {-#ifndef use_int32- if (UseFullInt64Range)- return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==- Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);- else-#endif- return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==- (e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);- }-//-------------------------------------------------------------------------------- bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,- const IntPoint pt3, bool UseFullInt64Range)- {-#ifndef use_int32- if (UseFullInt64Range)- return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);- else-#endif- return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);- }-//-------------------------------------------------------------------------------- bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,- const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)- {-#ifndef use_int32- if (UseFullInt64Range)- return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);- else-#endif- return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);- }-//-------------------------------------------------------------------------------- inline bool IsHorizontal(TEdge &e)- {- return e.Dx == HORIZONTAL;- }-//-------------------------------------------------------------------------------- inline double GetDx(const IntPoint pt1, const IntPoint pt2)- {- return (pt1.Y == pt2.Y) ?- HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);- }-//----------------------------------------------------------------------------- inline void SetDx(TEdge &e)- {- cInt dy = (e.Top.Y - e.Bot.Y);- if (dy == 0) e.Dx = HORIZONTAL;- else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;- }-//----------------------------------------------------------------------------- inline void SwapSides(TEdge &Edge1, TEdge &Edge2)- {- EdgeSide Side = Edge1.Side;- Edge1.Side = Edge2.Side;- Edge2.Side = Side;- }-//-------------------------------------------------------------------------------- inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)- {- int OutIdx = Edge1.OutIdx;- Edge1.OutIdx = Edge2.OutIdx;- Edge2.OutIdx = OutIdx;- }-//-------------------------------------------------------------------------------- inline cInt TopX(TEdge &edge, const cInt currentY)- {- return ( currentY == edge.Top.Y ) ?- edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));- }-//-------------------------------------------------------------------------------- void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)- {-#ifdef use_xyz- ip.Z = 0;-#endif-- double b1, b2;- if (Edge1.Dx == Edge2.Dx)- {- ip.Y = Edge1.Curr.Y;- ip.X = TopX(Edge1, ip.Y);- return;- }- else if (Edge1.Dx == 0)- {- ip.X = Edge1.Bot.X;- if (IsHorizontal(Edge2))- ip.Y = Edge2.Bot.Y;- else- {- b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);- ip.Y = Round(ip.X / Edge2.Dx + b2);- }- }- else if (Edge2.Dx == 0)- {- ip.X = Edge2.Bot.X;- if (IsHorizontal(Edge1))- ip.Y = Edge1.Bot.Y;- else- {- b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);- ip.Y = Round(ip.X / Edge1.Dx + b1);- }- }- else- {- b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;- b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;- double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);- ip.Y = Round(q);- if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))- ip.X = Round(Edge1.Dx * q + b1);- else- ip.X = Round(Edge2.Dx * q + b2);- }-- if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)- {- if (Edge1.Top.Y > Edge2.Top.Y)- ip.Y = Edge1.Top.Y;- else- ip.Y = Edge2.Top.Y;- if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))- ip.X = TopX(Edge1, ip.Y);- else- ip.X = TopX(Edge2, ip.Y);- }- //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...- if (ip.Y > Edge1.Curr.Y)- {- ip.Y = Edge1.Curr.Y;- //use the more vertical edge to derive X ...- if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))- ip.X = TopX(Edge2, ip.Y); else- ip.X = TopX(Edge1, ip.Y);- }- }-//-------------------------------------------------------------------------------- void ReversePolyPtLinks(OutPt *pp)- {- if (!pp) return;- OutPt *pp1, *pp2;- pp1 = pp;- do {- pp2 = pp1->Next;- pp1->Next = pp1->Prev;- pp1->Prev = pp2;- pp1 = pp2;- } while( pp1 != pp );- }-//-------------------------------------------------------------------------------- void DisposeOutPts(OutPt*& pp)- {- if (pp == 0) return;- pp->Prev->Next = 0;- while( pp )- {- OutPt *tmpPp = pp;- pp = pp->Next;- delete tmpPp;- }- }-//-------------------------------------------------------------------------------- inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)- {- std::memset(e, 0, sizeof(TEdge));- e->Next = eNext;- e->Prev = ePrev;- e->Curr = Pt;- e->OutIdx = Unassigned;- }-//-------------------------------------------------------------------------------- void InitEdge2(TEdge& e, PolyType Pt)- {- if (e.Curr.Y >= e.Next->Curr.Y)- {- e.Bot = e.Curr;- e.Top = e.Next->Curr;- } else- {- e.Top = e.Curr;- e.Bot = e.Next->Curr;- }- SetDx(e);- e.PolyTyp = Pt;- }-//-------------------------------------------------------------------------------- TEdge* RemoveEdge(TEdge* e)- {- //removes e from double_linked_list (but without removing from memory)- e->Prev->Next = e->Next;- e->Next->Prev = e->Prev;- TEdge* result = e->Next;- e->Prev = 0; //flag as removed (see ClipperBase.Clear)- return result;- }-//-------------------------------------------------------------------------------- inline void ReverseHorizontal(TEdge &e)- {- //swap horizontal edges' Top and Bottom x's so they follow the natural- //progression of the bounds - ie so their xbots will align with the- //adjoining lower edge. [Helpful in the ProcessHorizontal() method.]- std::swap(e.Top.X, e.Bot.X);-#ifdef use_xyz- std::swap(e.Top.Z, e.Bot.Z);-#endif- }-//-------------------------------------------------------------------------------- void SwapPoints(IntPoint &pt1, IntPoint &pt2)- {- IntPoint tmp = pt1;- pt1 = pt2;- pt2 = tmp;- }-//-------------------------------------------------------------------------------- bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,- IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)- {- //precondition: segments are Collinear.- if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))- {- if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);- if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);- if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;- if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;- return pt1.X < pt2.X;- } else- {- if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);- if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);- if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;- if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;- return pt1.Y > pt2.Y;- }- }-//-------------------------------------------------------------------------------- bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)- {- OutPt *p = btmPt1->Prev;- while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;- double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));- p = btmPt1->Next;- while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;- double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));-- p = btmPt2->Prev;- while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;- double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));- p = btmPt2->Next;- while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;- double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));-- if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&- std::min(dx1p, dx1n) == std::min(dx2p, dx2n))- return Area(btmPt1) > 0; //if otherwise identical use orientation- else- return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);- }-//-------------------------------------------------------------------------------- OutPt* GetBottomPt(OutPt *pp)- {- OutPt* dups = 0;- OutPt* p = pp->Next;- while (p != pp)- {- if (p->Pt.Y > pp->Pt.Y)- {- pp = p;- dups = 0;- }- else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)- {- if (p->Pt.X < pp->Pt.X)- {- dups = 0;- pp = p;- } else- {- if (p->Next != pp && p->Prev != pp) dups = p;- }- }- p = p->Next;- }- if (dups)- {- //there appears to be at least 2 vertices at BottomPt so ...- while (dups != p)- {- if (!FirstIsBottomPt(p, dups)) pp = dups;- dups = dups->Next;- while (dups->Pt != pp->Pt) dups = dups->Next;- }- }- return pp;- }-//-------------------------------------------------------------------------------- bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,- const IntPoint pt2, const IntPoint pt3)- {- if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))- return false;- else if (pt1.X != pt3.X)- return (pt2.X > pt1.X) == (pt2.X < pt3.X);- else- return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);- }-//-------------------------------------------------------------------------------- bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)- {- if (seg1a > seg1b) std::swap(seg1a, seg1b);- if (seg2a > seg2b) std::swap(seg2a, seg2b);- return (seg1a < seg2b) && (seg2a < seg1b);- }--//-------------------------------------------------------------------------------// ClipperBase class methods ...-//-------------------------------------------------------------------------------- ClipperBase::ClipperBase() //constructor- {- m_CurrentLM = m_MinimaList.begin(); //begin() == end() here- m_UseFullRange = false;- }-//-------------------------------------------------------------------------------- ClipperBase::~ClipperBase() //destructor- {- Clear();- }-//-------------------------------------------------------------------------------- void RangeTest(const IntPoint& Pt, bool& useFullRange)- {- if (useFullRange)- {- if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)- throw clipperException("Coordinate outside allowed range");- }- else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)- {- useFullRange = true;- RangeTest(Pt, useFullRange);- }- }-//-------------------------------------------------------------------------------- TEdge* FindNextLocMin(TEdge* E)- {- for (;;)- {- while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;- if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;- while (IsHorizontal(*E->Prev)) E = E->Prev;- TEdge* E2 = E;- while (IsHorizontal(*E)) E = E->Next;- if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.- if (E2->Prev->Bot.X < E->Bot.X) E = E2;- break;- }- return E;- }-//-------------------------------------------------------------------------------- TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)- {- TEdge *Result = E;- TEdge *Horz = 0;-- if (E->OutIdx == Skip)- {- //if edges still remain in the current bound beyond the skip edge then- //create another LocMin and call ProcessBound once more- if (NextIsForward)- {- while (E->Top.Y == E->Next->Bot.Y) E = E->Next;- //don't include top horizontals when parsing a bound a second time,- //they will be contained in the opposite bound ...- while (E != Result && IsHorizontal(*E)) E = E->Prev;- }- else- {- while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;- while (E != Result && IsHorizontal(*E)) E = E->Next;- }-- if (E == Result)- {- if (NextIsForward) Result = E->Next;- else Result = E->Prev;- }- else- {- //there are more edges in the bound beyond result starting with E- if (NextIsForward)- E = Result->Next;- else- E = Result->Prev;- MinimaList::value_type locMin;- locMin.Y = E->Bot.Y;- locMin.LeftBound = 0;- locMin.RightBound = E;- E->WindDelta = 0;- Result = ProcessBound(E, NextIsForward);- m_MinimaList.push_back(locMin);- }- return Result;- }-- TEdge *EStart;-- if (IsHorizontal(*E))- {- //We need to be careful with open paths because this may not be a- //true local minima (ie E may be following a skip edge).- //Also, consecutive horz. edges may start heading left before going right.- if (NextIsForward)- EStart = E->Prev;- else- EStart = E->Next;- if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge- {- if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)- ReverseHorizontal(*E);- }- else if (EStart->Bot.X != E->Bot.X)- ReverseHorizontal(*E);- }-- EStart = E;- if (NextIsForward)- {- while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)- Result = Result->Next;- if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)- {- //nb: at the top of a bound, horizontals are added to the bound- //only when the preceding edge attaches to the horizontal's left vertex- //unless a Skip edge is encountered when that becomes the top divide- Horz = Result;- while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;- if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;- }- while (E != Result)- {- E->NextInLML = E->Next;- if (IsHorizontal(*E) && E != EStart &&- E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);- E = E->Next;- }- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)- ReverseHorizontal(*E);- Result = Result->Next; //move to the edge just beyond current bound- } else- {- while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)- Result = Result->Prev;- if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)- {- Horz = Result;- while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;- if (Horz->Next->Top.X == Result->Prev->Top.X ||- Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;- }-- while (E != Result)- {- E->NextInLML = E->Prev;- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)- ReverseHorizontal(*E);- E = E->Prev;- }- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)- ReverseHorizontal(*E);- Result = Result->Prev; //move to the edge just beyond current bound- }-- return Result;- }-//-------------------------------------------------------------------------------- bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)- {-#ifdef use_lines- if (!Closed && PolyTyp == ptClip)- throw clipperException("AddPath: Open paths must be subject.");-#else- if (!Closed)- throw clipperException("AddPath: Open paths have been disabled.");-#endif-- int highI = (int)pg.size() -1;- if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;- while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;- if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;-- //create a new edge array ...- TEdge *edges = new TEdge [highI +1];-- bool IsFlat = true;- //1. Basic (first) edge initialization ...- try- {- edges[1].Curr = pg[1];- RangeTest(pg[0], m_UseFullRange);- RangeTest(pg[highI], m_UseFullRange);- InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);- InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);- for (int i = highI - 1; i >= 1; --i)- {- RangeTest(pg[i], m_UseFullRange);- InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);- }- }- catch(...)- {- delete [] edges;- throw; //range test fails- }- TEdge *eStart = &edges[0];-- //2. Remove duplicate vertices, and (when closed) collinear edges ...- TEdge *E = eStart, *eLoopStop = eStart;- for (;;)- {- //nb: allows matching start and end points when not Closed ...- if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))- {- if (E == E->Next) break;- if (E == eStart) eStart = E->Next;- E = RemoveEdge(E);- eLoopStop = E;- continue;- }- if (E->Prev == E->Next)- break; //only two vertices- else if (Closed &&- SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&- (!m_PreserveCollinear ||- !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))- {- //Collinear edges are allowed for open paths but in closed paths- //the default is to merge adjacent collinear edges into a single edge.- //However, if the PreserveCollinear property is enabled, only overlapping- //collinear edges (ie spikes) will be removed from closed paths.- if (E == eStart) eStart = E->Next;- E = RemoveEdge(E);- E = E->Prev;- eLoopStop = E;- continue;- }- E = E->Next;- if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;- }-- if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))- {- delete [] edges;- return false;- }-- if (!Closed)- {- m_HasOpenPaths = true;- eStart->Prev->OutIdx = Skip;- }-- //3. Do second stage of edge initialization ...- E = eStart;- do- {- InitEdge2(*E, PolyTyp);- E = E->Next;- if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;- }- while (E != eStart);-- //4. Finally, add edge bounds to LocalMinima list ...-- //Totally flat paths must be handled differently when adding them- //to LocalMinima list to avoid endless loops etc ...- if (IsFlat)- {- if (Closed)- {- delete [] edges;- return false;- }- E->Prev->OutIdx = Skip;- MinimaList::value_type locMin;- locMin.Y = E->Bot.Y;- locMin.LeftBound = 0;- locMin.RightBound = E;- locMin.RightBound->Side = esRight;- locMin.RightBound->WindDelta = 0;- for (;;)- {- if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);- if (E->Next->OutIdx == Skip) break;- E->NextInLML = E->Next;- E = E->Next;- }- m_MinimaList.push_back(locMin);- m_edges.push_back(edges);- return true;- }-- m_edges.push_back(edges);- bool leftBoundIsForward;- TEdge* EMin = 0;-- //workaround to avoid an endless loop in the while loop below when- //open paths have matching start and end points ...- if (E->Prev->Bot == E->Prev->Top) E = E->Next;-- for (;;)- {- E = FindNextLocMin(E);- if (E == EMin) break;- else if (!EMin) EMin = E;-- //E and E.Prev now share a local minima (left aligned if horizontal).- //Compare their slopes to find which starts which bound ...- MinimaList::value_type locMin;- locMin.Y = E->Bot.Y;- if (E->Dx < E->Prev->Dx)- {- locMin.LeftBound = E->Prev;- locMin.RightBound = E;- leftBoundIsForward = false; //Q.nextInLML = Q.prev- } else- {- locMin.LeftBound = E;- locMin.RightBound = E->Prev;- leftBoundIsForward = true; //Q.nextInLML = Q.next- }-- if (!Closed) locMin.LeftBound->WindDelta = 0;- else if (locMin.LeftBound->Next == locMin.RightBound)- locMin.LeftBound->WindDelta = -1;- else locMin.LeftBound->WindDelta = 1;- locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;-- E = ProcessBound(locMin.LeftBound, leftBoundIsForward);- if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);-- TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);- if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);-- if (locMin.LeftBound->OutIdx == Skip)- locMin.LeftBound = 0;- else if (locMin.RightBound->OutIdx == Skip)- locMin.RightBound = 0;- m_MinimaList.push_back(locMin);- if (!leftBoundIsForward) E = E2;- }- return true;- }-//-------------------------------------------------------------------------------- bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)- {- bool result = false;- for (Paths::size_type i = 0; i < ppg.size(); ++i)- if (AddPath(ppg[i], PolyTyp, Closed)) result = true;- return result;- }-//-------------------------------------------------------------------------------- void ClipperBase::Clear()- {- DisposeLocalMinimaList();- for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)- {- TEdge* edges = m_edges[i];- delete [] edges;- }- m_edges.clear();- m_UseFullRange = false;- m_HasOpenPaths = false;- }-//-------------------------------------------------------------------------------- void ClipperBase::Reset()- {- m_CurrentLM = m_MinimaList.begin();- if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process- std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());-- m_Scanbeam = ScanbeamList(); //clears/resets priority_queue- //reset all edges ...- for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)- {- InsertScanbeam(lm->Y);- TEdge* e = lm->LeftBound;- if (e)- {- e->Curr = e->Bot;- e->Side = esLeft;- e->OutIdx = Unassigned;- }-- e = lm->RightBound;- if (e)- {- e->Curr = e->Bot;- e->Side = esRight;- e->OutIdx = Unassigned;- }- }- m_ActiveEdges = 0;- m_CurrentLM = m_MinimaList.begin();- }-//-------------------------------------------------------------------------------- void ClipperBase::DisposeLocalMinimaList()- {- m_MinimaList.clear();- m_CurrentLM = m_MinimaList.begin();- }-//-------------------------------------------------------------------------------- bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)- {- if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;- locMin = &(*m_CurrentLM);- ++m_CurrentLM;- return true;- }-//-------------------------------------------------------------------------------- IntRect ClipperBase::GetBounds()- {- IntRect result;- MinimaList::iterator lm = m_MinimaList.begin();- if (lm == m_MinimaList.end())- {- result.left = result.top = result.right = result.bottom = 0;- return result;- }- result.left = lm->LeftBound->Bot.X;- result.top = lm->LeftBound->Bot.Y;- result.right = lm->LeftBound->Bot.X;- result.bottom = lm->LeftBound->Bot.Y;- while (lm != m_MinimaList.end())- {- //todo - needs fixing for open paths- result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);- TEdge* e = lm->LeftBound;- for (;;) {- TEdge* bottomE = e;- while (e->NextInLML)- {- if (e->Bot.X < result.left) result.left = e->Bot.X;- if (e->Bot.X > result.right) result.right = e->Bot.X;- e = e->NextInLML;- }- result.left = std::min(result.left, e->Bot.X);- result.right = std::max(result.right, e->Bot.X);- result.left = std::min(result.left, e->Top.X);- result.right = std::max(result.right, e->Top.X);- result.top = std::min(result.top, e->Top.Y);- if (bottomE == lm->LeftBound) e = lm->RightBound;- else break;- }- ++lm;- }- return result;- }-//-------------------------------------------------------------------------------- void ClipperBase::InsertScanbeam(const cInt Y)- {- m_Scanbeam.push(Y);- }-//-------------------------------------------------------------------------------- bool ClipperBase::PopScanbeam(cInt &Y)- {- if (m_Scanbeam.empty()) return false;- Y = m_Scanbeam.top();- m_Scanbeam.pop();- while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.- return true;- }-//-------------------------------------------------------------------------------- void ClipperBase::DisposeAllOutRecs(){- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- DisposeOutRec(i);- m_PolyOuts.clear();- }-//-------------------------------------------------------------------------------- void ClipperBase::DisposeOutRec(PolyOutList::size_type index)- {- OutRec *outRec = m_PolyOuts[index];- if (outRec->Pts) DisposeOutPts(outRec->Pts);- delete outRec;- m_PolyOuts[index] = 0;- }-//-------------------------------------------------------------------------------- void ClipperBase::DeleteFromAEL(TEdge *e)- {- TEdge* AelPrev = e->PrevInAEL;- TEdge* AelNext = e->NextInAEL;- if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted- if (AelPrev) AelPrev->NextInAEL = AelNext;- else m_ActiveEdges = AelNext;- if (AelNext) AelNext->PrevInAEL = AelPrev;- e->NextInAEL = 0;- e->PrevInAEL = 0;- }-//-------------------------------------------------------------------------------- OutRec* ClipperBase::CreateOutRec()- {- OutRec* result = new OutRec;- result->IsHole = false;- result->IsOpen = false;- result->FirstLeft = 0;- result->Pts = 0;- result->BottomPt = 0;- result->PolyNd = 0;- m_PolyOuts.push_back(result);- result->Idx = (int)m_PolyOuts.size() - 1;- return result;- }-//-------------------------------------------------------------------------------- void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)- {- //check that one or other edge hasn't already been removed from AEL ...- if (Edge1->NextInAEL == Edge1->PrevInAEL ||- Edge2->NextInAEL == Edge2->PrevInAEL) return;-- if (Edge1->NextInAEL == Edge2)- {- TEdge* Next = Edge2->NextInAEL;- if (Next) Next->PrevInAEL = Edge1;- TEdge* Prev = Edge1->PrevInAEL;- if (Prev) Prev->NextInAEL = Edge2;- Edge2->PrevInAEL = Prev;- Edge2->NextInAEL = Edge1;- Edge1->PrevInAEL = Edge2;- Edge1->NextInAEL = Next;- }- else if (Edge2->NextInAEL == Edge1)- {- TEdge* Next = Edge1->NextInAEL;- if (Next) Next->PrevInAEL = Edge2;- TEdge* Prev = Edge2->PrevInAEL;- if (Prev) Prev->NextInAEL = Edge1;- Edge1->PrevInAEL = Prev;- Edge1->NextInAEL = Edge2;- Edge2->PrevInAEL = Edge1;- Edge2->NextInAEL = Next;- }- else- {- TEdge* Next = Edge1->NextInAEL;- TEdge* Prev = Edge1->PrevInAEL;- Edge1->NextInAEL = Edge2->NextInAEL;- if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;- Edge1->PrevInAEL = Edge2->PrevInAEL;- if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;- Edge2->NextInAEL = Next;- if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;- Edge2->PrevInAEL = Prev;- if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;- }-- if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;- else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;- }-//-------------------------------------------------------------------------------- void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)- {- if (!e->NextInLML)- throw clipperException("UpdateEdgeIntoAEL: invalid call");-- e->NextInLML->OutIdx = e->OutIdx;- TEdge* AelPrev = e->PrevInAEL;- TEdge* AelNext = e->NextInAEL;- if (AelPrev) AelPrev->NextInAEL = e->NextInLML;- else m_ActiveEdges = e->NextInLML;- if (AelNext) AelNext->PrevInAEL = e->NextInLML;- e->NextInLML->Side = e->Side;- e->NextInLML->WindDelta = e->WindDelta;- e->NextInLML->WindCnt = e->WindCnt;- e->NextInLML->WindCnt2 = e->WindCnt2;- e = e->NextInLML;- e->Curr = e->Bot;- e->PrevInAEL = AelPrev;- e->NextInAEL = AelNext;- if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);- }-//-------------------------------------------------------------------------------- bool ClipperBase::LocalMinimaPending()- {- return (m_CurrentLM != m_MinimaList.end());- }--//-------------------------------------------------------------------------------// TClipper methods ...-//-------------------------------------------------------------------------------- Clipper::Clipper(int initOptions) : ClipperBase() //constructor- {- m_ExecuteLocked = false;- m_UseFullRange = false;- m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);- m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);- m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);- m_HasOpenPaths = false;-#ifdef use_xyz- m_ZFill = 0;-#endif- }-//--------------------------------------------------------------------------------#ifdef use_xyz- void Clipper::ZFillFunction(ZFillCallback zFillFunc)-{- m_ZFill = zFillFunc;-}-//-------------------------------------------------------------------------------#endif-- bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)- {- return Execute(clipType, solution, fillType, fillType);- }-//-------------------------------------------------------------------------------- bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)- {- return Execute(clipType, polytree, fillType, fillType);- }-//-------------------------------------------------------------------------------- bool Clipper::Execute(ClipType clipType, Paths &solution,- PolyFillType subjFillType, PolyFillType clipFillType)- {- if( m_ExecuteLocked ) return false;- if (m_HasOpenPaths)- throw clipperException("Error: PolyTree struct is needed for open path clipping.");- m_ExecuteLocked = true;- solution.resize(0);- m_SubjFillType = subjFillType;- m_ClipFillType = clipFillType;- m_ClipType = clipType;- m_UsingPolyTree = false;- bool succeeded = ExecuteInternal();- if (succeeded) BuildResult(solution);- DisposeAllOutRecs();- m_ExecuteLocked = false;- return succeeded;- }-//-------------------------------------------------------------------------------- bool Clipper::Execute(ClipType clipType, PolyTree& polytree,- PolyFillType subjFillType, PolyFillType clipFillType)- {- if( m_ExecuteLocked ) return false;- m_ExecuteLocked = true;- m_SubjFillType = subjFillType;- m_ClipFillType = clipFillType;- m_ClipType = clipType;- m_UsingPolyTree = true;- bool succeeded = ExecuteInternal();- if (succeeded) BuildResult2(polytree);- DisposeAllOutRecs();- m_ExecuteLocked = false;- return succeeded;- }-//-------------------------------------------------------------------------------- void Clipper::FixHoleLinkage(OutRec &outrec)- {- //skip OutRecs that (a) contain outermost polygons or- //(b) already have the correct owner/child linkage ...- if (!outrec.FirstLeft ||- (outrec.IsHole != outrec.FirstLeft->IsHole &&- outrec.FirstLeft->Pts)) return;-- OutRec* orfl = outrec.FirstLeft;- while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))- orfl = orfl->FirstLeft;- outrec.FirstLeft = orfl;- }-//-------------------------------------------------------------------------------- bool Clipper::ExecuteInternal()- {- bool succeeded = true;- try {- Reset();- m_Maxima = MaximaList();- m_SortedEdges = 0;-- succeeded = true;- cInt botY, topY;- if (!PopScanbeam(botY)) return false;- InsertLocalMinimaIntoAEL(botY);- while (PopScanbeam(topY) || LocalMinimaPending())- {- ProcessHorizontals();- ClearGhostJoins();- if (!ProcessIntersections(topY))- {- succeeded = false;- break;- }- ProcessEdgesAtTopOfScanbeam(topY);- botY = topY;- InsertLocalMinimaIntoAEL(botY);- }- }- catch(...)- {- succeeded = false;- }-- if (succeeded)- {- //fix orientations ...- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- OutRec *outRec = m_PolyOuts[i];- if (!outRec->Pts || outRec->IsOpen) continue;- if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))- ReversePolyPtLinks(outRec->Pts);- }-- if (!m_Joins.empty()) JoinCommonEdges();-- //unfortunately FixupOutPolygon() must be done after JoinCommonEdges()- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- OutRec *outRec = m_PolyOuts[i];- if (!outRec->Pts) continue;- if (outRec->IsOpen)- FixupOutPolyline(*outRec);- else- FixupOutPolygon(*outRec);- }-- if (m_StrictSimple) DoSimplePolygons();- }-- ClearJoins();- ClearGhostJoins();- return succeeded;- }-//-------------------------------------------------------------------------------- void Clipper::SetWindingCount(TEdge &edge)- {- TEdge *e = edge.PrevInAEL;- //find the edge of the same polytype that immediately preceeds 'edge' in AEL- while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;- if (!e)- {- if (edge.WindDelta == 0)- {- PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);- edge.WindCnt = (pft == pftNegative ? -1 : 1);- }- else- edge.WindCnt = edge.WindDelta;- edge.WindCnt2 = 0;- e = m_ActiveEdges; //ie get ready to calc WindCnt2- }- else if (edge.WindDelta == 0 && m_ClipType != ctUnion)- {- edge.WindCnt = 1;- edge.WindCnt2 = e->WindCnt2;- e = e->NextInAEL; //ie get ready to calc WindCnt2- }- else if (IsEvenOddFillType(edge))- {- //EvenOdd filling ...- if (edge.WindDelta == 0)- {- //are we inside a subj polygon ...- bool Inside = true;- TEdge *e2 = e->PrevInAEL;- while (e2)- {- if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)- Inside = !Inside;- e2 = e2->PrevInAEL;- }- edge.WindCnt = (Inside ? 0 : 1);- }- else- {- edge.WindCnt = edge.WindDelta;- }- edge.WindCnt2 = e->WindCnt2;- e = e->NextInAEL; //ie get ready to calc WindCnt2- }- else- {- //nonZero, Positive or Negative filling ...- if (e->WindCnt * e->WindDelta < 0)- {- //prev edge is 'decreasing' WindCount (WC) toward zero- //so we're outside the previous polygon ...- if (Abs(e->WindCnt) > 1)- {- //outside prev poly but still inside another.- //when reversing direction of prev poly use the same WC- if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;- //otherwise continue to 'decrease' WC ...- else edge.WindCnt = e->WindCnt + edge.WindDelta;- }- else- //now outside all polys of same polytype so set own WC ...- edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);- } else- {- //prev edge is 'increasing' WindCount (WC) away from zero- //so we're inside the previous polygon ...- if (edge.WindDelta == 0)- edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);- //if wind direction is reversing prev then use same WC- else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;- //otherwise add to WC ...- else edge.WindCnt = e->WindCnt + edge.WindDelta;- }- edge.WindCnt2 = e->WindCnt2;- e = e->NextInAEL; //ie get ready to calc WindCnt2- }-- //update WindCnt2 ...- if (IsEvenOddAltFillType(edge))- {- //EvenOdd filling ...- while (e != &edge)- {- if (e->WindDelta != 0)- edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);- e = e->NextInAEL;- }- } else- {- //nonZero, Positive or Negative filling ...- while ( e != &edge )- {- edge.WindCnt2 += e->WindDelta;- e = e->NextInAEL;- }- }- }-//-------------------------------------------------------------------------------- bool Clipper::IsEvenOddFillType(const TEdge& edge) const- {- if (edge.PolyTyp == ptSubject)- return m_SubjFillType == pftEvenOdd; else- return m_ClipFillType == pftEvenOdd;- }-//-------------------------------------------------------------------------------- bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const- {- if (edge.PolyTyp == ptSubject)- return m_ClipFillType == pftEvenOdd; else- return m_SubjFillType == pftEvenOdd;- }-//-------------------------------------------------------------------------------- bool Clipper::IsContributing(const TEdge& edge) const- {- PolyFillType pft, pft2;- if (edge.PolyTyp == ptSubject)- {- pft = m_SubjFillType;- pft2 = m_ClipFillType;- } else- {- pft = m_ClipFillType;- pft2 = m_SubjFillType;- }-- switch(pft)- {- case pftEvenOdd:- //return false if a subj line has been flagged as inside a subj polygon- if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;- break;- case pftNonZero:- if (Abs(edge.WindCnt) != 1) return false;- break;- case pftPositive:- if (edge.WindCnt != 1) return false;- break;- default: //pftNegative- if (edge.WindCnt != -1) return false;- }-- switch(m_ClipType)- {- case ctIntersection:- switch(pft2)- {- case pftEvenOdd:- case pftNonZero:- return (edge.WindCnt2 != 0);- case pftPositive:- return (edge.WindCnt2 > 0);- default:- return (edge.WindCnt2 < 0);- }- break;- case ctUnion:- switch(pft2)- {- case pftEvenOdd:- case pftNonZero:- return (edge.WindCnt2 == 0);- case pftPositive:- return (edge.WindCnt2 <= 0);- default:- return (edge.WindCnt2 >= 0);- }- break;- case ctDifference:- if (edge.PolyTyp == ptSubject)- switch(pft2)- {- case pftEvenOdd:- case pftNonZero:- return (edge.WindCnt2 == 0);- case pftPositive:- return (edge.WindCnt2 <= 0);- default:- return (edge.WindCnt2 >= 0);- }- else- switch(pft2)- {- case pftEvenOdd:- case pftNonZero:- return (edge.WindCnt2 != 0);- case pftPositive:- return (edge.WindCnt2 > 0);- default:- return (edge.WindCnt2 < 0);- }- break;- case ctXor:- if (edge.WindDelta == 0) //XOr always contributing unless open- switch(pft2)- {- case pftEvenOdd:- case pftNonZero:- return (edge.WindCnt2 == 0);- case pftPositive:- return (edge.WindCnt2 <= 0);- default:- return (edge.WindCnt2 >= 0);- }- else- return true;- break;- default:- return true;- }- }-//-------------------------------------------------------------------------------- OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)- {- OutPt* result;- TEdge *e, *prevE;- if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))- {- result = AddOutPt(e1, Pt);- e2->OutIdx = e1->OutIdx;- e1->Side = esLeft;- e2->Side = esRight;- e = e1;- if (e->PrevInAEL == e2)- prevE = e2->PrevInAEL;- else- prevE = e->PrevInAEL;- } else- {- result = AddOutPt(e2, Pt);- e1->OutIdx = e2->OutIdx;- e1->Side = esRight;- e2->Side = esLeft;- e = e2;- if (e->PrevInAEL == e1)- prevE = e1->PrevInAEL;- else- prevE = e->PrevInAEL;- }-- if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)- {- cInt xPrev = TopX(*prevE, Pt.Y);- cInt xE = TopX(*e, Pt.Y);- if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&- SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))- {- OutPt* outPt = AddOutPt(prevE, Pt);- AddJoin(result, outPt, e->Top);- }- }- return result;- }-//-------------------------------------------------------------------------------- void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)- {- AddOutPt( e1, Pt );- if (e2->WindDelta == 0) AddOutPt(e2, Pt);- if( e1->OutIdx == e2->OutIdx )- {- e1->OutIdx = Unassigned;- e2->OutIdx = Unassigned;- }- else if (e1->OutIdx < e2->OutIdx)- AppendPolygon(e1, e2);- else- AppendPolygon(e2, e1);- }-//-------------------------------------------------------------------------------- void Clipper::AddEdgeToSEL(TEdge *edge)- {- //SEL pointers in PEdge are reused to build a list of horizontal edges.- //However, we don't need to worry about order with horizontal edge processing.- if( !m_SortedEdges )- {- m_SortedEdges = edge;- edge->PrevInSEL = 0;- edge->NextInSEL = 0;- }- else- {- edge->NextInSEL = m_SortedEdges;- edge->PrevInSEL = 0;- m_SortedEdges->PrevInSEL = edge;- m_SortedEdges = edge;- }- }-//-------------------------------------------------------------------------------- bool Clipper::PopEdgeFromSEL(TEdge *&edge)- {- if (!m_SortedEdges) return false;- edge = m_SortedEdges;- DeleteFromSEL(m_SortedEdges);- return true;- }-//-------------------------------------------------------------------------------- void Clipper::CopyAELToSEL()- {- TEdge* e = m_ActiveEdges;- m_SortedEdges = e;- while ( e )- {- e->PrevInSEL = e->PrevInAEL;- e->NextInSEL = e->NextInAEL;- e = e->NextInAEL;- }- }-//-------------------------------------------------------------------------------- void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)- {- Join* j = new Join;- j->OutPt1 = op1;- j->OutPt2 = op2;- j->OffPt = OffPt;- m_Joins.push_back(j);- }-//-------------------------------------------------------------------------------- void Clipper::ClearJoins()- {- for (JoinList::size_type i = 0; i < m_Joins.size(); i++)- delete m_Joins[i];- m_Joins.resize(0);- }-//-------------------------------------------------------------------------------- void Clipper::ClearGhostJoins()- {- for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)- delete m_GhostJoins[i];- m_GhostJoins.resize(0);- }-//-------------------------------------------------------------------------------- void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)- {- Join* j = new Join;- j->OutPt1 = op;- j->OutPt2 = 0;- j->OffPt = OffPt;- m_GhostJoins.push_back(j);- }-//-------------------------------------------------------------------------------- void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)- {- const LocalMinimum *lm;- while (PopLocalMinima(botY, lm))- {- TEdge* lb = lm->LeftBound;- TEdge* rb = lm->RightBound;-- OutPt *Op1 = 0;- if (!lb)- {- //nb: don't insert LB into either AEL or SEL- InsertEdgeIntoAEL(rb, 0);- SetWindingCount(*rb);- if (IsContributing(*rb))- Op1 = AddOutPt(rb, rb->Bot);- }- else if (!rb)- {- InsertEdgeIntoAEL(lb, 0);- SetWindingCount(*lb);- if (IsContributing(*lb))- Op1 = AddOutPt(lb, lb->Bot);- InsertScanbeam(lb->Top.Y);- }- else- {- InsertEdgeIntoAEL(lb, 0);- InsertEdgeIntoAEL(rb, lb);- SetWindingCount( *lb );- rb->WindCnt = lb->WindCnt;- rb->WindCnt2 = lb->WindCnt2;- if (IsContributing(*lb))- Op1 = AddLocalMinPoly(lb, rb, lb->Bot);- InsertScanbeam(lb->Top.Y);- }-- if (rb)- {- if (IsHorizontal(*rb))- {- AddEdgeToSEL(rb);- if (rb->NextInLML)- InsertScanbeam(rb->NextInLML->Top.Y);- }- else InsertScanbeam( rb->Top.Y );- }-- if (!lb || !rb) continue;-- //if any output polygons share an edge, they'll need joining later ...- if (Op1 && IsHorizontal(*rb) &&- m_GhostJoins.size() > 0 && (rb->WindDelta != 0))- {- for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)- {- Join* jr = m_GhostJoins[i];- //if the horizontal Rb and a 'ghost' horizontal overlap, then convert- //the 'ghost' join to a real join ready for later ...- if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))- AddJoin(jr->OutPt1, Op1, jr->OffPt);- }- }-- if (lb->OutIdx >= 0 && lb->PrevInAEL &&- lb->PrevInAEL->Curr.X == lb->Bot.X &&- lb->PrevInAEL->OutIdx >= 0 &&- SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&- (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))- {- OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);- AddJoin(Op1, Op2, lb->Top);- }-- if(lb->NextInAEL != rb)- {-- if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&- SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&- (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))- {- OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);- AddJoin(Op1, Op2, rb->Top);- }-- TEdge* e = lb->NextInAEL;- if (e)- {- while( e != rb )- {- //nb: For calculating winding counts etc, IntersectEdges() assumes- //that param1 will be to the Right of param2 ABOVE the intersection ...- IntersectEdges(rb , e , lb->Curr); //order important here- e = e->NextInAEL;- }- }- }-- }- }-//-------------------------------------------------------------------------------- void Clipper::DeleteFromSEL(TEdge *e)- {- TEdge* SelPrev = e->PrevInSEL;- TEdge* SelNext = e->NextInSEL;- if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted- if( SelPrev ) SelPrev->NextInSEL = SelNext;- else m_SortedEdges = SelNext;- if( SelNext ) SelNext->PrevInSEL = SelPrev;- e->NextInSEL = 0;- e->PrevInSEL = 0;- }-//--------------------------------------------------------------------------------#ifdef use_xyz- void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)-{- if (pt.Z != 0 || !m_ZFill) return;- else if (pt == e1.Bot) pt.Z = e1.Bot.Z;- else if (pt == e1.Top) pt.Z = e1.Top.Z;- else if (pt == e2.Bot) pt.Z = e2.Bot.Z;- else if (pt == e2.Top) pt.Z = e2.Top.Z;- else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);-}-//-------------------------------------------------------------------------------#endif-- void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)- {- bool e1Contributing = ( e1->OutIdx >= 0 );- bool e2Contributing = ( e2->OutIdx >= 0 );--#ifdef use_xyz- SetZ(Pt, *e1, *e2);-#endif--#ifdef use_lines- //if either edge is on an OPEN path ...- if (e1->WindDelta == 0 || e2->WindDelta == 0)- {- //ignore subject-subject open path intersections UNLESS they- //are both open paths, AND they are both 'contributing maximas' ...- if (e1->WindDelta == 0 && e2->WindDelta == 0) return;-- //if intersecting a subj line with a subj poly ...- else if (e1->PolyTyp == e2->PolyTyp &&- e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)- {- if (e1->WindDelta == 0)- {- if (e2Contributing)- {- AddOutPt(e1, Pt);- if (e1Contributing) e1->OutIdx = Unassigned;- }- }- else- {- if (e1Contributing)- {- AddOutPt(e2, Pt);- if (e2Contributing) e2->OutIdx = Unassigned;- }- }- }- else if (e1->PolyTyp != e2->PolyTyp)- {- //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...- if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&- (m_ClipType != ctUnion || e2->WindCnt2 == 0))- {- AddOutPt(e1, Pt);- if (e1Contributing) e1->OutIdx = Unassigned;- }- else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&- (m_ClipType != ctUnion || e1->WindCnt2 == 0))- {- AddOutPt(e2, Pt);- if (e2Contributing) e2->OutIdx = Unassigned;- }- }- return;- }-#endif-- //update winding counts...- //assumes that e1 will be to the Right of e2 ABOVE the intersection- if ( e1->PolyTyp == e2->PolyTyp )- {- if ( IsEvenOddFillType( *e1) )- {- int oldE1WindCnt = e1->WindCnt;- e1->WindCnt = e2->WindCnt;- e2->WindCnt = oldE1WindCnt;- } else- {- if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;- else e1->WindCnt += e2->WindDelta;- if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;- else e2->WindCnt -= e1->WindDelta;- }- } else- {- if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;- else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;- if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;- else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;- }-- PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;- if (e1->PolyTyp == ptSubject)- {- e1FillType = m_SubjFillType;- e1FillType2 = m_ClipFillType;- } else- {- e1FillType = m_ClipFillType;- e1FillType2 = m_SubjFillType;- }- if (e2->PolyTyp == ptSubject)- {- e2FillType = m_SubjFillType;- e2FillType2 = m_ClipFillType;- } else- {- e2FillType = m_ClipFillType;- e2FillType2 = m_SubjFillType;- }-- cInt e1Wc, e2Wc;- switch (e1FillType)- {- case pftPositive: e1Wc = e1->WindCnt; break;- case pftNegative: e1Wc = -e1->WindCnt; break;- default: e1Wc = Abs(e1->WindCnt);- }- switch(e2FillType)- {- case pftPositive: e2Wc = e2->WindCnt; break;- case pftNegative: e2Wc = -e2->WindCnt; break;- default: e2Wc = Abs(e2->WindCnt);- }-- if ( e1Contributing && e2Contributing )- {- if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||- (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )- {- AddLocalMaxPoly(e1, e2, Pt);- }- else- {- AddOutPt(e1, Pt);- AddOutPt(e2, Pt);- SwapSides( *e1 , *e2 );- SwapPolyIndexes( *e1 , *e2 );- }- }- else if ( e1Contributing )- {- if (e2Wc == 0 || e2Wc == 1)- {- AddOutPt(e1, Pt);- SwapSides(*e1, *e2);- SwapPolyIndexes(*e1, *e2);- }- }- else if ( e2Contributing )- {- if (e1Wc == 0 || e1Wc == 1)- {- AddOutPt(e2, Pt);- SwapSides(*e1, *e2);- SwapPolyIndexes(*e1, *e2);- }- }- else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))- {- //neither edge is currently contributing ...-- cInt e1Wc2, e2Wc2;- switch (e1FillType2)- {- case pftPositive: e1Wc2 = e1->WindCnt2; break;- case pftNegative : e1Wc2 = -e1->WindCnt2; break;- default: e1Wc2 = Abs(e1->WindCnt2);- }- switch (e2FillType2)- {- case pftPositive: e2Wc2 = e2->WindCnt2; break;- case pftNegative: e2Wc2 = -e2->WindCnt2; break;- default: e2Wc2 = Abs(e2->WindCnt2);- }-- if (e1->PolyTyp != e2->PolyTyp)- {- AddLocalMinPoly(e1, e2, Pt);- }- else if (e1Wc == 1 && e2Wc == 1)- switch( m_ClipType ) {- case ctIntersection:- if (e1Wc2 > 0 && e2Wc2 > 0)- AddLocalMinPoly(e1, e2, Pt);- break;- case ctUnion:- if ( e1Wc2 <= 0 && e2Wc2 <= 0 )- AddLocalMinPoly(e1, e2, Pt);- break;- case ctDifference:- if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||- ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))- AddLocalMinPoly(e1, e2, Pt);- break;- case ctXor:- AddLocalMinPoly(e1, e2, Pt);- }- else- SwapSides( *e1, *e2 );- }- }-//-------------------------------------------------------------------------------- void Clipper::SetHoleState(TEdge *e, OutRec *outrec)- {- TEdge *e2 = e->PrevInAEL;- TEdge *eTmp = 0;- while (e2)- {- if (e2->OutIdx >= 0 && e2->WindDelta != 0)- {- if (!eTmp) eTmp = e2;- else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;- }- e2 = e2->PrevInAEL;- }- if (!eTmp)- {- outrec->FirstLeft = 0;- outrec->IsHole = false;- }- else- {- outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];- outrec->IsHole = !outrec->FirstLeft->IsHole;- }- }-//-------------------------------------------------------------------------------- OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)- {- //work out which polygon fragment has the correct hole state ...- if (!outRec1->BottomPt)- outRec1->BottomPt = GetBottomPt(outRec1->Pts);- if (!outRec2->BottomPt)- outRec2->BottomPt = GetBottomPt(outRec2->Pts);- OutPt *OutPt1 = outRec1->BottomPt;- OutPt *OutPt2 = outRec2->BottomPt;- if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;- else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;- else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;- else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;- else if (OutPt1->Next == OutPt1) return outRec2;- else if (OutPt2->Next == OutPt2) return outRec1;- else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;- else return outRec2;- }-//-------------------------------------------------------------------------------- bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)- {- do- {- outRec1 = outRec1->FirstLeft;- if (outRec1 == outRec2) return true;- } while (outRec1);- return false;- }-//-------------------------------------------------------------------------------- OutRec* Clipper::GetOutRec(int Idx)- {- OutRec* outrec = m_PolyOuts[Idx];- while (outrec != m_PolyOuts[outrec->Idx])- outrec = m_PolyOuts[outrec->Idx];- return outrec;- }-//-------------------------------------------------------------------------------- void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)- {- //get the start and ends of both output polygons ...- OutRec *outRec1 = m_PolyOuts[e1->OutIdx];- OutRec *outRec2 = m_PolyOuts[e2->OutIdx];-- OutRec *holeStateRec;- if (OutRec1RightOfOutRec2(outRec1, outRec2))- holeStateRec = outRec2;- else if (OutRec1RightOfOutRec2(outRec2, outRec1))- holeStateRec = outRec1;- else- holeStateRec = GetLowermostRec(outRec1, outRec2);-- //get the start and ends of both output polygons and- //join e2 poly onto e1 poly and delete pointers to e2 ...-- OutPt* p1_lft = outRec1->Pts;- OutPt* p1_rt = p1_lft->Prev;- OutPt* p2_lft = outRec2->Pts;- OutPt* p2_rt = p2_lft->Prev;-- //join e2 poly onto e1 poly and delete pointers to e2 ...- if( e1->Side == esLeft )- {- if( e2->Side == esLeft )- {- //z y x a b c- ReversePolyPtLinks(p2_lft);- p2_lft->Next = p1_lft;- p1_lft->Prev = p2_lft;- p1_rt->Next = p2_rt;- p2_rt->Prev = p1_rt;- outRec1->Pts = p2_rt;- } else- {- //x y z a b c- p2_rt->Next = p1_lft;- p1_lft->Prev = p2_rt;- p2_lft->Prev = p1_rt;- p1_rt->Next = p2_lft;- outRec1->Pts = p2_lft;- }- } else- {- if( e2->Side == esRight )- {- //a b c z y x- ReversePolyPtLinks(p2_lft);- p1_rt->Next = p2_rt;- p2_rt->Prev = p1_rt;- p2_lft->Next = p1_lft;- p1_lft->Prev = p2_lft;- } else- {- //a b c x y z- p1_rt->Next = p2_lft;- p2_lft->Prev = p1_rt;- p1_lft->Prev = p2_rt;- p2_rt->Next = p1_lft;- }- }-- outRec1->BottomPt = 0;- if (holeStateRec == outRec2)- {- if (outRec2->FirstLeft != outRec1)- outRec1->FirstLeft = outRec2->FirstLeft;- outRec1->IsHole = outRec2->IsHole;- }- outRec2->Pts = 0;- outRec2->BottomPt = 0;- outRec2->FirstLeft = outRec1;-- int OKIdx = e1->OutIdx;- int ObsoleteIdx = e2->OutIdx;-- e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly- e2->OutIdx = Unassigned;-- TEdge* e = m_ActiveEdges;- while( e )- {- if( e->OutIdx == ObsoleteIdx )- {- e->OutIdx = OKIdx;- e->Side = e1->Side;- break;- }- e = e->NextInAEL;- }-- outRec2->Idx = outRec1->Idx;- }-//-------------------------------------------------------------------------------- OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)- {- if( e->OutIdx < 0 )- {- OutRec *outRec = CreateOutRec();- outRec->IsOpen = (e->WindDelta == 0);- OutPt* newOp = new OutPt;- outRec->Pts = newOp;- newOp->Idx = outRec->Idx;- newOp->Pt = pt;- newOp->Next = newOp;- newOp->Prev = newOp;- if (!outRec->IsOpen)- SetHoleState(e, outRec);- e->OutIdx = outRec->Idx;- return newOp;- } else- {- OutRec *outRec = m_PolyOuts[e->OutIdx];- //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'- OutPt* op = outRec->Pts;-- bool ToFront = (e->Side == esLeft);- if (ToFront && (pt == op->Pt)) return op;- else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;-- OutPt* newOp = new OutPt;- newOp->Idx = outRec->Idx;- newOp->Pt = pt;- newOp->Next = op;- newOp->Prev = op->Prev;- newOp->Prev->Next = newOp;- op->Prev = newOp;- if (ToFront) outRec->Pts = newOp;- return newOp;- }- }-//-------------------------------------------------------------------------------- OutPt* Clipper::GetLastOutPt(TEdge *e)- {- OutRec *outRec = m_PolyOuts[e->OutIdx];- if (e->Side == esLeft)- return outRec->Pts;- else- return outRec->Pts->Prev;- }-//-------------------------------------------------------------------------------- void Clipper::ProcessHorizontals()- {- TEdge* horzEdge;- while (PopEdgeFromSEL(horzEdge))- ProcessHorizontal(horzEdge);- }-//-------------------------------------------------------------------------------- inline bool IsMinima(TEdge *e)- {- return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);- }-//-------------------------------------------------------------------------------- inline bool IsMaxima(TEdge *e, const cInt Y)- {- return e && e->Top.Y == Y && !e->NextInLML;- }-//-------------------------------------------------------------------------------- inline bool IsIntermediate(TEdge *e, const cInt Y)- {- return e->Top.Y == Y && e->NextInLML;- }-//-------------------------------------------------------------------------------- TEdge *GetMaximaPair(TEdge *e)- {- if ((e->Next->Top == e->Top) && !e->Next->NextInLML)- return e->Next;- else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)- return e->Prev;- else return 0;- }-//-------------------------------------------------------------------------------- TEdge *GetMaximaPairEx(TEdge *e)- {- //as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)- TEdge* result = GetMaximaPair(e);- if (result && (result->OutIdx == Skip ||- (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;- return result;- }-//-------------------------------------------------------------------------------- void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)- {- if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;- if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;-- if( Edge1->NextInSEL == Edge2 )- {- TEdge* Next = Edge2->NextInSEL;- if( Next ) Next->PrevInSEL = Edge1;- TEdge* Prev = Edge1->PrevInSEL;- if( Prev ) Prev->NextInSEL = Edge2;- Edge2->PrevInSEL = Prev;- Edge2->NextInSEL = Edge1;- Edge1->PrevInSEL = Edge2;- Edge1->NextInSEL = Next;- }- else if( Edge2->NextInSEL == Edge1 )- {- TEdge* Next = Edge1->NextInSEL;- if( Next ) Next->PrevInSEL = Edge2;- TEdge* Prev = Edge2->PrevInSEL;- if( Prev ) Prev->NextInSEL = Edge1;- Edge1->PrevInSEL = Prev;- Edge1->NextInSEL = Edge2;- Edge2->PrevInSEL = Edge1;- Edge2->NextInSEL = Next;- }- else- {- TEdge* Next = Edge1->NextInSEL;- TEdge* Prev = Edge1->PrevInSEL;- Edge1->NextInSEL = Edge2->NextInSEL;- if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;- Edge1->PrevInSEL = Edge2->PrevInSEL;- if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;- Edge2->NextInSEL = Next;- if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;- Edge2->PrevInSEL = Prev;- if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;- }-- if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;- else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;- }-//-------------------------------------------------------------------------------- TEdge* GetNextInAEL(TEdge *e, Direction dir)- {- return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;- }-//-------------------------------------------------------------------------------- void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)- {- if (HorzEdge.Bot.X < HorzEdge.Top.X)- {- Left = HorzEdge.Bot.X;- Right = HorzEdge.Top.X;- Dir = dLeftToRight;- } else- {- Left = HorzEdge.Top.X;- Right = HorzEdge.Bot.X;- Dir = dRightToLeft;- }- }-//--------------------------------------------------------------------------/*******************************************************************************-* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *-* Bottom of a scanbeam) are processed as if layered. The order in which HEs *-* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *-* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *-* and with other non-horizontal edges [*]. Once these intersections are *-* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *-* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *-*******************************************************************************/-- void Clipper::ProcessHorizontal(TEdge *horzEdge)- {- Direction dir;- cInt horzLeft, horzRight;- bool IsOpen = (horzEdge->WindDelta == 0);-- GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);-- TEdge* eLastHorz = horzEdge, *eMaxPair = 0;- while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))- eLastHorz = eLastHorz->NextInLML;- if (!eLastHorz->NextInLML)- eMaxPair = GetMaximaPair(eLastHorz);-- MaximaList::const_iterator maxIt;- MaximaList::const_reverse_iterator maxRit;- if (m_Maxima.size() > 0)- {- //get the first maxima in range (X) ...- if (dir == dLeftToRight)- {- maxIt = m_Maxima.begin();- while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;- if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)- maxIt = m_Maxima.end();- }- else- {- maxRit = m_Maxima.rbegin();- while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;- if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)- maxRit = m_Maxima.rend();- }- }-- OutPt* op1 = 0;-- for (;;) //loop through consec. horizontal edges- {-- bool IsLastHorz = (horzEdge == eLastHorz);- TEdge* e = GetNextInAEL(horzEdge, dir);- while(e)- {-- //this code block inserts extra coords into horizontal edges (in output- //polygons) whereever maxima touch these horizontal edges. This helps- //'simplifying' polygons (ie if the Simplify property is set).- if (m_Maxima.size() > 0)- {- if (dir == dLeftToRight)- {- while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)- {- if (horzEdge->OutIdx >= 0 && !IsOpen)- AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));- maxIt++;- }- }- else- {- while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)- {- if (horzEdge->OutIdx >= 0 && !IsOpen)- AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));- maxRit++;- }- }- };-- if ((dir == dLeftToRight && e->Curr.X > horzRight) ||- (dir == dRightToLeft && e->Curr.X < horzLeft)) break;-- //Also break if we've got to the end of an intermediate horizontal edge ...- //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.- if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&- e->Dx < horzEdge->NextInLML->Dx) break;-- if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times- {-#ifdef use_xyz- if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);- else SetZ(e->Curr, *e, *horzEdge);-#endif- op1 = AddOutPt(horzEdge, e->Curr);- TEdge* eNextHorz = m_SortedEdges;- while (eNextHorz)- {- if (eNextHorz->OutIdx >= 0 &&- HorzSegmentsOverlap(horzEdge->Bot.X,- horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))- {- OutPt* op2 = GetLastOutPt(eNextHorz);- AddJoin(op2, op1, eNextHorz->Top);- }- eNextHorz = eNextHorz->NextInSEL;- }- AddGhostJoin(op1, horzEdge->Bot);- }-- //OK, so far we're still in range of the horizontal Edge but make sure- //we're at the last of consec. horizontals when matching with eMaxPair- if(e == eMaxPair && IsLastHorz)- {- if (horzEdge->OutIdx >= 0)- AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);- DeleteFromAEL(horzEdge);- DeleteFromAEL(eMaxPair);- return;- }-- if(dir == dLeftToRight)- {- IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);- IntersectEdges(horzEdge, e, Pt);- }- else- {- IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);- IntersectEdges( e, horzEdge, Pt);- }- TEdge* eNext = GetNextInAEL(e, dir);- SwapPositionsInAEL( horzEdge, e );- e = eNext;- } //end while(e)-- //Break out of loop if HorzEdge.NextInLML is not also horizontal ...- if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;-- UpdateEdgeIntoAEL(horzEdge);- if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);- GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);-- } //end for (;;)-- if (horzEdge->OutIdx >= 0 && !op1)- {- op1 = GetLastOutPt(horzEdge);- TEdge* eNextHorz = m_SortedEdges;- while (eNextHorz)- {- if (eNextHorz->OutIdx >= 0 &&- HorzSegmentsOverlap(horzEdge->Bot.X,- horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))- {- OutPt* op2 = GetLastOutPt(eNextHorz);- AddJoin(op2, op1, eNextHorz->Top);- }- eNextHorz = eNextHorz->NextInSEL;- }- AddGhostJoin(op1, horzEdge->Top);- }-- if (horzEdge->NextInLML)- {- if(horzEdge->OutIdx >= 0)- {- op1 = AddOutPt( horzEdge, horzEdge->Top);- UpdateEdgeIntoAEL(horzEdge);- if (horzEdge->WindDelta == 0) return;- //nb: HorzEdge is no longer horizontal here- TEdge* ePrev = horzEdge->PrevInAEL;- TEdge* eNext = horzEdge->NextInAEL;- if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&- ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&- (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&- SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))- {- OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);- AddJoin(op1, op2, horzEdge->Top);- }- else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&- eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&- eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&- SlopesEqual(*horzEdge, *eNext, m_UseFullRange))- {- OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);- AddJoin(op1, op2, horzEdge->Top);- }- }- else- UpdateEdgeIntoAEL(horzEdge);- }- else- {- if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);- DeleteFromAEL(horzEdge);- }- }-//-------------------------------------------------------------------------------- bool Clipper::ProcessIntersections(const cInt topY)- {- if( !m_ActiveEdges ) return true;- try {- BuildIntersectList(topY);- size_t IlSize = m_IntersectList.size();- if (IlSize == 0) return true;- if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();- else return false;- }- catch(...)- {- m_SortedEdges = 0;- DisposeIntersectNodes();- throw clipperException("ProcessIntersections error");- }- m_SortedEdges = 0;- return true;- }-//-------------------------------------------------------------------------------- void Clipper::DisposeIntersectNodes()- {- for (size_t i = 0; i < m_IntersectList.size(); ++i )- delete m_IntersectList[i];- m_IntersectList.clear();- }-//-------------------------------------------------------------------------------- void Clipper::BuildIntersectList(const cInt topY)- {- if ( !m_ActiveEdges ) return;-- //prepare for sorting ...- TEdge* e = m_ActiveEdges;- m_SortedEdges = e;- while( e )- {- e->PrevInSEL = e->PrevInAEL;- e->NextInSEL = e->NextInAEL;- e->Curr.X = TopX( *e, topY );- e = e->NextInAEL;- }-- //bubblesort ...- bool isModified;- do- {- isModified = false;- e = m_SortedEdges;- while( e->NextInSEL )- {- TEdge *eNext = e->NextInSEL;- IntPoint Pt;- if(e->Curr.X > eNext->Curr.X)- {- IntersectPoint(*e, *eNext, Pt);- if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);- IntersectNode * newNode = new IntersectNode;- newNode->Edge1 = e;- newNode->Edge2 = eNext;- newNode->Pt = Pt;- m_IntersectList.push_back(newNode);-- SwapPositionsInSEL(e, eNext);- isModified = true;- }- else- e = eNext;- }- if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;- else break;- }- while ( isModified );- m_SortedEdges = 0; //important- }-//--------------------------------------------------------------------------------- void Clipper::ProcessIntersectList()- {- for (size_t i = 0; i < m_IntersectList.size(); ++i)- {- IntersectNode* iNode = m_IntersectList[i];- {- IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);- SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );- }- delete iNode;- }- m_IntersectList.clear();- }-//-------------------------------------------------------------------------------- bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)- {- return node2->Pt.Y < node1->Pt.Y;- }-//-------------------------------------------------------------------------------- inline bool EdgesAdjacent(const IntersectNode &inode)- {- return (inode.Edge1->NextInSEL == inode.Edge2) ||- (inode.Edge1->PrevInSEL == inode.Edge2);- }-//-------------------------------------------------------------------------------- bool Clipper::FixupIntersectionOrder()- {- //pre-condition: intersections are sorted Bottom-most first.- //Now it's crucial that intersections are made only between adjacent edges,- //so to ensure this the order of intersections may need adjusting ...- CopyAELToSEL();- std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);- size_t cnt = m_IntersectList.size();- for (size_t i = 0; i < cnt; ++i)- {- if (!EdgesAdjacent(*m_IntersectList[i]))- {- size_t j = i + 1;- while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;- if (j == cnt) return false;- std::swap(m_IntersectList[i], m_IntersectList[j]);- }- SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);- }- return true;- }-//-------------------------------------------------------------------------------- void Clipper::DoMaxima(TEdge *e)- {- TEdge* eMaxPair = GetMaximaPairEx(e);- if (!eMaxPair)- {- if (e->OutIdx >= 0)- AddOutPt(e, e->Top);- DeleteFromAEL(e);- return;- }-- TEdge* eNext = e->NextInAEL;- while(eNext && eNext != eMaxPair)- {- IntersectEdges(e, eNext, e->Top);- SwapPositionsInAEL(e, eNext);- eNext = e->NextInAEL;- }-- if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)- {- DeleteFromAEL(e);- DeleteFromAEL(eMaxPair);- }- else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )- {- if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);- DeleteFromAEL(e);- DeleteFromAEL(eMaxPair);- }-#ifdef use_lines- else if (e->WindDelta == 0)- {- if (e->OutIdx >= 0)- {- AddOutPt(e, e->Top);- e->OutIdx = Unassigned;- }- DeleteFromAEL(e);-- if (eMaxPair->OutIdx >= 0)- {- AddOutPt(eMaxPair, e->Top);- eMaxPair->OutIdx = Unassigned;- }- DeleteFromAEL(eMaxPair);- }-#endif- else throw clipperException("DoMaxima error");- }-//-------------------------------------------------------------------------------- void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)- {- TEdge* e = m_ActiveEdges;- while( e )- {- //1. process maxima, treating them as if they're 'bent' horizontal edges,- // but exclude maxima with horizontal edges. nb: e can't be a horizontal.- bool IsMaximaEdge = IsMaxima(e, topY);-- if(IsMaximaEdge)- {- TEdge* eMaxPair = GetMaximaPairEx(e);- IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));- }-- if(IsMaximaEdge)- {- if (m_StrictSimple) m_Maxima.push_back(e->Top.X);- TEdge* ePrev = e->PrevInAEL;- DoMaxima(e);- if( !ePrev ) e = m_ActiveEdges;- else e = ePrev->NextInAEL;- }- else- {- //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...- if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))- {- UpdateEdgeIntoAEL(e);- if (e->OutIdx >= 0)- AddOutPt(e, e->Bot);- AddEdgeToSEL(e);- }- else- {- e->Curr.X = TopX( *e, topY );- e->Curr.Y = topY;-#ifdef use_xyz- e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);-#endif- }-- //When StrictlySimple and 'e' is being touched by another edge, then- //make sure both edges have a vertex here ...- if (m_StrictSimple)- {- TEdge* ePrev = e->PrevInAEL;- if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&- (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))- {- IntPoint pt = e->Curr;-#ifdef use_xyz- SetZ(pt, *ePrev, *e);-#endif- OutPt* op = AddOutPt(ePrev, pt);- OutPt* op2 = AddOutPt(e, pt);- AddJoin(op, op2, pt); //StrictlySimple (type-3) join- }- }-- e = e->NextInAEL;- }- }-- //3. Process horizontals at the Top of the scanbeam ...- m_Maxima.sort();- ProcessHorizontals();- m_Maxima.clear();-- //4. Promote intermediate vertices ...- e = m_ActiveEdges;- while(e)- {- if(IsIntermediate(e, topY))- {- OutPt* op = 0;- if( e->OutIdx >= 0 )- op = AddOutPt(e, e->Top);- UpdateEdgeIntoAEL(e);-- //if output polygons share an edge, they'll need joining later ...- TEdge* ePrev = e->PrevInAEL;- TEdge* eNext = e->NextInAEL;- if (ePrev && ePrev->Curr.X == e->Bot.X &&- ePrev->Curr.Y == e->Bot.Y && op &&- ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&- SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&- (e->WindDelta != 0) && (ePrev->WindDelta != 0))- {- OutPt* op2 = AddOutPt(ePrev, e->Bot);- AddJoin(op, op2, e->Top);- }- else if (eNext && eNext->Curr.X == e->Bot.X &&- eNext->Curr.Y == e->Bot.Y && op &&- eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&- SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&- (e->WindDelta != 0) && (eNext->WindDelta != 0))- {- OutPt* op2 = AddOutPt(eNext, e->Bot);- AddJoin(op, op2, e->Top);- }- }- e = e->NextInAEL;- }- }-//-------------------------------------------------------------------------------- void Clipper::FixupOutPolyline(OutRec &outrec)- {- OutPt *pp = outrec.Pts;- OutPt *lastPP = pp->Prev;- while (pp != lastPP)- {- pp = pp->Next;- if (pp->Pt == pp->Prev->Pt)- {- if (pp == lastPP) lastPP = pp->Prev;- OutPt *tmpPP = pp->Prev;- tmpPP->Next = pp->Next;- pp->Next->Prev = tmpPP;- delete pp;- pp = tmpPP;- }- }-- if (pp == pp->Prev)- {- DisposeOutPts(pp);- outrec.Pts = 0;- return;- }- }-//-------------------------------------------------------------------------------- void Clipper::FixupOutPolygon(OutRec &outrec)- {- //FixupOutPolygon() - removes duplicate points and simplifies consecutive- //parallel edges by removing the middle vertex.- OutPt *lastOK = 0;- outrec.BottomPt = 0;- OutPt *pp = outrec.Pts;- bool preserveCol = m_PreserveCollinear || m_StrictSimple;-- for (;;)- {- if (pp->Prev == pp || pp->Prev == pp->Next)- {- DisposeOutPts(pp);- outrec.Pts = 0;- return;- }-- //test for duplicate points and collinear edges ...- if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||- (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&- (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))- {- lastOK = 0;- OutPt *tmp = pp;- pp->Prev->Next = pp->Next;- pp->Next->Prev = pp->Prev;- pp = pp->Prev;- delete tmp;- }- else if (pp == lastOK) break;- else- {- if (!lastOK) lastOK = pp;- pp = pp->Next;- }- }- outrec.Pts = pp;- }-//-------------------------------------------------------------------------------- int PointCount(OutPt *Pts)- {- if (!Pts) return 0;- int result = 0;- OutPt* p = Pts;- do- {- result++;- p = p->Next;- }- while (p != Pts);- return result;- }-//-------------------------------------------------------------------------------- void Clipper::BuildResult(Paths &polys)- {- polys.reserve(m_PolyOuts.size());- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- if (!m_PolyOuts[i]->Pts) continue;- Path pg;- OutPt* p = m_PolyOuts[i]->Pts->Prev;- int cnt = PointCount(p);- if (cnt < 2) continue;- pg.reserve(cnt);- for (int i = 0; i < cnt; ++i)- {- pg.push_back(p->Pt);- p = p->Prev;- }- polys.push_back(pg);- }- }-//-------------------------------------------------------------------------------- void Clipper::BuildResult2(PolyTree& polytree)- {- polytree.Clear();- polytree.AllNodes.reserve(m_PolyOuts.size());- //add each output polygon/contour to polytree ...- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)- {- OutRec* outRec = m_PolyOuts[i];- int cnt = PointCount(outRec->Pts);- if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;- FixHoleLinkage(*outRec);- PolyNode* pn = new PolyNode();- //nb: polytree takes ownership of all the PolyNodes- polytree.AllNodes.push_back(pn);- outRec->PolyNd = pn;- pn->Parent = 0;- pn->Index = 0;- pn->Contour.reserve(cnt);- OutPt *op = outRec->Pts->Prev;- for (int j = 0; j < cnt; j++)- {- pn->Contour.push_back(op->Pt);- op = op->Prev;- }- }-- //fixup PolyNode links etc ...- polytree.Childs.reserve(m_PolyOuts.size());- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)- {- OutRec* outRec = m_PolyOuts[i];- if (!outRec->PolyNd) continue;- if (outRec->IsOpen)- {- outRec->PolyNd->m_IsOpen = true;- polytree.AddChild(*outRec->PolyNd);- }- else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)- outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);- else- polytree.AddChild(*outRec->PolyNd);- }- }-//-------------------------------------------------------------------------------- void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)- {- //just swap the contents (because fIntersectNodes is a single-linked-list)- IntersectNode inode = int1; //gets a copy of Int1- int1.Edge1 = int2.Edge1;- int1.Edge2 = int2.Edge2;- int1.Pt = int2.Pt;- int2.Edge1 = inode.Edge1;- int2.Edge2 = inode.Edge2;- int2.Pt = inode.Pt;- }-//-------------------------------------------------------------------------------- inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)- {- if (e2.Curr.X == e1.Curr.X)- {- if (e2.Top.Y > e1.Top.Y)- return e2.Top.X < TopX(e1, e2.Top.Y);- else return e1.Top.X > TopX(e2, e1.Top.Y);- }- else return e2.Curr.X < e1.Curr.X;- }-//-------------------------------------------------------------------------------- bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,- cInt& Left, cInt& Right)- {- if (a1 < a2)- {- if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}- else {Left = std::max(a1,b2); Right = std::min(a2,b1);}- }- else- {- if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}- else {Left = std::max(a2,b2); Right = std::min(a1,b1);}- }- return Left < Right;- }-//-------------------------------------------------------------------------------- inline void UpdateOutPtIdxs(OutRec& outrec)- {- OutPt* op = outrec.Pts;- do- {- op->Idx = outrec.Idx;- op = op->Prev;- }- while(op != outrec.Pts);- }-//-------------------------------------------------------------------------------- void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)- {- if(!m_ActiveEdges)- {- edge->PrevInAEL = 0;- edge->NextInAEL = 0;- m_ActiveEdges = edge;- }- else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))- {- edge->PrevInAEL = 0;- edge->NextInAEL = m_ActiveEdges;- m_ActiveEdges->PrevInAEL = edge;- m_ActiveEdges = edge;- }- else- {- if(!startEdge) startEdge = m_ActiveEdges;- while(startEdge->NextInAEL &&- !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))- startEdge = startEdge->NextInAEL;- edge->NextInAEL = startEdge->NextInAEL;- if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;- edge->PrevInAEL = startEdge;- startEdge->NextInAEL = edge;- }- }-//------------------------------------------------------------------------ OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)- {- OutPt* result = new OutPt;- result->Pt = outPt->Pt;- result->Idx = outPt->Idx;- if (InsertAfter)- {- result->Next = outPt->Next;- result->Prev = outPt;- outPt->Next->Prev = result;- outPt->Next = result;- }- else- {- result->Prev = outPt->Prev;- result->Next = outPt;- outPt->Prev->Next = result;- outPt->Prev = result;- }- return result;- }-//-------------------------------------------------------------------------------- bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,- const IntPoint Pt, bool DiscardLeft)- {- Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);- Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);- if (Dir1 == Dir2) return false;-- //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we- //want Op1b to be on the Right. (And likewise with Op2 and Op2b.)- //So, to facilitate this while inserting Op1b and Op2b ...- //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,- //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)- if (Dir1 == dLeftToRight)- {- while (op1->Next->Pt.X <= Pt.X &&- op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)- op1 = op1->Next;- if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;- op1b = DupOutPt(op1, !DiscardLeft);- if (op1b->Pt != Pt)- {- op1 = op1b;- op1->Pt = Pt;- op1b = DupOutPt(op1, !DiscardLeft);- }- }- else- {- while (op1->Next->Pt.X >= Pt.X &&- op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)- op1 = op1->Next;- if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;- op1b = DupOutPt(op1, DiscardLeft);- if (op1b->Pt != Pt)- {- op1 = op1b;- op1->Pt = Pt;- op1b = DupOutPt(op1, DiscardLeft);- }- }-- if (Dir2 == dLeftToRight)- {- while (op2->Next->Pt.X <= Pt.X &&- op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)- op2 = op2->Next;- if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;- op2b = DupOutPt(op2, !DiscardLeft);- if (op2b->Pt != Pt)- {- op2 = op2b;- op2->Pt = Pt;- op2b = DupOutPt(op2, !DiscardLeft);- };- } else- {- while (op2->Next->Pt.X >= Pt.X &&- op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)- op2 = op2->Next;- if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;- op2b = DupOutPt(op2, DiscardLeft);- if (op2b->Pt != Pt)- {- op2 = op2b;- op2->Pt = Pt;- op2b = DupOutPt(op2, DiscardLeft);- };- };-- if ((Dir1 == dLeftToRight) == DiscardLeft)- {- op1->Prev = op2;- op2->Next = op1;- op1b->Next = op2b;- op2b->Prev = op1b;- }- else- {- op1->Next = op2;- op2->Prev = op1;- op1b->Prev = op2b;- op2b->Next = op1b;- }- return true;- }-//-------------------------------------------------------------------------------- bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)- {- OutPt *op1 = j->OutPt1, *op1b;- OutPt *op2 = j->OutPt2, *op2b;-- //There are 3 kinds of joins for output polygons ...- //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere- //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).- //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same- //location at the Bottom of the overlapping segment (& Join.OffPt is above).- //3. StrictSimple joins where edges touch but are not collinear and where- //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.- bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);-- if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&- (j->OffPt == j->OutPt2->Pt))- {- //Strictly Simple join ...- if (outRec1 != outRec2) return false;- op1b = j->OutPt1->Next;- while (op1b != op1 && (op1b->Pt == j->OffPt))- op1b = op1b->Next;- bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);- op2b = j->OutPt2->Next;- while (op2b != op2 && (op2b->Pt == j->OffPt))- op2b = op2b->Next;- bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);- if (reverse1 == reverse2) return false;- if (reverse1)- {- op1b = DupOutPt(op1, false);- op2b = DupOutPt(op2, true);- op1->Prev = op2;- op2->Next = op1;- op1b->Next = op2b;- op2b->Prev = op1b;- j->OutPt1 = op1;- j->OutPt2 = op1b;- return true;- } else- {- op1b = DupOutPt(op1, true);- op2b = DupOutPt(op2, false);- op1->Next = op2;- op2->Prev = op1;- op1b->Prev = op2b;- op2b->Next = op1b;- j->OutPt1 = op1;- j->OutPt2 = op1b;- return true;- }- }- else if (isHorizontal)- {- //treat horizontal joins differently to non-horizontal joins since with- //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt- //may be anywhere along the horizontal edge.- op1b = op1;- while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)- op1 = op1->Prev;- while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)- op1b = op1b->Next;- if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'-- op2b = op2;- while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)- op2 = op2->Prev;- while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)- op2b = op2b->Next;- if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'-- cInt Left, Right;- //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges- if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))- return false;-- //DiscardLeftSide: when overlapping edges are joined, a spike will created- //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up- //on the discard Side as either may still be needed for other joins ...- IntPoint Pt;- bool DiscardLeftSide;- if (op1->Pt.X >= Left && op1->Pt.X <= Right)- {- Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);- }- else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)- {- Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);- }- else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)- {- Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;- }- else- {- Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);- }- j->OutPt1 = op1; j->OutPt2 = op2;- return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);- } else- {- //nb: For non-horizontal joins ...- // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y- // 2. Jr.OutPt1.Pt > Jr.OffPt.Y-- //make sure the polygons are correctly oriented ...- op1b = op1->Next;- while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;- bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||- !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));- if (Reverse1)- {- op1b = op1->Prev;- while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;- if ((op1b->Pt.Y > op1->Pt.Y) ||- !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;- };- op2b = op2->Next;- while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;- bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||- !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));- if (Reverse2)- {- op2b = op2->Prev;- while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;- if ((op2b->Pt.Y > op2->Pt.Y) ||- !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;- }-- if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||- ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;-- if (Reverse1)- {- op1b = DupOutPt(op1, false);- op2b = DupOutPt(op2, true);- op1->Prev = op2;- op2->Next = op1;- op1b->Next = op2b;- op2b->Prev = op1b;- j->OutPt1 = op1;- j->OutPt2 = op1b;- return true;- } else- {- op1b = DupOutPt(op1, true);- op2b = DupOutPt(op2, false);- op1->Next = op2;- op2->Prev = op1;- op1b->Prev = op2b;- op2b->Next = op1b;- j->OutPt1 = op1;- j->OutPt2 = op1b;- return true;- }- }- }-//------------------------------------------------------------------------ static OutRec* ParseFirstLeft(OutRec* FirstLeft)- {- while (FirstLeft && !FirstLeft->Pts)- FirstLeft = FirstLeft->FirstLeft;- return FirstLeft;- }-//-------------------------------------------------------------------------------- void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)- {- //tests if NewOutRec contains the polygon before reassigning FirstLeft- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- OutRec* outRec = m_PolyOuts[i];- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);- if (outRec->Pts && firstLeft == OldOutRec)- {- if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))- outRec->FirstLeft = NewOutRec;- }- }- }-//------------------------------------------------------------------------ void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)- {- //A polygon has split into two such that one is now the inner of the other.- //It's possible that these polygons now wrap around other polygons, so check- //every polygon that's also contained by OuterOutRec's FirstLeft container- //(including 0) to see if they've become inner to the new inner polygon ...- OutRec* orfl = OuterOutRec->FirstLeft;- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- OutRec* outRec = m_PolyOuts[i];-- if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)- continue;- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);- if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)- continue;- if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))- outRec->FirstLeft = InnerOutRec;- else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))- outRec->FirstLeft = OuterOutRec;- else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)- outRec->FirstLeft = orfl;- }- }-//----------------------------------------------------------------------- void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)- {- //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)- {- OutRec* outRec = m_PolyOuts[i];- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);- if (outRec->Pts && firstLeft == OldOutRec)- outRec->FirstLeft = NewOutRec;- }- }-//------------------------------------------------------------------------ void Clipper::JoinCommonEdges()- {- for (JoinList::size_type i = 0; i < m_Joins.size(); i++)- {- Join* join = m_Joins[i];-- OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);- OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);-- if (!outRec1->Pts || !outRec2->Pts) continue;- if (outRec1->IsOpen || outRec2->IsOpen) continue;-- //get the polygon fragment with the correct hole state (FirstLeft)- //before calling JoinPoints() ...- OutRec *holeStateRec;- if (outRec1 == outRec2) holeStateRec = outRec1;- else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;- else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;- else holeStateRec = GetLowermostRec(outRec1, outRec2);-- if (!JoinPoints(join, outRec1, outRec2)) continue;-- if (outRec1 == outRec2)- {- //instead of joining two polygons, we've just created a new one by- //splitting one polygon into two.- outRec1->Pts = join->OutPt1;- outRec1->BottomPt = 0;- outRec2 = CreateOutRec();- outRec2->Pts = join->OutPt2;-- //update all OutRec2.Pts Idx's ...- UpdateOutPtIdxs(*outRec2);-- if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))- {- //outRec1 contains outRec2 ...- outRec2->IsHole = !outRec1->IsHole;- outRec2->FirstLeft = outRec1;-- if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);-- if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))- ReversePolyPtLinks(outRec2->Pts);-- } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))- {- //outRec2 contains outRec1 ...- outRec2->IsHole = outRec1->IsHole;- outRec1->IsHole = !outRec2->IsHole;- outRec2->FirstLeft = outRec1->FirstLeft;- outRec1->FirstLeft = outRec2;-- if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);-- if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))- ReversePolyPtLinks(outRec1->Pts);- }- else- {- //the 2 polygons are completely separate ...- outRec2->IsHole = outRec1->IsHole;- outRec2->FirstLeft = outRec1->FirstLeft;-- //fixup FirstLeft pointers that may need reassigning to OutRec2- if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);- }-- } else- {- //joined 2 polygons together ...-- outRec2->Pts = 0;- outRec2->BottomPt = 0;- outRec2->Idx = outRec1->Idx;-- outRec1->IsHole = holeStateRec->IsHole;- if (holeStateRec == outRec2)- outRec1->FirstLeft = outRec2->FirstLeft;- outRec2->FirstLeft = outRec1;-- if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);- }- }- }--//-------------------------------------------------------------------------------// ClipperOffset support functions ...-//-------------------------------------------------------------------------------- DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)- {- if(pt2.X == pt1.X && pt2.Y == pt1.Y)- return DoublePoint(0, 0);-- double Dx = (double)(pt2.X - pt1.X);- double dy = (double)(pt2.Y - pt1.Y);- double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );- Dx *= f;- dy *= f;- return DoublePoint(dy, -Dx);- }--//-------------------------------------------------------------------------------// ClipperOffset class-//-------------------------------------------------------------------------------- ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)- {- this->MiterLimit = miterLimit;- this->ArcTolerance = arcTolerance;- m_lowest.X = -1;- }-//-------------------------------------------------------------------------------- ClipperOffset::~ClipperOffset()- {- Clear();- }-//-------------------------------------------------------------------------------- void ClipperOffset::Clear()- {- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)- delete m_polyNodes.Childs[i];- m_polyNodes.Childs.clear();- m_lowest.X = -1;- }-//-------------------------------------------------------------------------------- void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)- {- int highI = (int)path.size() - 1;- if (highI < 0) return;- PolyNode* newNode = new PolyNode();- newNode->m_jointype = joinType;- newNode->m_endtype = endType;-- //strip duplicate points from path and also get index to the lowest point ...- if (endType == etClosedLine || endType == etClosedPolygon)- while (highI > 0 && path[0] == path[highI]) highI--;- newNode->Contour.reserve(highI + 1);- newNode->Contour.push_back(path[0]);- int j = 0, k = 0;- for (int i = 1; i <= highI; i++)- if (newNode->Contour[j] != path[i])- {- j++;- newNode->Contour.push_back(path[i]);- if (path[i].Y > newNode->Contour[k].Y ||- (path[i].Y == newNode->Contour[k].Y &&- path[i].X < newNode->Contour[k].X)) k = j;- }- if (endType == etClosedPolygon && j < 2)- {- delete newNode;- return;- }- m_polyNodes.AddChild(*newNode);-- //if this path's lowest pt is lower than all the others then update m_lowest- if (endType != etClosedPolygon) return;- if (m_lowest.X < 0)- m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);- else- {- IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];- if (newNode->Contour[k].Y > ip.Y ||- (newNode->Contour[k].Y == ip.Y &&- newNode->Contour[k].X < ip.X))- m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);- }- }-//-------------------------------------------------------------------------------- void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)- {- for (Paths::size_type i = 0; i < paths.size(); ++i)- AddPath(paths[i], joinType, endType);- }-//-------------------------------------------------------------------------------- void ClipperOffset::FixOrientations()- {- //fixup orientations of all closed paths if the orientation of the- //closed path with the lowermost vertex is wrong ...- if (m_lowest.X >= 0 &&- !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))- {- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)- {- PolyNode& node = *m_polyNodes.Childs[i];- if (node.m_endtype == etClosedPolygon ||- (node.m_endtype == etClosedLine && Orientation(node.Contour)))- ReversePath(node.Contour);- }- } else- {- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)- {- PolyNode& node = *m_polyNodes.Childs[i];- if (node.m_endtype == etClosedLine && !Orientation(node.Contour))- ReversePath(node.Contour);- }- }- }-//-------------------------------------------------------------------------------- void ClipperOffset::Execute(Paths& solution, double delta)- {- solution.clear();- FixOrientations();- DoOffset(delta);-- //now clean up 'corners' ...- Clipper clpr;- clpr.AddPaths(m_destPolys, ptSubject, true);- if (delta > 0)- {- clpr.Execute(ctUnion, solution, pftPositive, pftPositive);- }- else- {- IntRect r = clpr.GetBounds();- Path outer(4);- outer[0] = IntPoint(r.left - 10, r.bottom + 10);- outer[1] = IntPoint(r.right + 10, r.bottom + 10);- outer[2] = IntPoint(r.right + 10, r.top - 10);- outer[3] = IntPoint(r.left - 10, r.top - 10);-- clpr.AddPath(outer, ptSubject, true);- clpr.ReverseSolution(true);- clpr.Execute(ctUnion, solution, pftNegative, pftNegative);- if (solution.size() > 0) solution.erase(solution.begin());- }- }-//-------------------------------------------------------------------------------- void ClipperOffset::Execute(PolyTree& solution, double delta)- {- solution.Clear();- FixOrientations();- DoOffset(delta);-- //now clean up 'corners' ...- Clipper clpr;- clpr.AddPaths(m_destPolys, ptSubject, true);- if (delta > 0)- {- clpr.Execute(ctUnion, solution, pftPositive, pftPositive);- }- else- {- IntRect r = clpr.GetBounds();- Path outer(4);- outer[0] = IntPoint(r.left - 10, r.bottom + 10);- outer[1] = IntPoint(r.right + 10, r.bottom + 10);- outer[2] = IntPoint(r.right + 10, r.top - 10);- outer[3] = IntPoint(r.left - 10, r.top - 10);-- clpr.AddPath(outer, ptSubject, true);- clpr.ReverseSolution(true);- clpr.Execute(ctUnion, solution, pftNegative, pftNegative);- //remove the outer PolyNode rectangle ...- if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)- {- PolyNode* outerNode = solution.Childs[0];- solution.Childs.reserve(outerNode->ChildCount());- solution.Childs[0] = outerNode->Childs[0];- solution.Childs[0]->Parent = outerNode->Parent;- for (int i = 1; i < outerNode->ChildCount(); ++i)- solution.AddChild(*outerNode->Childs[i]);- }- else- solution.Clear();- }- }-//-------------------------------------------------------------------------------- void ClipperOffset::DoOffset(double delta)- {- m_destPolys.clear();- m_delta = delta;-- //if Zero offset, just copy any CLOSED polygons to m_p and return ...- if (NEAR_ZERO(delta))- {- m_destPolys.reserve(m_polyNodes.ChildCount());- for (int i = 0; i < m_polyNodes.ChildCount(); i++)- {- PolyNode& node = *m_polyNodes.Childs[i];- if (node.m_endtype == etClosedPolygon)- m_destPolys.push_back(node.Contour);- }- return;- }-- //see offset_triginometry3.svg in the documentation folder ...- if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);- else m_miterLim = 0.5;-- double y;- if (ArcTolerance <= 0.0) y = def_arc_tolerance;- else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)- y = std::fabs(delta) * def_arc_tolerance;- else y = ArcTolerance;- //see offset_triginometry2.svg in the documentation folder ...- double steps = pi / std::acos(1 - y / std::fabs(delta));- if (steps > std::fabs(delta) * pi)- steps = std::fabs(delta) * pi; //ie excessive precision check- m_sin = std::sin(two_pi / steps);- m_cos = std::cos(two_pi / steps);- m_StepsPerRad = steps / two_pi;- if (delta < 0.0) m_sin = -m_sin;-- m_destPolys.reserve(m_polyNodes.ChildCount() * 2);- for (int i = 0; i < m_polyNodes.ChildCount(); i++)- {- PolyNode& node = *m_polyNodes.Childs[i];- m_srcPoly = node.Contour;-- int len = (int)m_srcPoly.size();- if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))- continue;-- m_destPoly.clear();- if (len == 1)- {- if (node.m_jointype == jtRound)- {- double X = 1.0, Y = 0.0;- for (cInt j = 1; j <= steps; j++)- {- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[0].X + X * delta),- Round(m_srcPoly[0].Y + Y * delta)));- double X2 = X;- X = X * m_cos - m_sin * Y;- Y = X2 * m_sin + Y * m_cos;- }- }- else- {- double X = -1.0, Y = -1.0;- for (int j = 0; j < 4; ++j)- {- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[0].X + X * delta),- Round(m_srcPoly[0].Y + Y * delta)));- if (X < 0) X = 1;- else if (Y < 0) Y = 1;- else X = -1;- }- }- m_destPolys.push_back(m_destPoly);- continue;- }- //build m_normals ...- m_normals.clear();- m_normals.reserve(len);- for (int j = 0; j < len - 1; ++j)- m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));- if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)- m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));- else- m_normals.push_back(DoublePoint(m_normals[len - 2]));-- if (node.m_endtype == etClosedPolygon)- {- int k = len - 1;- for (int j = 0; j < len; ++j)- OffsetPoint(j, k, node.m_jointype);- m_destPolys.push_back(m_destPoly);- }- else if (node.m_endtype == etClosedLine)- {- int k = len - 1;- for (int j = 0; j < len; ++j)- OffsetPoint(j, k, node.m_jointype);- m_destPolys.push_back(m_destPoly);- m_destPoly.clear();- //re-build m_normals ...- DoublePoint n = m_normals[len -1];- for (int j = len - 1; j > 0; j--)- m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);- m_normals[0] = DoublePoint(-n.X, -n.Y);- k = 0;- for (int j = len - 1; j >= 0; j--)- OffsetPoint(j, k, node.m_jointype);- m_destPolys.push_back(m_destPoly);- }- else- {- int k = 0;- for (int j = 1; j < len - 1; ++j)- OffsetPoint(j, k, node.m_jointype);-- IntPoint pt1;- if (node.m_endtype == etOpenButt)- {- int j = len - 1;- pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *- delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));- m_destPoly.push_back(pt1);- pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *- delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));- m_destPoly.push_back(pt1);- }- else- {- int j = len - 1;- k = len - 2;- m_sinA = 0;- m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);- if (node.m_endtype == etOpenSquare)- DoSquare(j, k);- else- DoRound(j, k);- }-- //re-build m_normals ...- for (int j = len - 1; j > 0; j--)- m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);- m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);-- k = len - 1;- for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);-- if (node.m_endtype == etOpenButt)- {- pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),- (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));- m_destPoly.push_back(pt1);- pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),- (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));- m_destPoly.push_back(pt1);- }- else- {- k = 1;- m_sinA = 0;- if (node.m_endtype == etOpenSquare)- DoSquare(0, 1);- else- DoRound(0, 1);- }- m_destPolys.push_back(m_destPoly);- }- }- }-//-------------------------------------------------------------------------------- void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)- {- //cross product ...- m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);- if (std::fabs(m_sinA * m_delta) < 1.0)- {- //dot product ...- double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );- if (cosA > 0) // angle => 0 degrees- {- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),- Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));- return;- }- //else angle => 180 degrees- }- else if (m_sinA > 1.0) m_sinA = 1.0;- else if (m_sinA < -1.0) m_sinA = -1.0;-- if (m_sinA * m_delta < 0)- {- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),- Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));- m_destPoly.push_back(m_srcPoly[j]);- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),- Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));- }- else- switch (jointype)- {- case jtMiter:- {- double r = 1 + (m_normals[j].X * m_normals[k].X +- m_normals[j].Y * m_normals[k].Y);- if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);- break;- }- case jtSquare: DoSquare(j, k); break;- case jtRound: DoRound(j, k); break;- }- k = j;- }-//-------------------------------------------------------------------------------- void ClipperOffset::DoSquare(int j, int k)- {- double dx = std::tan(std::atan2(m_sinA,- m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),- Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),- Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));- }-//-------------------------------------------------------------------------------- void ClipperOffset::DoMiter(int j, int k, double r)- {- double q = m_delta / r;- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),- Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));- }-//-------------------------------------------------------------------------------- void ClipperOffset::DoRound(int j, int k)- {- double a = std::atan2(m_sinA,- m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);- int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);-- double X = m_normals[k].X, Y = m_normals[k].Y, X2;- for (int i = 0; i < steps; ++i)- {- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[j].X + X * m_delta),- Round(m_srcPoly[j].Y + Y * m_delta)));- X2 = X;- X = X * m_cos - m_sin * Y;- Y = X2 * m_sin + Y * m_cos;- }- m_destPoly.push_back(IntPoint(- Round(m_srcPoly[j].X + m_normals[j].X * m_delta),- Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));- }--//-------------------------------------------------------------------------------// Miscellaneous public functions-//-------------------------------------------------------------------------------- void Clipper::DoSimplePolygons()- {- PolyOutList::size_type i = 0;- while (i < m_PolyOuts.size())- {- OutRec* outrec = m_PolyOuts[i++];- OutPt* op = outrec->Pts;- if (!op || outrec->IsOpen) continue;- do //for each Pt in Polygon until duplicate found do ...- {- OutPt* op2 = op->Next;- while (op2 != outrec->Pts)- {- if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)- {- //split the polygon into two ...- OutPt* op3 = op->Prev;- OutPt* op4 = op2->Prev;- op->Prev = op4;- op4->Next = op;- op2->Prev = op3;- op3->Next = op2;-- outrec->Pts = op;- OutRec* outrec2 = CreateOutRec();- outrec2->Pts = op2;- UpdateOutPtIdxs(*outrec2);- if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))- {- //OutRec2 is contained by OutRec1 ...- outrec2->IsHole = !outrec->IsHole;- outrec2->FirstLeft = outrec;- if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);- }- else- if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))- {- //OutRec1 is contained by OutRec2 ...- outrec2->IsHole = outrec->IsHole;- outrec->IsHole = !outrec2->IsHole;- outrec2->FirstLeft = outrec->FirstLeft;- outrec->FirstLeft = outrec2;- if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);- }- else- {- //the 2 polygons are separate ...- outrec2->IsHole = outrec->IsHole;- outrec2->FirstLeft = outrec->FirstLeft;- if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);- }- op2 = op; //ie get ready for the Next iteration- }- op2 = op2->Next;- }- op = op->Next;- }- while (op != outrec->Pts);- }- }-//-------------------------------------------------------------------------------- void ReversePath(Path& p)- {- std::reverse(p.begin(), p.end());- }-//-------------------------------------------------------------------------------- void ReversePaths(Paths& p)- {- for (Paths::size_type i = 0; i < p.size(); ++i)- ReversePath(p[i]);- }-//-------------------------------------------------------------------------------- void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)- {- Clipper c;- c.StrictlySimple(true);- c.AddPath(in_poly, ptSubject, true);- c.Execute(ctUnion, out_polys, fillType, fillType);- }-//-------------------------------------------------------------------------------- void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)- {- Clipper c;- c.StrictlySimple(true);- c.AddPaths(in_polys, ptSubject, true);- c.Execute(ctUnion, out_polys, fillType, fillType);- }-//-------------------------------------------------------------------------------- void SimplifyPolygons(Paths &polys, PolyFillType fillType)- {- SimplifyPolygons(polys, polys, fillType);- }-//-------------------------------------------------------------------------------- inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)- {- double Dx = ((double)pt1.X - pt2.X);- double dy = ((double)pt1.Y - pt2.Y);- return (Dx*Dx + dy*dy);- }-//-------------------------------------------------------------------------------- double DistanceFromLineSqrd(- const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)- {- //The equation of a line in general form (Ax + By + C = 0)- //given 2 points (x?y? & (x?y? is ...- //(y?- y?x + (x?- x?y + (y?- y?x?- (x?- x?y?= 0- //A = (y?- y?; B = (x?- x?; C = (y?- y?x?- (x?- x?y?- //perpendicular distance of point (x?y? = (Ax?+ By?+ C)/Sqrt(A?+ B?- //see http://en.wikipedia.org/wiki/Perpendicular_distance- double A = double(ln1.Y - ln2.Y);- double B = double(ln2.X - ln1.X);- double C = A * ln1.X + B * ln1.Y;- C = A * pt.X + B * pt.Y - C;- return (C * C) / (A * A + B * B);- }-//----------------------------------------------------------------------------- bool SlopesNearCollinear(const IntPoint& pt1,- const IntPoint& pt2, const IntPoint& pt3, double distSqrd)- {- //this function is more accurate when the point that's geometrically- //between the other 2 points is the one that's tested for distance.- //ie makes it more likely to pick up 'spikes' ...- if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))- {- if ((pt1.X > pt2.X) == (pt1.X < pt3.X))- return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;- else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))- return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;- else- return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;- }- else- {- if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))- return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;- else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))- return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;- else- return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;- }- }-//-------------------------------------------------------------------------------- bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)- {- double Dx = (double)pt1.X - pt2.X;- double dy = (double)pt1.Y - pt2.Y;- return ((Dx * Dx) + (dy * dy) <= distSqrd);- }-//-------------------------------------------------------------------------------- OutPt* ExcludeOp(OutPt* op)- {- OutPt* result = op->Prev;- result->Next = op->Next;- op->Next->Prev = result;- result->Idx = 0;- return result;- }-//-------------------------------------------------------------------------------- void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)- {- //distance = proximity in units/pixels below which vertices- //will be stripped. Default ~= sqrt(2).-- size_t size = in_poly.size();-- if (size == 0)- {- out_poly.clear();- return;- }-- OutPt* outPts = new OutPt[size];- for (size_t i = 0; i < size; ++i)- {- outPts[i].Pt = in_poly[i];- outPts[i].Next = &outPts[(i + 1) % size];- outPts[i].Next->Prev = &outPts[i];- outPts[i].Idx = 0;- }-- double distSqrd = distance * distance;- OutPt* op = &outPts[0];- while (op->Idx == 0 && op->Next != op->Prev)- {- if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))- {- op = ExcludeOp(op);- size--;- }- else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))- {- ExcludeOp(op->Next);- op = ExcludeOp(op);- size -= 2;- }- else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))- {- op = ExcludeOp(op);- size--;- }- else- {- op->Idx = 1;- op = op->Next;- }- }-- if (size < 3) size = 0;- out_poly.resize(size);- for (size_t i = 0; i < size; ++i)- {- out_poly[i] = op->Pt;- op = op->Next;- }- delete [] outPts;- }-//-------------------------------------------------------------------------------- void CleanPolygon(Path& poly, double distance)- {- CleanPolygon(poly, poly, distance);- }-//-------------------------------------------------------------------------------- void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)- {- out_polys.resize(in_polys.size());- for (Paths::size_type i = 0; i < in_polys.size(); ++i)- CleanPolygon(in_polys[i], out_polys[i], distance);- }-//-------------------------------------------------------------------------------- void CleanPolygons(Paths& polys, double distance)- {- CleanPolygons(polys, polys, distance);- }-//-------------------------------------------------------------------------------- void Minkowski(const Path& poly, const Path& path,- Paths& solution, bool isSum, bool isClosed)- {- int delta = (isClosed ? 1 : 0);- size_t polyCnt = poly.size();- size_t pathCnt = path.size();- Paths pp;- pp.reserve(pathCnt);- if (isSum)- for (size_t i = 0; i < pathCnt; ++i)- {- Path p;- p.reserve(polyCnt);- for (size_t j = 0; j < poly.size(); ++j)- p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));- pp.push_back(p);- }- else- for (size_t i = 0; i < pathCnt; ++i)- {- Path p;- p.reserve(polyCnt);- for (size_t j = 0; j < poly.size(); ++j)- p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));- pp.push_back(p);- }-- solution.clear();- solution.reserve((pathCnt + delta) * (polyCnt + 1));- for (size_t i = 0; i < pathCnt - 1 + delta; ++i)- for (size_t j = 0; j < polyCnt; ++j)- {- Path quad;- quad.reserve(4);- quad.push_back(pp[i % pathCnt][j % polyCnt]);- quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);- quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);- quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);- if (!Orientation(quad)) ReversePath(quad);- solution.push_back(quad);- }- }-//-------------------------------------------------------------------------------- void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)- {- Minkowski(pattern, path, solution, true, pathIsClosed);- Clipper c;- c.AddPaths(solution, ptSubject, true);- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);- }-//-------------------------------------------------------------------------------- void TranslatePath(const Path& input, Path& output, const IntPoint delta)- {- //precondition: input != output- output.resize(input.size());- for (size_t i = 0; i < input.size(); ++i)- output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);- }-//-------------------------------------------------------------------------------- void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)- {- Clipper c;- for (size_t i = 0; i < paths.size(); ++i)- {- Paths tmp;- Minkowski(pattern, paths[i], tmp, true, pathIsClosed);- c.AddPaths(tmp, ptSubject, true);- if (pathIsClosed)- {- Path tmp2;- TranslatePath(paths[i], tmp2, pattern[0]);- c.AddPath(tmp2, ptClip, true);- }- }- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);- }-//-------------------------------------------------------------------------------- void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)- {- Minkowski(poly1, poly2, solution, false, true);- Clipper c;- c.AddPaths(solution, ptSubject, true);- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);- }-//-------------------------------------------------------------------------------- enum NodeType {ntAny, ntOpen, ntClosed};-- void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)- {- bool match = true;- if (nodetype == ntClosed) match = !polynode.IsOpen();- else if (nodetype == ntOpen) return;-- if (!polynode.Contour.empty() && match)- paths.push_back(polynode.Contour);- for (int i = 0; i < polynode.ChildCount(); ++i)- AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);- }-//-------------------------------------------------------------------------------- void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)- {- paths.resize(0);- paths.reserve(polytree.Total());- AddPolyNodeToPaths(polytree, ntAny, paths);- }-//-------------------------------------------------------------------------------- void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)- {- paths.resize(0);- paths.reserve(polytree.Total());- AddPolyNodeToPaths(polytree, ntClosed, paths);- }-//-------------------------------------------------------------------------------- void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)- {- paths.resize(0);- paths.reserve(polytree.Total());- //Open paths are top level only, so ...- for (int i = 0; i < polytree.ChildCount(); ++i)- if (polytree.Childs[i]->IsOpen())- paths.push_back(polytree.Childs[i]->Contour);- }-//-------------------------------------------------------------------------------- std::ostream& operator <<(std::ostream &s, const IntPoint &p)- {- s << "(" << p.X << "," << p.Y << ")";- return s;- }-//-------------------------------------------------------------------------------- std::ostream& operator <<(std::ostream &s, const Path &p)- {- if (p.empty()) return s;- Path::size_type last = p.size() -1;- for (Path::size_type i = 0; i < last; i++)- s << "(" << p[i].X << "," << p[i].Y << "), ";- s << "(" << p[last].X << "," << p[last].Y << ")\n";- return s;- }-//-------------------------------------------------------------------------------- std::ostream& operator <<(std::ostream &s, const Paths &p)- {- for (Paths::size_type i = 0; i < p.size(); i++)- s << p[i];- s << "\n";- return s;- }-//--------------------------------------------------------------------------------} //ClipperLib namespacediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/main.cpp b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/main.cppdeleted file mode 100755index 8427e74..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/cpp/src/main.cpp+++ /dev/null@@ -1,113 +0,0 @@-#include "OcrResultUtils.h"-#include "BitmapUtils.h"-#include "OcrLite.h"-#include "OcrUtils.h"-#include "omp.h"--static OcrLite *ocrLite;--JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {- ocrLite = new OcrLite();- return JNI_VERSION_1_4;-}--JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) {- LOGI("Goodbye OcrLite!");- delete ocrLite;-}--extern "C" JNIEXPORT jboolean JNICALL-Java_com_benjaminwan_ocrlibrary_OcrEngine_init(JNIEnv *env, jobject thiz, jobject assetManager,- jint numThread, jstring detName, jstring clsName,- jstring recName, jstring keysName) {- std::string modelDetName = jstringTostring(env, detName);- std::string modelClsName = jstringTostring(env, clsName);- std::string modelRecName = jstringTostring(env, recName);- std::string modelKeysName = jstringTostring(env, keysName);- ocrLite->init(env, assetManager, numThread, modelDetName, modelClsName, modelRecName, modelKeysName);- omp_set_num_threads(numThread);- //ocrLite->initLogger(false);- return JNI_TRUE;-}--cv::Mat makePadding(cv::Mat &src, const int padding) {- if (padding <= 0) return src;- cv::Scalar paddingScalar = {255, 255, 255};- cv::Mat paddingSrc;- cv::copyMakeBorder(src, paddingSrc, padding, padding, padding, padding, cv::BORDER_ISOLATED,- paddingScalar);- return paddingSrc;-}--extern "C"-JNIEXPORT jobject JNICALL-Java_com_benjaminwan_ocrlibrary_OcrEngine_detect(JNIEnv *env, jobject thiz, jobject input, jobject output,- jint padding, jint maxSideLen, jfloat boxScoreThresh, jfloat boxThresh,- jfloat unClipRatio, jboolean doAngle, jboolean mostAngle) {- Logger("padding(%d),maxSideLen(%d),boxScoreThresh(%f),boxThresh(%f),unClipRatio(%f),doAngle(%d),mostAngle(%d)",- padding, maxSideLen, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle);- cv::Mat imgRGBA, imgBGR, imgOut;- bitmapToMat(env, input, imgRGBA);- cv::cvtColor(imgRGBA, imgBGR, cv::COLOR_RGBA2BGR);- int originMaxSide = (std::max)(imgBGR.cols, imgBGR.rows);- int resize;- if (maxSideLen <= 0 || maxSideLen > originMaxSide) {- resize = originMaxSide;- } else {- resize = maxSideLen;- }- resize += 2*padding;- cv::Rect paddingRect(padding, padding, imgBGR.cols, imgBGR.rows);- cv::Mat paddingSrc = makePadding(imgBGR, padding);- //按比例缩小图像,减少文字分割时间- ScaleParam s = getScaleParam(paddingSrc, resize);//例:按长或宽缩放 src.cols=不缩放,src.cols/2=长度缩小一半- OcrResult ocrResult = ocrLite->detect(paddingSrc, paddingRect, s, boxScoreThresh, boxThresh,- unClipRatio, doAngle, mostAngle);-- cv::cvtColor(ocrResult.boxImg, imgOut, cv::COLOR_BGR2RGBA);- matToBitmap(env, imgOut, output);-- return OcrResultUtils(env, ocrResult, output).getJObject();-}--extern "C" JNIEXPORT jdouble JNICALL-Java_com_benjaminwan_ocrlibrary_OcrEngine_benchmark(JNIEnv *env, jobject thiz, jobject input,- jint loop) {- int padding = 50;- int paddingRect= 0;- float boxScoreThresh = 0.6;- float boxThresh = 0.3;- float unClipRatio = 2.0;- bool doAngle = true;- bool mostAngle = true;- LOGI("padding(%d),paddingRect(%d),boxScoreThresh(%f),boxThresh(%f),unClipRatio(%f),doAngle(%d),mostAngle(%d)",- padding, paddingRect, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle);- cv::Mat imgRGBA, imgBGR, imgOut;- bitmapToMat(env, input, imgRGBA);- cv::cvtColor(imgRGBA, imgBGR, cv::COLOR_RGBA2BGR);- cv::Rect originRect(padding, padding, imgBGR.cols, imgBGR.rows);- cv::Mat src = makePadding(imgBGR, padding);- //按比例缩小图像,减少文字分割时间- ScaleParam s = getScaleParam(src, src.cols);//例:按长或宽缩放 src.cols=不缩放,src.cols/2=长度缩小一半-- LOGI("=====warmup=====");- OcrResult result = ocrLite->detect(src, originRect, s, boxScoreThresh, boxThresh,- unClipRatio, doAngle, mostAngle);- LOGI("dbNetTime(%f) detectTime(%f)\n", result.dbNetTime, result.detectTime);- double dbTime = 0.0f;- double detectTime = 0.0f;- int loopCount = loop;- for (int i = 0; i < loopCount; ++i) {- LOGI("=====loop:%d=====", i + 1);- OcrResult ocrResult = ocrLite->detect(src, originRect, s, boxScoreThresh, boxThresh,- unClipRatio, doAngle, mostAngle);- LOGI("dbNetTime(%f) detectTime(%f)\n", ocrResult.dbNetTime, ocrResult.detectTime);- dbTime += ocrResult.dbNetTime;- detectTime += ocrResult.detectTime;- }- LOGI("=====result=====\n");- double averageTime = detectTime / loopCount;- LOGI("average dbNetTime=%fms, average detectTime=%fms\n", dbTime / loopCount,- averageTime);- return (jdouble) averageTime;-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrEngine.kt b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrEngine.ktdeleted file mode 100755index c345314..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrEngine.kt+++ /dev/null@@ -1,52 +0,0 @@-package com.benjaminwan.ocrlibrary--import android.content.Context-import android.content.res.AssetManager-import android.graphics.Bitmap--class OcrEngine(context: Context) {- companion object {- const val numThread: Int = 4- }-- init {- System.loadLibrary("BaiPiaoOcr")- val ret = init(- context.assets, numThread,- "ch_ppocr_mobile_v2.0_det_infer.onnx",- "ch_ppocr_mobile_v2.0_cls_infer.onnx",- "ch_ppocr_mobile_v2.0_rec_infer.onnx",- "ppocr_keys_v1.txt"- )- if (!ret) throw IllegalArgumentException()- }-- var padding: Int = 0- var boxScoreThresh: Float = 0.5f- var boxThresh: Float = 0.3f- var unClipRatio: Float = 2.0f- var doAngle: Boolean = true- var mostAngle: Boolean = true-- fun detect(input: Bitmap, output: Bitmap, maxSideLen: Int) =- detect(- input, output, padding, maxSideLen,- boxScoreThresh, boxThresh,- unClipRatio, doAngle, mostAngle- )-- external fun init(- assetManager: AssetManager,- numThread: Int, detName: String,- clsName: String, recName: String, keysName: String- ): Boolean-- external fun detect(- input: Bitmap, output: Bitmap, padding: Int, maxSideLen: Int,- boxScoreThresh: Float, boxThresh: Float,- unClipRatio: Float, doAngle: Boolean, mostAngle: Boolean- ): OcrResult-- external fun benchmark(input: Bitmap, loop: Int): Double--}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrResult.kt b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrResult.ktdeleted file mode 100755index 46dc74c..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrResult.kt+++ /dev/null@@ -1,62 +0,0 @@-package com.benjaminwan.ocrlibrary--import android.graphics.Bitmap-import android.os.Parcelable-import kotlinx.android.parcel.Parcelize--open class OcrOutput--object OcrStop : OcrOutput()-object OcrFailed : OcrOutput()--@Parcelize-data class OcrResult(- val dbNetTime: Double,- val textBlocks: ArrayList<TextBlock>,- var boxImg: Bitmap,- var detectTime: Double,- var strRes: String-) : Parcelable, OcrOutput()--@Parcelize-data class Point(var x: Int, var y: Int) : Parcelable--@Parcelize-data class TextBlock(- val boxPoint: ArrayList<Point>, var boxScore: Float,- val angleIndex: Int, val angleScore: Float, val angleTime: Double,- val text: String, val charScores: FloatArray, val crnnTime: Double,- val blockTime: Double-) : Parcelable {- override fun equals(other: Any?): Boolean {- if (this === other) return true- if (javaClass != other?.javaClass) return false-- other as TextBlock-- if (boxPoint != other.boxPoint) return false- if (boxScore != other.boxScore) return false- if (angleIndex != other.angleIndex) return false- if (angleScore != other.angleScore) return false- if (angleTime != other.angleTime) return false- if (text != other.text) return false- if (!charScores.contentEquals(other.charScores)) return false- if (crnnTime != other.crnnTime) return false- if (blockTime != other.blockTime) return false-- return true- }-- override fun hashCode(): Int {- var result = boxPoint.hashCode()- result = 31 * result + boxScore.hashCode()- result = 31 * result + angleIndex- result = 31 * result + angleScore.hashCode()- result = 31 * result + angleTime.hashCode()- result = 31 * result + text.hashCode()- result = 31 * result + charScores.contentHashCode()- result = 31 * result + crnnTime.hashCode()- result = 31 * result + blockTime.hashCode()- return result- }-}diff --git a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/test/java/com/benjaminwan/ocrlibrary/ExampleUnitTest.kt b/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/test/java/com/benjaminwan/ocrlibrary/ExampleUnitTest.ktdeleted file mode 100755index 9871f20..0000000--- a/android/BaiPiaoOcrAndroidOnnx/OcrLibrary/src/test/java/com/benjaminwan/ocrlibrary/ExampleUnitTest.kt+++ /dev/null@@ -1,17 +0,0 @@-package com.benjaminwan.ocrlibrary--import org.junit.Test--import org.junit.Assert.*--/**- * Example local unit test, which will execute on the development machine (host).- *- * See [testing documentation](http://d.android.com/tools/testing).- */-class ExampleUnitTest {- @Test- fun addition_isCorrect() {- assertEquals(4, 2 + 2)- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/README.md b/android/BaiPiaoOcrAndroidOnnx/README.mddeleted file mode 100755index 1065ab3..0000000--- a/android/BaiPiaoOcrAndroidOnnx/README.md+++ /dev/null@@ -1,118 +0,0 @@-# BaiPiaoOcrAndroidOnnx--### Project下载--* 有整合好源码和依赖库的完整工程项目,文件比较大,可到Q群共享内下载,找以Project开头的压缩包文件-* 如果想自己折腾,则请继续阅读本说明--### Demo APK下载--编译好的demo文件比较大,可以到Q群共享内下载--### 介绍--白富美OCR onnxruntime推理 for Android--onnxruntime框架[https://github.com/microsoft/onnxruntime](https://github.com/microsoft/onnxruntime)--### 关于模型:--* det模型用于分割文字块,有两种模型(server和mobile),其中server体积大且较慢但效果好,mobile体积小且较快但效果差点。-* cls模型用于检测文字方向,只有一种模型-* rec模型用于文字识别,有两种模型(server和mobile),其中server体积大且较慢但效果好,mobile体积小且较快但效果差点。--### 模型下载--* [模型下载地址](https://github.com/znsoftm/BaiPiaoOCR/tree/main/models)-也可以到Q群共享内下载,下载后解压到如下目录。 目前det模型有2种,如果想让apk体积小,那么就选mobile模型即可-```-BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/assets- ├── ch_ppocr_mobile_v2.0_cls_infer.onnx- ├── ch_ppocr_mobile_v2.0_det_infer.onnx det二选一- ├── ch_ppocr_server_v2.0_det_infer.onnx det二选一- ├── ch_ppocr_mobile_v2.0_rec_infer.onnx rec二选一- ├── ch_ppocr_server_v2.0_rec_infer.onnx rec二选一- └── ppocr_keys_v1.txt-```-* 代码中配置使用哪个模型-BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/java/com/benjaminwan/ocrlibrary/OcrEngine.kt,在init方法中配置:-```kotlin-val ret = init(- context.assets, numThread,- "ch_ppocr_mobile_v2.0_det_infer.onnx",- "ch_ppocr_mobile_v2.0_cls_infer.onnx",- "ch_ppocr_mobile_v2.0_rec_infer.onnx",- "ppocr_keys_v1.txt"- )-```--### 总体说明--1. 封装为独立的Library。-2. Native层以C++编写。-3. demo app以Kotlin-JVM编写。-4. Android版与其它版本不同,包含了几个应用场景,包括相册识别、摄像头识别、手机IMEI号识别、摄像头身份证识别这几个功能页面。-5. 自己编译的opencv 3.4.10,并精简了不需要的模块,减小apk体积。-6. onnxruntime动态库为自己编译的1.6.0版--### 编译说明--1. AndroidStudio 4.1.2或以上-2. NDK-3. cmake 3.4.1或以上-4. 下载opencv-3.4.10-android-sdk-static-lite.7z,[下载地址](https://gitee.com/benjaminwan/ocr-lite-android-onnx/releases/v1.0.0.20201022)-解压后目录结构为--```-BaiPiaoOcrAndroidOnnx/OcrLibrary/src/sdk- └── native- ├── 3rdparty- ├── jni- └── staticlibs-```--5. 下载onnxruntime-1.6.0-android.7z,[下载地址](https://gitee.com/benjaminwan/ocr-lite-android-onnx/releases/v1.0.0.20201022)--```-BaiPiaoOcrAndroidOnnx/OcrLibrary/src/main/onnx-├── ONNXConfig.cmake-├── arm64-v8a-│ └── libonnxruntime.so-├── armeabi-v7a-│ └── libonnxruntime.so-├── include-├── x86-│ └── libonnxruntime.so-└── x86_64- └── libonnxruntime.so-```--6. 如果想让apk体积进一步缩小,可以修改BaiPiaoOcrAndroidOnnx/OcrLibrary/build.gradle-注释掉x86_64和x86,这两个一般用于模拟器。-```groovy-externalNativeBuild {- cmake {- abiFilters 'armeabi-v7a', 'arm64-v8a'//, 'x86_64', 'x86'- }-}-```--### 输入参数说明--请参考[C++项目](https://github.com/znsoftm/BaiPiaoOCR/tree/main/cpp/BaiPiaoOcrOnnx)--### 删除缓存,重新编译--删除项目根目录下的如下文件夹--```-.idea-build-app/build-OcrLibrary/.cxx-OcrLibrary/build-```--### 编译Release包--使用命令编译```./gradlew assembleRelease```diff --git a/android/BaiPiaoOcrAndroidOnnx/app/.gitignore b/android/BaiPiaoOcrAndroidOnnx/app/.gitignoredeleted file mode 100755index 42afabf..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/.gitignore+++ /dev/null@@ -1 +0,0 @@-/build\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/build.gradle b/android/BaiPiaoOcrAndroidOnnx/app/build.gradledeleted file mode 100755index 4178ec9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/build.gradle+++ /dev/null@@ -1,114 +0,0 @@-apply plugin: 'com.android.application'-apply plugin: 'kotlin-android'-apply plugin: 'kotlin-android-extensions'-apply plugin: 'kotlin-kapt'--android {- signingConfigs {- ocr {- keyAlias 'baipiao'- keyPassword 'baipiao'- storeFile file('../keystore/baipiao.keystore')- storePassword 'baipiao'- }- }-- compileSdkVersion 30- buildToolsVersion "30.0.2"-- defaultConfig {- applicationId "com.benjaminwan.ocr.onnx"- minSdkVersion 21- targetSdkVersion 30- versionCode 2- versionName "1.0.1"- signingConfig signingConfigs.ocr- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"- }-- buildTypes {- release {- minifyEnabled false- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'- }- }-- compileOptions {- sourceCompatibility JavaVersion.VERSION_1_8- targetCompatibility JavaVersion.VERSION_1_8- }-- kotlinOptions {- jvmTarget = JavaVersion.VERSION_1_8.toString()- }-- kapt {- correctErrorTypes = true- }-- applicationVariants.all {- variant ->- variant.outputs.all {- outputFileName = "${rootProject.name}-${defaultConfig.versionName}-${variant.buildType.name}.apk"- }- }-}--repositories {- flatDir {- dirs '../common-aar', 'libs'- }-}--dependencies {- implementation fileTree(dir: "libs", include: ["*.jar"])- testImplementation 'junit:junit:4.12'- androidTestImplementation 'androidx.test.ext:junit:1.1.2'- androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'- //Kotlin- implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"- //Android- implementation 'androidx.core:core-ktx:1.3.2'- implementation 'androidx.appcompat:appcompat:1.2.0'- implementation 'androidx.constraintlayout:constraintlayout:2.0.1'- implementation 'androidx.recyclerview:recyclerview:1.1.0'-- //glide- implementation 'com.github.bumptech.glide:glide:4.11.0'- implementation project(":OcrLibrary")-- def autodispose_version = '1.3.0'- //AutoDispose 配合Rx实现生命周期管理- implementation "com.uber.autodispose:autodispose:$autodispose_version"- implementation "com.uber.autodispose:autodispose-lifecycle:$autodispose_version"- implementation "com.uber.autodispose:autodispose-android:$autodispose_version"- implementation "com.uber.autodispose:autodispose-android-archcomponents:$autodispose_version"-- implementation 'com.github.chrisbanes:PhotoView:2.3.0'-- def epoxyVersion = '4.1.0'- implementation "com.airbnb.android:epoxy:$epoxyVersion"- kapt "com.airbnb.android:epoxy-processor:$epoxyVersion"-- // CameraX core library- def camerax_version = '1.0.0-beta11'- implementation "androidx.camera:camera-core:$camerax_version"- // CameraX Camera2 extensions- implementation "androidx.camera:camera-camera2:$camerax_version"- // CameraX Lifecycle library- implementation "androidx.camera:camera-lifecycle:$camerax_version"- // CameraX View class- implementation 'androidx.camera:camera-view:1.0.0-alpha18'-- //cameraMask 相机遮罩- implementation 'jsc.kit.cameramask:camera-mask:0.3.0'-- //runWithPermissions 申请权限- implementation 'com.afollestad.assent:core:3.0.0-RC4'- implementation 'com.afollestad.assent:rationales:3.0.0-RC4'-- //Logger- implementation 'com.orhanobut:logger:2.2.0'-- implementation(name: 'IdCardView-1.0', ext: 'aar')-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/proguard-rules.pro b/android/BaiPiaoOcrAndroidOnnx/app/proguard-rules.prodeleted file mode 100755index 481bb43..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/proguard-rules.pro+++ /dev/null@@ -1,21 +0,0 @@-# Add project specific ProGuard rules here.-# You can control the set of applied configuration files using the-# proguardFiles setting in build.gradle.-#-# For more details, see-# http://developer.android.com/guide/developing/tools/proguard.html--# If your project uses WebView with JS, uncomment the following-# and specify the fully qualified class name to the JavaScript interface-# class:-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {-# public *;-#}--# Uncomment this to preserve the line number information for-# debugging stack traces.-#-keepattributes SourceFile,LineNumberTable--# If you keep the line number information, uncomment this to-# hide the original source file name.-#-renamesourcefileattribute SourceFile\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/androidTest/java/com/benjaminwan/ocr/onnx/ExampleInstrumentedTest.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/androidTest/java/com/benjaminwan/ocr/onnx/ExampleInstrumentedTest.ktdeleted file mode 100755index 56d305f..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/androidTest/java/com/benjaminwan/ocr/onnx/ExampleInstrumentedTest.kt+++ /dev/null@@ -1,24 +0,0 @@-package com.benjaminwan.ocr.onnx--import androidx.test.platform.app.InstrumentationRegistry-import androidx.test.ext.junit.runners.AndroidJUnit4--import org.junit.Test-import org.junit.runner.RunWith--import org.junit.Assert.*--/**- * Instrumented test, which will execute on an Android device.- *- * See [testing documentation](http://d.android.com/tools/testing).- */-@RunWith(AndroidJUnit4::class)-class ExampleInstrumentedTest {- @Test- fun useAppContext() {- // Context of the app under test.- val appContext = InstrumentationRegistry.getInstrumentation().targetContext- assertEquals("com.benjaminwan.ocr.onnx", appContext.packageName)- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/AndroidManifest.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/AndroidManifest.xmldeleted file mode 100755index d9033b6..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/AndroidManifest.xml+++ /dev/null@@ -1,42 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android"- package="com.benjaminwan.ocr.onnx">-- <uses-permission android:name="android.permission.CAMERA"/>- <uses-permission android:name="android.permission.VIBRATE"/>-- <application- android:name=".app.App"- android:allowBackup="true"- android:icon="@drawable/ic_ocr"- android:label="@string/app_name"- android:roundIcon="@drawable/ic_ocr"- android:supportsRtl="true"- android:theme="@style/AppTheme">- <activity- android:name=".MainActivity"- android:screenOrientation="portrait">- <intent-filter>- <action android:name="android.intent.action.MAIN" />-- <category android:name="android.intent.category.LAUNCHER" />- </intent-filter>- </activity>- <activity- android:name=".GalleryActivity"- android:screenOrientation="portrait" />- <activity- android:name=".CameraActivity"- android:screenOrientation="portrait" />- <activity- android:name=".ImeiActivity"- android:screenOrientation="portrait" />- <activity- android:name=".PlateActivity"- android:screenOrientation="portrait" />- <activity- android:name=".IdCardFrontActivity"- android:screenOrientation="portrait" />- </application>--</manifest>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/CameraActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/CameraActivity.ktdeleted file mode 100755index e53ca21..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/CameraActivity.kt+++ /dev/null@@ -1,259 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.graphics.Bitmap-import android.os.Bundle-import android.view.View-import android.widget.SeekBar-import androidx.appcompat.app.AppCompatActivity-import androidx.camera.core.*-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.view.PreviewView-import androidx.core.content.ContextCompat-import com.afollestad.assent.Permission-import com.afollestad.assent.askForPermissions-import com.afollestad.assent.isAllGranted-import com.afollestad.assent.rationale.createDialogRationale-import com.benjaminwan.ocr.onnx.app.App-import com.benjaminwan.ocr.onnx.dialog.DebugDialog-import com.benjaminwan.ocr.onnx.dialog.TextResultDialog-import com.benjaminwan.ocr.onnx.utils.showToast-import com.benjaminwan.ocrlibrary.OcrResult-import com.bumptech.glide.Glide-import com.orhanobut.logger.Logger-import com.uber.autodispose.android.lifecycle.autoDisposable-import io.reactivex.Single-import io.reactivex.android.schedulers.AndroidSchedulers-import io.reactivex.schedulers.Schedulers-import kotlinx.android.synthetic.main.activity_camera.*-import kotlin.math.max--class CameraActivity : AppCompatActivity(), View.OnClickListener, SeekBar.OnSeekBarChangeListener {-- private var ocrResult: OcrResult? = null-- private var preview: Preview? = null- private var imageCapture: ImageCapture? = null- private var camera: Camera? = null- private lateinit var viewFinder: PreviewView-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- setContentView(R.layout.activity_camera)- App.ocrEngine.doAngle = false//摄像头一般不需要考虑倒过来的情况- clearBtn.setOnClickListener(this)- detectBtn.setOnClickListener(this)- resultBtn.setOnClickListener(this)- debugBtn.setOnClickListener(this)- updatePadding(App.ocrEngine.padding)- updateBoxScoreThresh((App.ocrEngine.boxScoreThresh * 100).toInt())- updateBoxThresh((App.ocrEngine.boxThresh * 100).toInt())- updateUnClipRatio((App.ocrEngine.unClipRatio * 10).toInt())- paddingSeekBar.setOnSeekBarChangeListener(this)- boxScoreThreshSeekBar.setOnSeekBarChangeListener(this)- boxThreshSeekBar.setOnSeekBarChangeListener(this)- maxSideLenSeekBar.setOnSeekBarChangeListener(this)- scaleUnClipRatioSeekBar.setOnSeekBarChangeListener(this)- viewFinder = findViewById(R.id.viewFinder)- cameraLensView.postDelayed({- updateMaxSideLen(100)- }, 500)- }-- override fun onResume() {- super.onResume()- val rationaleHandler = createDialogRationale(R.string.app_permission) {- onPermission(- Permission.CAMERA, "请点击允许"- )- }-- if (!isAllGranted(Permission.CAMERA)) {- askForPermissions(- Permission.CAMERA,- rationaleHandler = rationaleHandler- ) { result ->- val permissionGranted: Boolean =- result.isAllGranted(- Permission.CAMERA- )- if (!permissionGranted) {- showToast("未获取权限,应用无法正常使用!")- } else {- startCamera()- }- }- } else {- startCamera()- }- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.clearBtn -> {- clearLastResult()- }- R.id.detectBtn -> {- val width = cameraLensView.measuredWidth * 9 / 10- val height = cameraLensView.measuredHeight * 9 / 10- val ratio = maxSideLenSeekBar.progress.toFloat() / 100.toFloat()- val maxSize = max(width, height)- val maxSideLen = (ratio * maxSize).toInt()- detect(maxSideLen)- }- R.id.resultBtn -> {- val result = ocrResult ?: return- TextResultDialog.instance- .setTitle("识别结果")- .setContent(result.strRes)- .show(supportFragmentManager, "TextResultDialog")- }- R.id.debugBtn -> {- val result = ocrResult ?: return- DebugDialog.instance- .setTitle("调试信息")- .setResult(result)- .show(supportFragmentManager, "DebugDialog")- }- else -> {- }- }- }-- override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {- seekBar ?: return- when (seekBar.id) {- R.id.maxSideLenSeekBar -> {- updateMaxSideLen(progress)- }- R.id.paddingSeekBar -> {- updatePadding(progress)- }- R.id.boxScoreThreshSeekBar -> {- updateBoxScoreThresh(progress)- }- R.id.boxThreshSeekBar -> {- updateBoxThresh(progress)- }- R.id.scaleUnClipRatioSeekBar -> {- updateUnClipRatio(progress)- }- else -> {- }- }- }-- override fun onStartTrackingTouch(seekBar: SeekBar?) {- }-- override fun onStopTrackingTouch(seekBar: SeekBar?) {- }-- private fun updateMaxSideLen(progress: Int) {- val width = cameraLensView.measuredWidth * 9 / 10- val height = cameraLensView.measuredHeight * 9 / 10- val ratio = progress.toFloat() / 100.toFloat()- val maxSize = max(width, height)- val maxSideLen = (ratio * maxSize).toInt()- Logger.i("======$width,$height,$ratio,$maxSize,$maxSideLen")- maxSideLenTv.text = "MaxSideLen:$maxSideLen(${ratio * 100}%)"- }-- private fun updatePadding(progress: Int) {- paddingTv.text = "Padding:$progress"- App.ocrEngine.padding = progress- }-- private fun updateBoxScoreThresh(progress: Int) {- val thresh = progress.toFloat() / 100.toFloat()- boxScoreThreshTv.text = "${getString(R.string.box_score_thresh)}:$thresh"- App.ocrEngine.boxScoreThresh = thresh- }-- private fun updateBoxThresh(progress: Int) {- val thresh = progress.toFloat() / 100.toFloat()- boxThreshTv.text = "BoxThresh:$thresh"- App.ocrEngine.boxThresh = thresh- }-- private fun updateUnClipRatio(progress: Int) {- val scale = progress.toFloat() / 10.toFloat()- unClipRatioTv.text = "${getString(R.string.box_un_clip_ratio)}:$scale"- App.ocrEngine.unClipRatio = scale- }-- private fun showLoading() {- loadingImg.visibility = View.VISIBLE- Glide.with(this).load(R.drawable.loading_anim).into(loadingImg)- }-- private fun hideLoading() {- loadingImg.visibility = View.GONE- }-- private fun clearLastResult() {- cameraLensView.cameraLensBitmap = null- timeTV.text = ""- ocrResult = null- }-- private fun detect(reSize: Int) {- Single.fromCallable {- val src = cameraLensView.cropCameraLensRectBitmap(viewFinder.bitmap, false)- val boxImg: Bitmap = Bitmap.createBitmap(- src.width, src.height, Bitmap.Config.ARGB_8888- )- Logger.i("selectedImg=${src.height},${src.width} ${src.config}")- App.ocrEngine.detect(src, boxImg, reSize)- }.subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .doOnSubscribe { showLoading() }- .doFinally { hideLoading() }- .autoDisposable(this)- .subscribe { t1, t2 ->- ocrResult = t1- timeTV.text = "识别时间:${t1.detectTime.toInt()}ms"- cameraLensView.cameraLensBitmap = t1.boxImg- }- }-- private fun startCamera() {- val cameraProviderFuture = ProcessCameraProvider.getInstance(this)-- cameraProviderFuture.addListener(Runnable {- // Used to bind the lifecycle of cameras to the lifecycle owner- val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()-- // Preview- preview = Preview.Builder()- .setTargetAspectRatio(AspectRatio.RATIO_4_3)- .build()-- val imageCaptureBuilder = ImageCapture.Builder()- imageCaptureBuilder.setTargetAspectRatio(AspectRatio.RATIO_4_3)- imageCapture = imageCaptureBuilder.build()-- // Select back camera- val cameraSelector =- CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()-- try {- // Unbind use cases before rebinding- cameraProvider.unbindAll()-- // Bind use cases to camera- camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)- preview?.setSurfaceProvider(viewFinder.surfaceProvider)- } catch (exc: Exception) {- Logger.e("Use case binding failed", exc.message.toString())- }-- }, ContextCompat.getMainExecutor(this))- }-- companion object {- const val REQUEST_SELECT_IMAGE = 666- }---}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/GalleryActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/GalleryActivity.ktdeleted file mode 100755index 5fe5405..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/GalleryActivity.kt+++ /dev/null@@ -1,242 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.app.Activity-import android.content.Intent-import android.graphics.Bitmap-import android.os.Bundle-import android.view.View-import android.widget.SeekBar-import androidx.appcompat.app.AppCompatActivity-import com.benjaminwan.ocr.onnx.app.App-import com.benjaminwan.ocr.onnx.dialog.DebugDialog-import com.benjaminwan.ocr.onnx.dialog.TextResultDialog-import com.benjaminwan.ocr.onnx.utils.decodeUri-import com.benjaminwan.ocr.onnx.utils.showToast-import com.benjaminwan.ocrlibrary.OcrResult-import com.bumptech.glide.Glide-import com.bumptech.glide.load.engine.DiskCacheStrategy-import com.bumptech.glide.request.RequestOptions-import com.orhanobut.logger.Logger-import com.uber.autodispose.android.lifecycle.autoDisposable-import io.reactivex.Single-import io.reactivex.android.schedulers.AndroidSchedulers-import io.reactivex.schedulers.Schedulers-import kotlinx.android.synthetic.main.activity_gallery.*-import kotlin.math.max--class GalleryActivity : AppCompatActivity(), View.OnClickListener, SeekBar.OnSeekBarChangeListener {-- private var selectedImg: Bitmap? = null- private var ocrResult: OcrResult? = null-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- setContentView(R.layout.activity_gallery)- App.ocrEngine.doAngle = true//相册识别时,默认启用文字方向检测- selectBtn.setOnClickListener(this)- detectBtn.setOnClickListener(this)- resultBtn.setOnClickListener(this)- debugBtn.setOnClickListener(this)- benchBtn.setOnClickListener(this)- doAngleSw.isChecked = App.ocrEngine.doAngle- mostAngleSw.isChecked = App.ocrEngine.mostAngle- updatePadding(App.ocrEngine.padding)- updateBoxScoreThresh((App.ocrEngine.boxScoreThresh * 100).toInt())- updateBoxThresh((App.ocrEngine.boxThresh * 100).toInt())- updateUnClipRatio((App.ocrEngine.unClipRatio * 10).toInt())- paddingSeekBar.setOnSeekBarChangeListener(this)- boxScoreThreshSeekBar.setOnSeekBarChangeListener(this)- boxThreshSeekBar.setOnSeekBarChangeListener(this)- maxSideLenSeekBar.setOnSeekBarChangeListener(this)- scaleUnClipRatioSeekBar.setOnSeekBarChangeListener(this)- doAngleSw.setOnCheckedChangeListener { _, isChecked ->- App.ocrEngine.doAngle = isChecked- mostAngleSw.isEnabled = isChecked- }- mostAngleSw.setOnCheckedChangeListener { _, isChecked ->- App.ocrEngine.mostAngle = isChecked- }- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.selectBtn -> {- val intent = Intent(Intent.ACTION_PICK).apply {- type = "image/*"- }- startActivityForResult(- intent, REQUEST_SELECT_IMAGE- )- }- R.id.detectBtn -> {- val img = selectedImg ?: return- val ratio = maxSideLenSeekBar.progress.toFloat() / 100.toFloat()- val maxSize = max(img.width, img.height)- val maxSideLen = (ratio * maxSize).toInt()- detect(img, maxSideLen)- }- R.id.resultBtn -> {- val result = ocrResult ?: return- TextResultDialog.instance- .setTitle("识别结果")- .setContent(result.strRes)- .show(supportFragmentManager, "TextResultDialog")- }- R.id.debugBtn -> {- val result = ocrResult ?: return- DebugDialog.instance- .setTitle("调试信息")- .setResult(result)- .show(supportFragmentManager, "DebugDialog")- }- R.id.benchBtn -> {- val img = selectedImg- if (img == null) {- showToast("请先选择一张图片")- return- }- val loop = 100- showToast("开始循环${loop}次的测试")- benchmark(img, loop)- }- else -> {- }- }- }-- override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {- seekBar ?: return- when (seekBar.id) {- R.id.maxSideLenSeekBar -> {- updateMaxSideLen(progress)- }- R.id.paddingSeekBar -> {- updatePadding(progress)- }- R.id.boxScoreThreshSeekBar -> {- updateBoxScoreThresh(progress)- }- R.id.boxThreshSeekBar -> {- updateBoxThresh(progress)- }- R.id.scaleUnClipRatioSeekBar -> {- updateUnClipRatio(progress)- }- else -> {- }- }- }-- override fun onStartTrackingTouch(seekBar: SeekBar?) {- }-- override fun onStopTrackingTouch(seekBar: SeekBar?) {- }-- private fun updateMaxSideLen(progress: Int) {- val ratio = progress.toFloat() / 100.toFloat()- if (selectedImg != null) {- val img = selectedImg ?: return- val maxSize = max(img.width, img.height)- val maxSizeLen = (ratio * maxSize).toInt()- maxSideLenTv.text = "MaxSideLen:$maxSizeLen(${ratio * 100}%)"- } else {- maxSideLenTv.text = "MaxSideLen:0(${ratio * 100}%)"- }- }-- private fun updatePadding(progress: Int) {- paddingTv.text = "Padding:$progress"- App.ocrEngine.padding = progress- }-- private fun updateBoxScoreThresh(progress: Int) {- val thresh = progress.toFloat() / 100.toFloat()- boxScoreThreshTv.text = "${getString(R.string.box_score_thresh)}:$thresh"- App.ocrEngine.boxScoreThresh = thresh- }-- private fun updateBoxThresh(progress: Int) {- val thresh = progress.toFloat() / 100.toFloat()- boxThreshTv.text = "BoxThresh:$thresh"- App.ocrEngine.boxThresh = thresh- }-- private fun updateUnClipRatio(progress: Int) {- val scale = progress.toFloat() / 10.toFloat()- unClipRatioTv.text = "${getString(R.string.box_un_clip_ratio)}:$scale"- App.ocrEngine.unClipRatio = scale- }-- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {- super.onActivityResult(requestCode, resultCode, data)- data ?: return- if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_SELECT_IMAGE) {- val imgUri = data.data ?: return- val options =- RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)- Glide.with(this).load(imgUri).apply(options).into(imageView)- selectedImg = decodeUri(imgUri)- updateMaxSideLen(maxSideLenSeekBar.progress)- clearLastResult()- }- }-- private fun showLoading() {- Glide.with(this).load(R.drawable.loading_anim).into(imageView)- }-- private fun clearLastResult() {- timeTV.text = ""- ocrResult = null- }-- private fun benchmark(img: Bitmap, loop: Int) {- Single.fromCallable {- val aveTime = App.ocrEngine.benchmark(img, loop)- //showToast("循环${loop}次,平均时间${aveTime}ms")- aveTime- }.subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .doOnSubscribe { showLoading() }- .doFinally { /*hideLoading()*/ }- .autoDisposable(this)- .subscribe { t1, t2 ->- timeTV.text = "循环${loop}次,平均时间${t1}ms"- Glide.with(this).clear(imageView)- }- }-- private fun detect(img: Bitmap, reSize: Int) {- Single.fromCallable {- val boxImg: Bitmap = Bitmap.createBitmap(- img.width, img.height, Bitmap.Config.ARGB_8888- )- Logger.i("selectedImg=${img.height},${img.width} ${img.config}")- val start = System.currentTimeMillis()- val ocrResult = App.ocrEngine.detect(img, boxImg, reSize)- val end = System.currentTimeMillis()- val time = "time=${end - start}ms"- ocrResult- }.subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .doOnSubscribe { showLoading() }- .doFinally { /*hideLoading()*/ }- .autoDisposable(this)- .subscribe { t1, t2 ->- ocrResult = t1- timeTV.text = "识别时间:${t1.detectTime.toInt()}ms"- val options =- RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)- Glide.with(this).load(t1.boxImg).apply(options).into(imageView)- Logger.i("$t1")- }- }-- companion object {- const val REQUEST_SELECT_IMAGE = 666- }---}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/IdCardFrontActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/IdCardFrontActivity.ktdeleted file mode 100755index 9b91f7b..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/IdCardFrontActivity.kt+++ /dev/null@@ -1,348 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.app.Service-import android.content.Intent-import android.graphics.Bitmap-import android.os.Bundle-import android.os.VibrationEffect-import android.os.Vibrator-import android.view.View-import android.widget.EditText-import androidx.appcompat.app.AppCompatActivity-import androidx.camera.core.*-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.view.PreviewView-import androidx.core.content.ContextCompat-import com.afollestad.assent.Permission-import com.afollestad.assent.askForPermissions-import com.afollestad.assent.isAllGranted-import com.afollestad.assent.rationale.createDialogRationale-import com.benjaminwan.ocr.onnx.app.App-import com.benjaminwan.ocr.onnx.models.IdCardFront-import com.benjaminwan.ocr.onnx.utils.getMatchIdCardNumberStr-import com.benjaminwan.ocr.onnx.utils.showToast-import com.benjaminwan.ocr.onnx.utils.trimBlankAndSymbols-import com.benjaminwan.ocrlibrary.OcrFailed-import com.benjaminwan.ocrlibrary.OcrResult-import com.benjaminwan.ocrlibrary.OcrStop-import com.orhanobut.logger.Logger-import com.uber.autodispose.android.lifecycle.autoDisposable-import io.reactivex.Observable-import io.reactivex.android.schedulers.AndroidSchedulers-import io.reactivex.schedulers.Schedulers-import kotlinx.android.synthetic.main.activity_idcard_front.*-import kotlin.math.max--class IdCardFrontActivity : AppCompatActivity(), View.OnClickListener {-- private var preview: Preview? = null- private var imageCapture: ImageCapture? = null- private var camera: Camera? = null- private lateinit var viewFinder: PreviewView- private var detectStart: Boolean = false-- private val vibrator: Vibrator by lazy {- applicationContext.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator- }-- //手机振动- private fun vibration() {- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {- val vibrationEffect = VibrationEffect.createOneShot(- 100, VibrationEffect.DEFAULT_AMPLITUDE- )- vibrator.vibrate(vibrationEffect)- } else {- vibrator.vibrate(100)- }- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- App.ocrEngine.doAngle = false//摄像头拍摄一般都是正的,不需要判断方向- App.ocrEngine.padding = 200- App.ocrEngine.boxScoreThresh = 0.1f- App.ocrEngine.unClipRatio = 2.0f- setContentView(R.layout.activity_idcard_front)- viewFinder = findViewById(R.id.viewFinder)- initViews()- }-- override fun onResume() {- super.onResume()- val rationaleHandler = createDialogRationale(R.string.app_permission) {- onPermission(- Permission.CAMERA, "请点击允许"- )- }-- if (!isAllGranted(Permission.CAMERA)) {- askForPermissions(- Permission.CAMERA,- rationaleHandler = rationaleHandler- ) { result ->- val permissionGranted: Boolean =- result.isAllGranted(- Permission.CAMERA- )- if (!permissionGranted) {- showToast("未获取权限,应用无法正常使用!")- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }-- override fun onStop() {- super.onStop()- setDetectState(false)- }-- private fun setResult() {- val text = numberEdit.text.toString().trim()- if (text.isNotEmpty()) {- val result = Intent().apply {- putExtra("scanResult", text)- }- setResult(1, result)- }- }-- override fun onBackPressed() {- setResult()- super.onBackPressed()- }-- private fun setEdit(editText: EditText, content: String) {- editText.setText(content)- editText.setSelection(content.length)- }-- private fun showResult(result: IdCardFront) {- setEdit(nameEdit, result.name)- setEdit(genderEdit, result.gender)- setEdit(nationEdit, result.nation)- setEdit(birthDateEdit, result.birth)- setEdit(addressEdit, result.address)- setEdit(numberEdit, result.number)- }-- private fun initViews() {- startBtn.setOnClickListener(this)- stopBtn.setOnClickListener(this)- clearNameBtn.setOnClickListener(this)- clearGenderBtn.setOnClickListener(this)- clearNationBtn.setOnClickListener(this)- clearBirthBtn.setOnClickListener(this)- clearAddressBtn.setOnClickListener(this)- clearNumberBtn.setOnClickListener(this)- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.startBtn -> {- detectLoop()- }- R.id.stopBtn -> {- detectStart = false- }- R.id.clearNameBtn -> {- nameEdit.setText("")- }- R.id.clearGenderBtn -> {- genderEdit.setText("")- }- R.id.clearNationBtn -> {- nationEdit.setText("")- }- R.id.clearBirthBtn -> {- birthDateEdit.setText("")- }- R.id.clearAddressBtn -> {- addressEdit.setText("")- }- R.id.clearNumberBtn -> {- numberEdit.setText("")- }- }- }-- private fun detectOnce(bitmap: Bitmap): OcrResult {- val maxSize = max(bitmap.height, bitmap.width)- val boxImg = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)- App.ocrEngine.padding = maxSize / 10- return App.ocrEngine.detect(bitmap, boxImg, maxSize)- }-- private fun setDetectState(isStart: Boolean) {- detectStart = isStart- startBtn.isEnabled = !isStart- stopBtn.isEnabled = isStart- nameEdit.isEnabled = !isStart- genderEdit.isEnabled = !isStart- nationEdit.isEnabled = !isStart- birthDateEdit.isEnabled = !isStart- addressEdit.isEnabled = !isStart- numberEdit.isEnabled = !isStart- clearNameBtn.isEnabled = !isStart- clearGenderBtn.isEnabled = !isStart- clearNationBtn.isEnabled = !isStart- clearBirthBtn.isEnabled = !isStart- clearAddressBtn.isEnabled = !isStart- clearNumberBtn.isEnabled = !isStart- if (isStart) idCardFrontView.bitmap = null- }-- private fun detectLoop() {- setDetectState(true)- Observable.fromCallable {- var success: IdCardFront? = null- var numberStr: String? = null- var nameStr: String? = null- var nationStr: String? = null- var addressStr: String? = null- val start = System.currentTimeMillis()- do {- val cameraBitmap = viewFinder.bitmap ?: continue- if (cameraBitmap.width <= 0 || cameraBitmap.height <= 0) continue- //先识别身份证号- if (numberStr == null) {- val numberBitmap = idCardFrontView.cropNumberBitmap(cameraBitmap)- val numberOnce = detectOnce(numberBitmap)- Logger.i(numberOnce.strRes)- numberStr =- getMatchIdCardNumberStr(numberOnce.strRes.trimBlankAndSymbols()) ?: continue- }- //识别姓名- if (nameStr == null) {- val nameBitmap = idCardFrontView.cropNameBitmap(cameraBitmap)- val nameOnce = detectOnce(nameBitmap)- Logger.i(nameOnce.toString())- val nameLine = nameOnce.textBlocks.sortedBy { it.boxPoint.first().x }- .joinToString("") { it.text.trimBlankAndSymbols() }- if (nameLine.isEmpty()) continue- nameStr = if (nameLine.contains("姓名") && nameLine.length > 2) {- nameLine.substringAfter("姓名")- } else if (nameLine.contains("名") && nameLine.length > 1 && nameLine.indexOf("名") <= 1) {- nameLine.substringAfter("名")- } else {- null- }- nameStr ?: continue- }- //民族- if (nationStr == null) {- val nationBitmap = idCardFrontView.cropNationBitmap(cameraBitmap)- val nationOnce = detectOnce(nationBitmap)- Logger.i(nationOnce.toString())- val nationLine = nationOnce.textBlocks.sortedBy { it.boxPoint.first().x }- .joinToString("") { it.text.trimBlankAndSymbols() }- if (nationLine.isEmpty()) continue- nationStr = if (nationLine.contains("民族") && nationLine.length > 2) {- nationLine.substringAfter("民族")- } else if (nationLine.contains("族") &&- nationLine.length > 1 && nationLine.indexOf("族") <= 1- ) {- nationLine.substringAfter("族")- } else {- null- }- nationStr ?: continue- }-- //住址- if (addressStr == null) {- val addressBitmap = idCardFrontView.cropAddressBitmap(cameraBitmap)- val addressOnce = detectOnce(addressBitmap)- Logger.i(addressOnce.toString())- val addressLine = addressOnce.textBlocks.sortedBy { it.boxPoint.first().y }- .joinToString("") { it.text.trimBlankAndSymbols() }- if (addressLine.isEmpty()) continue- addressStr = if (addressLine.contains("住址") && addressLine.length > 2) {- addressLine.substringAfter("住址")- } else if (addressLine.contains("址") &&- addressLine.length > 1 && addressLine.indexOf("址") <= 1- ) {- addressLine.substringAfter("址")- } else {- addressLine- }- }-- success = IdCardFront(- nameStr,- nationStr,- addressStr,- numberStr- )- } while (success == null && detectStart)- val end = System.currentTimeMillis()- Logger.i("time=${end - start}")- success ?: if (!detectStart) {- OcrStop- } else {- OcrFailed- }- }.subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .autoDisposable(this)- .subscribe({- when (it) {- is IdCardFront -> {- setDetectState(false)- vibration()- showResult(it)- }- is OcrStop -> {- setDetectState(false)- }- is OcrFailed -> {- detectLoop()- }- }- }, {- detectLoop()- })- }-- private fun startCamera() {- val cameraProviderFuture = ProcessCameraProvider.getInstance(this)-- cameraProviderFuture.addListener(Runnable {- // Used to bind the lifecycle of cameras to the lifecycle owner- val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()-- // Preview- preview = Preview.Builder()- .setTargetAspectRatio(AspectRatio.RATIO_4_3)- .build()-- val imageCaptureBuilder = ImageCapture.Builder()- imageCaptureBuilder.setTargetAspectRatio(AspectRatio.RATIO_4_3)- imageCapture = imageCaptureBuilder.build()-- // Select back camera- val cameraSelector =- CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()-- try {- // Unbind use cases before rebinding- cameraProvider.unbindAll()-- // Bind use cases to camera- camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)- preview?.setSurfaceProvider(viewFinder.surfaceProvider)- } catch (exc: Exception) {- Logger.e("Use case binding failed", exc)- }-- }, ContextCompat.getMainExecutor(this))- }--}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/ImeiActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/ImeiActivity.ktdeleted file mode 100755index 3225372..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/ImeiActivity.kt+++ /dev/null@@ -1,232 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.app.Service-import android.content.Intent-import android.graphics.Bitmap-import android.os.Bundle-import android.os.VibrationEffect-import android.os.Vibrator-import android.view.View-import androidx.appcompat.app.AppCompatActivity-import androidx.camera.core.*-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.view.PreviewView-import androidx.core.content.ContextCompat-import com.afollestad.assent.Permission-import com.afollestad.assent.askForPermissions-import com.afollestad.assent.isAllGranted-import com.afollestad.assent.rationale.createDialogRationale-import com.benjaminwan.ocr.onnx.app.App-import com.benjaminwan.ocr.onnx.utils.getMatchImeiStr-import com.benjaminwan.ocr.onnx.utils.replaceBlank-import com.benjaminwan.ocr.onnx.utils.showToast-import com.benjaminwan.ocrlibrary.OcrFailed-import com.benjaminwan.ocrlibrary.OcrResult-import com.benjaminwan.ocrlibrary.OcrStop-import com.orhanobut.logger.Logger-import com.uber.autodispose.android.lifecycle.autoDisposable-import io.reactivex.Observable-import io.reactivex.android.schedulers.AndroidSchedulers-import io.reactivex.schedulers.Schedulers-import kotlinx.android.synthetic.main.activity_imei.*-import kotlin.math.max--class ImeiActivity : AppCompatActivity(), View.OnClickListener {-- private var preview: Preview? = null- private var imageCapture: ImageCapture? = null- private var camera: Camera? = null- private lateinit var viewFinder: PreviewView- private var detectStart: Boolean = false-- private val vibrator: Vibrator by lazy {- applicationContext.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator- }-- //手机振动- private fun vibration() {- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {- val vibrationEffect = VibrationEffect.createOneShot(- 100, VibrationEffect.DEFAULT_AMPLITUDE- )- vibrator.vibrate(vibrationEffect)- } else {- vibrator.vibrate(100)- }- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- App.ocrEngine.doAngle = false//摄像头拍摄一般都是正的,不需要判断方向- setContentView(R.layout.activity_imei)- viewFinder = findViewById(R.id.viewFinder)- initViews()- }-- override fun onResume() {- super.onResume()- val rationaleHandler = createDialogRationale(R.string.app_permission) {- onPermission(- Permission.CAMERA, "请点击允许"- )- }-- if (!isAllGranted(Permission.CAMERA)) {- askForPermissions(- Permission.CAMERA,- rationaleHandler = rationaleHandler- ) { result ->- val permissionGranted: Boolean =- result.isAllGranted(- Permission.CAMERA- )- if (!permissionGranted) {- showToast("未获取权限,应用无法正常使用!")- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }-- override fun onStop() {- super.onStop()- setDetectState(false)- }-- private fun setResult() {- val text = resultEdit.text.toString().trim()- if (text.isNotEmpty()) {- val result = Intent().apply {- putExtra("scanResult", text)- }- setResult(1, result)- }- }-- override fun onBackPressed() {- setResult()- super.onBackPressed()- }-- private fun showResult(result: OcrResult) {- cameraLensView.cameraLensBitmap = result.boxImg- resultEdit.setText(result.strRes)- resultEdit.setSelection(result.strRes.length)- }-- private fun initViews() {- startBtn.setOnClickListener(this)- stopBtn.setOnClickListener(this)- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.startBtn -> {- detectLoop()- }- R.id.stopBtn -> {- detectStart = false- }- }- }-- private fun detectOnce(bitmap: Bitmap): OcrResult {- val maxSize = max(bitmap.height, bitmap.width)- val boxImg = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)- return App.ocrEngine.detect(bitmap, boxImg, maxSize)- }-- private fun setDetectState(isStart: Boolean) {- detectStart = isStart- startBtn.isEnabled = !isStart- stopBtn.isEnabled = isStart- resultEdit.isEnabled = !isStart- }-- private fun detectLoop() {- cameraLensView.cameraLensBitmap = null- resultEdit.setText("")- setDetectState(true)- Observable.fromCallable {- var success: OcrResult? = null- do {- val camPic = viewFinder.bitmap ?: continue- if (camPic.width <= 0 || camPic.height <= 0) continue- val bitmap =- cameraLensView.cropCameraLensRectBitmap(camPic, false)- val once = detectOnce(bitmap)- Logger.i(once.strRes)- val matchId = getMatchImeiStr(once.strRes.replaceBlank().toUpperCase())- if (matchId != null) {- success = once.copy(strRes = matchId)- }- } while (success == null && detectStart)- success ?: if (!detectStart) {- OcrStop- } else {- OcrFailed- }- }- .subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .autoDisposable(this)- .subscribe({- when (it) {- is OcrResult -> {- setDetectState(false)- vibration()- showResult(it)- }- is OcrStop -> {- setDetectState(false)- }- is OcrFailed -> {- detectLoop()- }- }- }, {- detectLoop()- })- }-- private fun startCamera() {- val cameraProviderFuture = ProcessCameraProvider.getInstance(this)-- cameraProviderFuture.addListener(Runnable {- // Used to bind the lifecycle of cameras to the lifecycle owner- val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()-- // Preview- preview = Preview.Builder()- .setTargetAspectRatio(AspectRatio.RATIO_4_3)- .build()-- val imageCaptureBuilder = ImageCapture.Builder()- imageCaptureBuilder.setTargetAspectRatio(AspectRatio.RATIO_4_3)- imageCapture = imageCaptureBuilder.build()-- // Select back camera- val cameraSelector =- CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()-- try {- // Unbind use cases before rebinding- cameraProvider.unbindAll()-- // Bind use cases to camera- camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)- preview?.setSurfaceProvider(viewFinder.surfaceProvider)- } catch (exc: Exception) {- Logger.e("Use case binding failed", exc)- }-- }, ContextCompat.getMainExecutor(this))- }--}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/MainActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/MainActivity.ktdeleted file mode 100755index b6f45df..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/MainActivity.kt+++ /dev/null@@ -1,43 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.content.Intent-import android.os.Bundle-import android.view.View-import androidx.appcompat.app.AppCompatActivity-import kotlinx.android.synthetic.main.activity_main.*--class MainActivity : AppCompatActivity(), View.OnClickListener {-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- setContentView(R.layout.activity_main)- galleryBtn.setOnClickListener(this)- cameraBtn.setOnClickListener(this)- imeiBtn.setOnClickListener(this)- plateBtn.setOnClickListener(this)- idCardBtn.setOnClickListener(this)- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.galleryBtn -> {- startActivity(Intent(this, GalleryActivity::class.java))- }- R.id.cameraBtn -> {- startActivity(Intent(this, CameraActivity::class.java))- }- R.id.imeiBtn -> {- startActivity(Intent(this, ImeiActivity::class.java))- }- R.id.plateBtn -> {- startActivity(Intent(this, PlateActivity::class.java))- }- R.id.idCardBtn -> {- startActivity(Intent(this, IdCardFrontActivity::class.java))- }- else -> {- }- }- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/PlateActivity.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/PlateActivity.ktdeleted file mode 100755index f4e2209..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/PlateActivity.kt+++ /dev/null@@ -1,236 +0,0 @@-package com.benjaminwan.ocr.onnx--import android.app.Service-import android.content.Intent-import android.graphics.Bitmap-import android.os.Bundle-import android.os.VibrationEffect-import android.os.Vibrator-import android.view.View-import androidx.appcompat.app.AppCompatActivity-import androidx.camera.core.*-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.view.PreviewView-import androidx.core.content.ContextCompat-import com.afollestad.assent.Permission-import com.afollestad.assent.askForPermissions-import com.afollestad.assent.isAllGranted-import com.afollestad.assent.rationale.createDialogRationale-import com.benjaminwan.ocr.onnx.app.App-import com.benjaminwan.ocr.onnx.utils.getMatchPlateStr-import com.benjaminwan.ocr.onnx.utils.showToast-import com.benjaminwan.ocr.onnx.utils.trimBlankAndSymbols-import com.benjaminwan.ocrlibrary.OcrFailed-import com.benjaminwan.ocrlibrary.OcrResult-import com.benjaminwan.ocrlibrary.OcrStop-import com.orhanobut.logger.Logger-import com.uber.autodispose.android.lifecycle.autoDisposable-import io.reactivex.Observable-import io.reactivex.android.schedulers.AndroidSchedulers-import io.reactivex.schedulers.Schedulers-import kotlinx.android.synthetic.main.activity_plate.*-import kotlin.math.max--class PlateActivity : AppCompatActivity(), View.OnClickListener {-- private var preview: Preview? = null- private var imageCapture: ImageCapture? = null- private var camera: Camera? = null- private lateinit var viewFinder: PreviewView- private var detectStart: Boolean = false-- private val vibrator: Vibrator by lazy {- applicationContext.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator- }-- //手机振动- private fun vibration() {- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {- val vibrationEffect = VibrationEffect.createOneShot(- 100, VibrationEffect.DEFAULT_AMPLITUDE- )- vibrator.vibrate(vibrationEffect)- } else {- vibrator.vibrate(100)- }- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- App.ocrEngine.doAngle = false//摄像头拍摄一般都是正的,不需要判断方向- App.ocrEngine.padding = 100- App.ocrEngine.boxScoreThresh = 0.2f- App.ocrEngine.unClipRatio = 2.0f- setContentView(R.layout.activity_plate)- viewFinder = findViewById(R.id.viewFinder)- initViews()- }-- override fun onResume() {- super.onResume()- val rationaleHandler = createDialogRationale(R.string.app_permission) {- onPermission(- Permission.CAMERA, "请点击允许"- )- }-- if (!isAllGranted(Permission.CAMERA)) {- askForPermissions(- Permission.CAMERA,- rationaleHandler = rationaleHandler- ) { result ->- val permissionGranted: Boolean =- result.isAllGranted(- Permission.CAMERA- )- if (!permissionGranted) {- showToast("未获取权限,应用无法正常使用!")- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }- } else {- startCamera()- viewFinder.postDelayed({ detectLoop() }, 100)- }- }-- override fun onStop() {- super.onStop()- setDetectState(false)- }-- private fun setResult() {- val text = resultEdit.text.toString().trim()- if (text.isNotEmpty()) {- val result = Intent().apply {- putExtra("scanResult", text)- }- setResult(1, result)- }- }-- override fun onBackPressed() {- setResult()- super.onBackPressed()- }-- private fun showResult(result: OcrResult) {- cameraLensView.cameraLensBitmap = result.boxImg- resultEdit.setText(result.strRes)- resultEdit.setSelection(result.strRes.length)- }-- private fun initViews() {- startBtn.setOnClickListener(this)- stopBtn.setOnClickListener(this)- }-- override fun onClick(view: View?) {- view ?: return- when (view.id) {- R.id.startBtn -> {- detectLoop()- }- R.id.stopBtn -> {- detectStart = false- }- }- }-- private fun detectOnce(bitmap: Bitmap): OcrResult {- val maxSize = max(bitmap.height, bitmap.width)- val boxImg = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)- return App.ocrEngine.detect(bitmap, boxImg, maxSize / 2)- }-- private fun setDetectState(isStart: Boolean) {- detectStart = isStart- startBtn.isEnabled = !isStart- stopBtn.isEnabled = isStart- resultEdit.isEnabled = !isStart- }-- private fun detectLoop() {- cameraLensView.cameraLensBitmap = null- resultEdit.setText("")- setDetectState(true)- Observable.fromCallable {- var success: OcrResult? = null- do {- val camPic = viewFinder.bitmap ?: continue- if (camPic.width <= 0 || camPic.height <= 0) continue- val bitmap =- cameraLensView.cropCameraLensRectBitmap(camPic, false)- val once = detectOnce(bitmap)- val text = once.strRes.trimBlankAndSymbols().toUpperCase()- Logger.i(text)- val matchId = getMatchPlateStr(text)- if (matchId != null) {- success = once.copy(strRes = matchId)- }- } while (success == null && detectStart)- success ?: if (!detectStart) {- OcrStop- } else {- OcrFailed- }- }- .subscribeOn(Schedulers.io())- .observeOn(AndroidSchedulers.mainThread())- .autoDisposable(this)- .subscribe({- when (it) {- is OcrResult -> {- setDetectState(false)- vibration()- showResult(it)- }- is OcrStop -> {- setDetectState(false)- }- is OcrFailed -> {- detectLoop()- }- }- }, {- detectLoop()- })- }-- private fun startCamera() {- val cameraProviderFuture = ProcessCameraProvider.getInstance(this)-- cameraProviderFuture.addListener(Runnable {- // Used to bind the lifecycle of cameras to the lifecycle owner- val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()-- // Preview- preview = Preview.Builder()- .setTargetAspectRatio(AspectRatio.RATIO_4_3)- .build()-- val imageCaptureBuilder = ImageCapture.Builder()- imageCaptureBuilder.setTargetAspectRatio(AspectRatio.RATIO_4_3)- imageCapture = imageCaptureBuilder.build()-- // Select back camera- val cameraSelector =- CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()-- try {- // Unbind use cases before rebinding- cameraProvider.unbindAll()-- // Bind use cases to camera- camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)- preview?.setSurfaceProvider(viewFinder.surfaceProvider)- } catch (exc: Exception) {- Logger.e("Use case binding failed", exc)- }-- }, ContextCompat.getMainExecutor(this))- }--}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/app/App.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/app/App.ktdeleted file mode 100755index 26d78a7..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/app/App.kt+++ /dev/null@@ -1,56 +0,0 @@-package com.benjaminwan.ocr.onnx.app--import android.app.Application-import android.util.Log-import com.benjaminwan.ocr.onnx.BuildConfig-import com.benjaminwan.ocrlibrary.OcrEngine-import com.orhanobut.logger.AndroidLogAdapter-import com.orhanobut.logger.LogStrategy-import com.orhanobut.logger.Logger-import com.orhanobut.logger.PrettyFormatStrategy--class App : Application() {- companion object {- lateinit var INSTANCE: App- lateinit var ocrEngine: OcrEngine- }-- override fun onCreate() {- super.onCreate()- INSTANCE = this- initLogger()- initOCREngine()- }- private fun initOCREngine() {- ocrEngine = OcrEngine(this.applicationContext)- }-- private fun initLogger() {- val formatStrategy = PrettyFormatStrategy.newBuilder()- .showThreadInfo(true)- .tag("OcrLite")- .logStrategy(LogCatStrategy())- .build()- Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {- override fun isLoggable(priority: Int, tag: String?): Boolean = BuildConfig.DEBUG- })- }-- inner class LogCatStrategy : LogStrategy {-- private var last: Int = 0-- override fun log(priority: Int, tag: String?, message: String) {- Log.println(priority, randomKey() + tag!!, message)- }-- private fun randomKey(): String {- var random = (10 * Math.random()).toInt()- if (random == last) {- random = (random + 1) % 10- }- last = random- return random.toString()- }- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/BaseDialog.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/BaseDialog.ktdeleted file mode 100755index c61ae9a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/BaseDialog.kt+++ /dev/null@@ -1,100 +0,0 @@-package com.benjaminwan.ocr.onnx.dialog--import android.app.Dialog-import android.os.Bundle-import android.util.DisplayMetrics-import android.view.Gravity-import android.view.ViewGroup-import android.view.WindowManager-import androidx.fragment.app.DialogFragment--abstract class BaseDialog : DialogFragment() {-- private var mGravity = Gravity.CENTER//对话框的位置- private var mCanceledOnTouchOutside = true//是否触摸外部关闭- private var mCanceledBack = true//是否返回键关闭- private var mAnimStyle: Int = 0//显示动画-- override fun onActivityCreated(savedInstanceState: Bundle?) {- //修复DialogFragment内存泄漏- if (showsDialog) {- showsDialog = false- }- super.onActivityCreated(savedInstanceState)- showsDialog = true-- val tmpView = view- if (tmpView != null) {- check(tmpView.parent == null) { "DialogFragment can not be attached to a container view" }- dialog?.setContentView(tmpView)- }-- activity?.let {- dialog?.setOwnerActivity(it)- }-- if (savedInstanceState != null) {- val dialogState = savedInstanceState.getBundle("android:savedDialogState")- if (dialogState != null) {- dialog?.onRestoreInstanceState(dialogState)- }- }- }-- fun setGravity(gravity: Int) {- mGravity = gravity- }-- fun setCanceledBack(canceledBack: Boolean) {- mCanceledBack = canceledBack- }-- fun setCanceledOnTouchOutside(canceledOnTouchOutsidek: Boolean) {- mCanceledOnTouchOutside = canceledOnTouchOutsidek- }-- fun setAnimStyle(animStyle: Int) {- mAnimStyle = animStyle- }-- override fun onStart() {- val baseDialog = dialog- if (baseDialog != null) {- baseDialog.setCanceledOnTouchOutside(mCanceledOnTouchOutside)- baseDialog.setCancelable(mCanceledBack)- setDialogGravity(baseDialog)//设置对话框布局- }- // 全屏显示Dialog,重新测绘宽高- if (dialog != null) {- val dm = DisplayMetrics()- activity?.windowManager?.defaultDisplay?.getMetrics(dm)- val attributes = dialog!!.window!!.attributes- attributes.gravity = Gravity.CENTER//对齐方式- dialog?.window?.attributes = attributes- dialog?.window?.setLayout(- ViewGroup.LayoutParams.MATCH_PARENT,- (dm.heightPixels * 0.9).toInt()- )- }- super.onStart()- }-- /**- * 对话框配置- *- * @param dialog- */- private fun setDialogGravity(dialog: Dialog) {- val window = dialog.window ?: return- val wlp = window.attributes- wlp.gravity = mGravity- wlp.width = WindowManager.LayoutParams.MATCH_PARENT- wlp.height = WindowManager.LayoutParams.WRAP_CONTENT-- window.attributes = wlp- //动画- if (mAnimStyle != 0) {- window.setWindowAnimations(mAnimStyle)- }- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/DebugDialog.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/DebugDialog.ktdeleted file mode 100755index 9fdde1b..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/DebugDialog.kt+++ /dev/null@@ -1,117 +0,0 @@-package com.benjaminwan.ocr.onnx.dialog--import android.os.Bundle-import android.view.Gravity-import android.view.LayoutInflater-import android.view.View-import android.view.ViewGroup-import androidx.recyclerview.widget.DefaultItemAnimator-import com.airbnb.epoxy.EpoxyRecyclerView-import com.benjaminwan.ocr.onnx.R-import com.benjaminwan.ocr.onnx.models.dbNetTimeItemView-import com.benjaminwan.ocr.onnx.models.debugItemView-import com.benjaminwan.ocr.onnx.utils.format-import com.benjaminwan.ocr.onnx.utils.hideSoftInput-import com.benjaminwan.ocr.onnx.utils.setMarginItemDecoration-import com.benjaminwan.ocrlibrary.OcrResult-import com.benjaminwan.ocrlibrary.TextBlock-import kotlinx.android.synthetic.main.dialog_debug.*-import kotlinx.android.synthetic.main.dialog_text_result.negativeBtn-import kotlinx.android.synthetic.main.dialog_text_result.positiveBtn-import kotlinx.android.synthetic.main.dialog_text_result.titleTV--class DebugDialog : BaseDialog(), View.OnClickListener {- companion object {- val instance: DebugDialog- get() {- val dialog = DebugDialog()- dialog.setCanceledBack(true)- dialog.setCanceledOnTouchOutside(false)- dialog.setGravity(Gravity.CENTER)- dialog.setAnimStyle(R.style.diag_top_down_up_animation)- return dialog- }- }-- private var title: String = ""- private var textBlocks: MutableList<TextBlock> = mutableListOf()- private var dbnetTime: Double = 0.0- private lateinit var recyclerView: EpoxyRecyclerView-- override fun onCreateView(- inflater: LayoutInflater,- viewGroup: ViewGroup?,- savedInstanceState: Bundle?- ): View? {- return inflater.inflate(R.layout.dialog_debug, viewGroup, false)- }-- override fun onActivityCreated(savedInstanceState: Bundle?) {- super.onActivityCreated(savedInstanceState)- initViews()- }-- override fun dismiss() {- hideSoftInput()- super.dismiss()- }-- private fun initViews() {- debugRV.setHasFixedSize(true)- debugRV.itemAnimator = DefaultItemAnimator()- debugRV.setMarginItemDecoration(2, 1, 2, 1)-- debugRV.withModels {- dbNetTimeItemView {- id("dbnet time item")- dbNetTimeStr(dbnetTime.format("#0.00") + "ms")- }- textBlocks.withIndex().forEach { (id, item) ->- val boxPointStr = item.boxPoint.map { "[${it.x},${it.y}]" }.joinToString()- val charScoresStr = item.charScores.map { it.format("#0.00") }.joinToString()- debugItemView {- id("debug view $id")- index("$id")- boxPoint(boxPointStr)- boxScore(item.boxScore.format("#0.00"))- angleIndex(item.angleIndex.toString())- angleScore(item.angleScore.format("#0.00"))- angleTime(item.angleTime.format("#0.00") + "ms")- text(item.text)- charScores(charScoresStr)- crnnTime(item.crnnTime.format("#0.00") + "ms")- blockTime(item.blockTime.format("#0.00") + "ms")- }- }- }-- negativeBtn.setOnClickListener(this)- positiveBtn.setOnClickListener(this)- if (title.isNotEmpty()) {- titleTV.text = title- }-- }-- fun setTitle(title: String): DebugDialog {- this.title = title- return this- }-- fun setResult(result: OcrResult): DebugDialog {- textBlocks.clear()- textBlocks.addAll(result.textBlocks)- dbnetTime = result.dbNetTime- return this- }-- override fun onClick(view: View) {- val resId = view.id- if (resId == R.id.negativeBtn) {- dismiss()- } else if (resId == R.id.positiveBtn) {- this.dismiss()- }- }--}diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/TextResultDialog.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/TextResultDialog.ktdeleted file mode 100755index 0750d0f..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/dialog/TextResultDialog.kt+++ /dev/null@@ -1,77 +0,0 @@-package com.benjaminwan.ocr.onnx.dialog--import android.os.Bundle-import android.view.Gravity-import android.view.LayoutInflater-import android.view.View-import android.view.ViewGroup-import com.benjaminwan.ocr.onnx.R-import com.benjaminwan.ocr.onnx.utils.hideSoftInput-import com.benjaminwan.ocr.onnx.utils.toClipboard-import kotlinx.android.synthetic.main.dialog_text_result.*--class TextResultDialog : BaseDialog(), View.OnClickListener {- companion object {- val instance: TextResultDialog- get() {- val dialog = TextResultDialog()- dialog.setCanceledBack(true)- dialog.setCanceledOnTouchOutside(false)- dialog.setGravity(Gravity.CENTER)- dialog.setAnimStyle(R.style.diag_top_down_up_animation)- return dialog- }- }-- private var content: String = ""- private var title: String = ""-- override fun onCreateView(- inflater: LayoutInflater,- viewGroup: ViewGroup?,- savedInstanceState: Bundle?- ): View? {- return inflater.inflate(R.layout.dialog_text_result, viewGroup, false)- }-- override fun onActivityCreated(savedInstanceState: Bundle?) {- super.onActivityCreated(savedInstanceState)- initViews()- }-- override fun dismiss() {- hideSoftInput()- super.dismiss()- }-- private fun initViews() {- negativeBtn.setOnClickListener(this)- positiveBtn.setOnClickListener(this)- contentEdit.setText(content)- if (title.isNotEmpty()) {- titleTV.text = title- }- }-- fun setTitle(title: String): TextResultDialog {- this.title = title- return this- }-- fun setContent(textContent: String): TextResultDialog {- content = textContent- return this- }--- override fun onClick(view: View) {- val resId = view.id- if (resId == R.id.negativeBtn) {- dismiss()- } else if (resId == R.id.positiveBtn) {- requireContext().toClipboard(content)- this.dismiss()- }- }--}diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DbNetTimeItemView.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DbNetTimeItemView.ktdeleted file mode 100755index 4e15b97..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DbNetTimeItemView.kt+++ /dev/null@@ -1,33 +0,0 @@-package com.benjaminwan.ocr.onnx.models--import android.content.Context-import android.util.AttributeSet-import android.widget.LinearLayout-import com.airbnb.epoxy.AfterPropsSet-import com.airbnb.epoxy.ModelView-import com.airbnb.epoxy.TextProp-import com.benjaminwan.ocr.onnx.R-import kotlinx.android.synthetic.main.rv_dbnet_time_item.view.*--// The ModelView annotation is used on Views to have models generated from those views.-// This is pretty straightforward with Kotlin, but properties need some special handling.-@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)-class DbNetTimeItemView @JvmOverloads constructor(- context: Context,- attrs: AttributeSet? = null,- defStyleAttr: Int = 0-) : LinearLayout(context, attrs, defStyleAttr) {-- init {- inflate(context, R.layout.rv_dbnet_time_item, this)- }-- // 2. Or you can use lateinit- @TextProp- lateinit var dbNetTimeStr: CharSequence-- @AfterPropsSet- fun useProps() {- dbNetTimeTv.text = dbNetTimeStr- }-}diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DebugItemView.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DebugItemView.ktdeleted file mode 100755index 93c73eb..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/DebugItemView.kt+++ /dev/null@@ -1,70 +0,0 @@-package com.benjaminwan.ocr.onnx.models--import android.content.Context-import android.util.AttributeSet-import android.widget.LinearLayout-import com.airbnb.epoxy.AfterPropsSet-import com.airbnb.epoxy.ModelView-import com.airbnb.epoxy.TextProp-import com.benjaminwan.ocr.onnx.R-import kotlinx.android.synthetic.main.rv_debug_item_content.view.*-import kotlinx.android.synthetic.main.rv_debug_view_item.view.*--// The ModelView annotation is used on Views to have models generated from those views.-// This is pretty straightforward with Kotlin, but properties need some special handling.-@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)-class DebugItemView @JvmOverloads constructor(- context: Context,- attrs: AttributeSet? = null,- defStyleAttr: Int = 0-) : LinearLayout(context, attrs, defStyleAttr) {-- init {- inflate(context, R.layout.rv_debug_view_item, this)- }-- // 2. Or you can use lateinit- @TextProp- lateinit var index: CharSequence-- @TextProp- lateinit var boxPoint: CharSequence-- @TextProp- lateinit var boxScore: CharSequence-- @TextProp- lateinit var angleIndex: CharSequence-- @TextProp- lateinit var angleScore: CharSequence-- @TextProp- lateinit var angleTime: CharSequence-- @TextProp- lateinit var text: CharSequence-- @TextProp- lateinit var charScores: CharSequence-- @TextProp- lateinit var crnnTime: CharSequence-- @TextProp- lateinit var blockTime: CharSequence-- @AfterPropsSet- fun useProps() {- blockIndexTv.text = index- boxPointTv.text = boxPoint- boxScoreTv.text = boxScore- angleIndexTv.text = angleIndex- angleScoreTv.text = angleScore- angleTimeTv.text = angleTime- textTv.text = text- charScoresTv.text = charScores- crnnTimeTv.text = crnnTime- blockTimeTv.text = blockTime- }-}diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/IdCardFront.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/IdCardFront.ktdeleted file mode 100755index 618e970..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/models/IdCardFront.kt+++ /dev/null@@ -1,34 +0,0 @@-package com.benjaminwan.ocr.onnx.models--import android.os.Parcelable-import com.benjaminwan.ocrlibrary.OcrOutput-import kotlinx.android.parcel.Parcelize--@Parcelize-data class IdCardFront(- val name: String,//姓名- val nation: String,//民族- val address: String,//地址- val number: String,//身份证号-) : Parcelable, OcrOutput() {- //性别- val gender: String- get() {- val genderNumber = number[16].toInt()- return if (genderNumber % 2 == 1) "男" else "女"- }-- //出生日期- val birth: String- get() {- val year = number.substring(6..9)- val month = number.substring(10..11)- val date = number.substring(12..13)- return "$year-$month-$date"- }-- fun isEmpty(): Boolean =- name.isEmpty() && nation.isEmpty() && address.isEmpty() && number.isEmpty()---}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/BitmapUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/BitmapUtils.ktdeleted file mode 100755index 5c3d224..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/BitmapUtils.kt+++ /dev/null@@ -1,17 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import android.content.Context-import android.graphics.Bitmap-import android.graphics.BitmapFactory-import android.net.Uri-import java.io.FileNotFoundException--@Throws(FileNotFoundException::class)-fun Context.decodeUri(imgUri: Uri): Bitmap? {- // Decode image size- val options = BitmapFactory.Options()- options.inJustDecodeBounds = false- options.inMutable = true- options.inPreferredConfig = Bitmap.Config.ARGB_8888- return BitmapFactory.decodeStream(contentResolver.openInputStream(imgUri), null, options)-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ClipboardUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ClipboardUtils.ktdeleted file mode 100755index 4bee7b4..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ClipboardUtils.kt+++ /dev/null@@ -1,34 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import android.content.ClipData-import android.content.ClipboardManager-import android.content.Context--fun Context.toClipboard(text: String) {- val clipboardManager =- this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager- // 创建普通字符型ClipData- val mClipData = ClipData.newPlainText(packageName, text)- // 将ClipData内容放到系统剪贴板里。- clipboardManager.setPrimaryClip(mClipData)- this.showToast("已复制到剪切板!")-}--fun Context.fromClipboard(): String? {- val clipboardManager =- this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager- return if (clipboardManager.hasPrimaryClip()) {- val clipData = clipboardManager.primaryClip- if (clipData != null) {- if (clipData.itemCount > 0) {- clipData.getItemAt(0).text.toString()- } else {- null- }- } else {- null- }- } else {- null- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/DecimalFormatUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/DecimalFormatUtils.ktdeleted file mode 100755index 8fe9090..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/DecimalFormatUtils.kt+++ /dev/null@@ -1,52 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import java.text.DecimalFormat--/**- * 数字格式化- * @param pattern 格式- * 例"#.000000" 保留6位小数- * @return 返回格式化后的字符串- */-fun Double.format(pattern: String): String {- if (pattern.isEmpty()) {- return this.toString()- }- return DecimalFormat(pattern).format(this)-}--/**- * 数字格式化- * @param pattern 格式- * @return 返回格式化后的字符串- */-fun Long.format(pattern: String): String {- if (pattern.isEmpty()) {- return this.toString()- }- return DecimalFormat(pattern).format(this)-}--/**- * 数字格式化- * @param pattern 格式- * @return 返回格式化后的字符串- */-fun Int.format(pattern: String): String {- if (pattern.isEmpty()) {- return this.toString()- }- return DecimalFormat(pattern).format(this)-}--/**- * 数字格式化- * @param pattern 格式- * @return 返回格式化后的字符串- */-fun Float.format(pattern: String): String {- if (pattern.isEmpty()) {- return this.toString()- }- return DecimalFormat(pattern).format(this)-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/IdCardMatchUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/IdCardMatchUtils.ktdeleted file mode 100755index 5aca8bc..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/IdCardMatchUtils.kt+++ /dev/null@@ -1,28 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import com.orhanobut.logger.Logger-import java.util.regex.Matcher-import java.util.regex.Pattern--const val idCardNumberRegex =- "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}\$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)\$"---fun getMatchIdCardNumberStr(text: String): String? {- val matchALL = Regex(idCardNumberRegex).find(text)- if (matchALL != null) {- Logger.i("match结果 matchALL:${matchALL.value}")- return matchALL.value- }- return null-}--fun String.trimSymbols(): String {- var dest = ""- if (this.isNotEmpty()) {- val p: Pattern = Pattern.compile("\\p{P}|\\p{S}")- val m: Matcher = p.matcher(this)- dest = m.replaceAll("")- }- return dest-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ImeiMatchUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ImeiMatchUtils.ktdeleted file mode 100755index f59cd35..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ImeiMatchUtils.kt+++ /dev/null@@ -1,26 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import com.orhanobut.logger.Logger-import java.util.regex.Matcher-import java.util.regex.Pattern--const val imeiRegex = "\\d{15}|\\d{17}"--fun getMatchImeiStr(text: String): String? {- val matchALL = Regex(imeiRegex).find(text)- if (matchALL != null) {- Logger.i("match结果 matchALL:${matchALL.value}")- return matchALL.value- }- return null-}--fun String.replaceBlank(): String {- var dest = ""- if (this.isNotEmpty()) {- val p: Pattern = Pattern.compile("\\s*|\t|\r|\n")- val m: Matcher = p.matcher(this)- dest = m.replaceAll("")- }- return dest-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/PlateMatchUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/PlateMatchUtils.ktdeleted file mode 100755index de22004..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/PlateMatchUtils.kt+++ /dev/null@@ -1,26 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import com.orhanobut.logger.Logger-import java.util.regex.Matcher-import java.util.regex.Pattern--const val plateRegex = "^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))\$"--fun getMatchPlateStr(text: String): String? {- val matchALL = Regex(plateRegex).find(text)- if (matchALL != null) {- Logger.i("match结果 matchALL:${matchALL.value}")- return matchALL.value- }- return null-}--fun String.trimBlankAndSymbols(): String {- var dest = ""- if (this.isNotEmpty()) {- val p: Pattern = Pattern.compile("\\p{P}|\\p{S}|\\s*|\t|\r|\n")- val m: Matcher = p.matcher(this)- dest = m.replaceAll("")- }- return dest-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/RecyclerViewUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/RecyclerViewUtils.ktdeleted file mode 100755index 48f408d..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/RecyclerViewUtils.kt+++ /dev/null@@ -1,98 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import android.content.Context-import android.graphics.Canvas-import android.graphics.Color-import android.graphics.Paint-import android.graphics.Rect-import android.view.View-import androidx.recyclerview.widget.LinearLayoutManager-import androidx.recyclerview.widget.RecyclerView--/**- * 设置RecyclerView的item四周间距- * @param left 左边距- * @param top 上边距- * @param right 右边距- * @param bottom 底边距- */-fun RecyclerView.setMarginItemDecoration(left: Int, top: Int, right: Int, bottom: Int) {- addItemDecoration(object : RecyclerView.ItemDecoration() {- override fun getItemOffsets(- outRect: Rect,- view: View,- parent: RecyclerView,- state: RecyclerView.State- ) {- //设置item间距- outRect.left = dp2px(context, left)- outRect.top = dp2px(context, top)- outRect.right = dp2px(context, right)- outRect.bottom = dp2px(context, bottom)- }- })-}--/**- * 设置RecyclerView的item四周间距,并在item底部画分隔符- * @param left 左边距- * @param top 上边距- * @param right 右边距- * @param bottom 底边距- */-fun RecyclerView.setItemDecorationAndDrawBottom(- left: Int, top: Int, right: Int, bottom: Int,- bottomLine: Int-) {- addItemDecoration(object : RecyclerView.ItemDecoration() {- override fun getItemOffsets(- outRect: Rect,- view: View,- parent: RecyclerView,- state: RecyclerView.State- ) {- //设置item间距- outRect.left = dp2px(context,left)- outRect.top = dp2px(context,top)- outRect.right = dp2px(context,right)- outRect.bottom = dp2px(context,bottom)- }-- override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {- super.onDraw(canvas, parent, state)- //分隔符- val paint = Paint()- paint.color = Color.GRAY-- val left = parent.paddingLeft //不可以修改left等变量名,否则item底色会变成灰色- val right = parent.measuredWidth - parent.paddingRight- val childSize = parent.childCount- for (i in 0 until childSize) {- val child = parent.getChildAt(i)- val layoutParams = child.layoutParams as RecyclerView.LayoutParams- val top = child.bottom + layoutParams.bottomMargin- val bottom = top + dp2px(context,bottomLine)- canvas.drawRect(- left.toFloat(), top.toFloat(),- right.toFloat(), bottom.toFloat(), paint- )- }- }- })-}--fun RecyclerView.scrollToTop() {- val layoutManager = this.layoutManager as LinearLayoutManager?- layoutManager?.scrollToPositionWithOffset(0, 0)-}--fun RecyclerView.scrollToBottom() {- val layoutManager = this.layoutManager as LinearLayoutManager?- val itemCount = this.adapter?.itemCount ?: 0- layoutManager?.scrollToPositionWithOffset(itemCount - 1, 0)-}--private fun dp2px(context: Context, value: Int): Int {- val scale = context.resources.displayMetrics.density- return (value.toFloat() * scale + 0.5f).toInt()-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/SoftInputUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/SoftInputUtils.ktdeleted file mode 100755index 6c78c45..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/SoftInputUtils.kt+++ /dev/null@@ -1,35 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import android.content.Context-import android.view.View-import android.view.inputmethod.InputMethodManager-import android.widget.EditText-import androidx.fragment.app.Fragment--/**- * 显示软建键盘- */-fun EditText.showSoftInput(){- requestFocus()- setSelection(text.toString().length)//将光标移至文字末尾- val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager- imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)-}--/**- * 隐藏软键盘- */-fun Fragment.hideSoftInput() {- val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager- imm.hideSoftInputFromWindow(view?.windowToken, 0)-}--/**- * 动态隐藏软键盘- *- * @param view 视图- */-fun View.hideSoftInput() {- val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager- imm.hideSoftInputFromWindow(windowToken, 0)-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ToastUtils.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ToastUtils.ktdeleted file mode 100755index 4113c16..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/utils/ToastUtils.kt+++ /dev/null@@ -1,47 +0,0 @@-package com.benjaminwan.ocr.onnx.utils--import android.app.Activity-import android.content.Context-import android.widget.Toast-import androidx.annotation.StringRes-import androidx.fragment.app.Fragment--fun Context.showToast(msg: CharSequence, duration: Int = Toast.LENGTH_SHORT) {- Toast.makeText(this, msg, duration).show()-}--fun Context.showToast(@StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {- Toast.makeText(this, resId, duration).show()-}--/**- * 显示Toast- * @param msg- */-fun Activity.showToast(msg: CharSequence, duration: Int = Toast.LENGTH_SHORT) {- applicationContext.showToast(msg, duration)-}--/**- * 显示Toast- * @param msg- */-fun Activity.showToast(@StringRes msg: Int, duration: Int = Toast.LENGTH_SHORT) {- applicationContext.showToast(msg, duration)-}--/**- * 显示Toast- * @param msg- */-fun Fragment.showToast(msg: CharSequence, duration: Int = Toast.LENGTH_SHORT) {- requireActivity().applicationContext.showToast(msg, duration)-}--/**- * 显示Toast- * @param msg- */-fun Fragment.showToast(@StringRes msg: Int, duration: Int = Toast.LENGTH_SHORT) {- requireActivity().applicationContext.showToast(msg, duration)-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_down.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_down.xmldeleted file mode 100755index 2f0cfd2..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_down.xml+++ /dev/null@@ -1,12 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <translate- android:duration="@android:integer/config_mediumAnimTime"- android:fromYDelta="0%p"- android:toYDelta="100%p" />-- <alpha- android:duration="@android:integer/config_mediumAnimTime"- android:fromAlpha="1.0"- android:toAlpha="0.3" />-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_up.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_up.xmldeleted file mode 100755index 51fe057..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_close_up.xml+++ /dev/null@@ -1,12 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <translate- android:duration="@android:integer/config_mediumAnimTime"- android:fromYDelta="0%p"- android:toYDelta="-100%p" />-- <alpha- android:duration="@android:integer/config_mediumAnimTime"- android:fromAlpha="1.0"- android:toAlpha="0.3" />-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_enter_anim.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_enter_anim.xmldeleted file mode 100755index a9a6feb..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_enter_anim.xml+++ /dev/null@@ -1,13 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <scale- android:interpolator="@android:anim/accelerate_interpolator"- android:fromXScale="1.0"- android:toXScale="1.0"- android:fromYScale="0.0"- android:toYScale="1.0"- android:pivotX="0%"- android:pivotY="100%"- android:fillAfter="false"- android:duration="@android:integer/config_mediumAnimTime"/>-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_exit_anim.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_exit_anim.xmldeleted file mode 100755index cb951ee..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_exit_anim.xml+++ /dev/null@@ -1,13 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <scale- android:interpolator="@android:anim/accelerate_interpolator"- android:fromXScale="1.0"- android:toXScale="1.0"- android:fromYScale="1.0"- android:toYScale="0.0"- android:pivotX="0%"- android:pivotY="100%"- android:fillAfter="false"- android:duration="@android:integer/config_mediumAnimTime"/>-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_in.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_in.xmldeleted file mode 100755index 1403901..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_in.xml+++ /dev/null@@ -1,7 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<alpha xmlns:android="http://schemas.android.com/apk/res/android"- android:duration="@android:integer/config_mediumAnimTime"- android:fillAfter="true"- android:fillEnabled="true"- android:fromAlpha="0.0"- android:toAlpha="1.0" />\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_out.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_out.xmldeleted file mode 100755index cfcd0ca..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_fade_out.xml+++ /dev/null@@ -1,7 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<alpha xmlns:android="http://schemas.android.com/apk/res/android"- android:duration="@android:integer/config_mediumAnimTime"- android:fillAfter="true"- android:fillEnabled="true"- android:fromAlpha="1.0"- android:toAlpha="0.0" />\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_down.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_down.xmldeleted file mode 100755index b6f069a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_down.xml+++ /dev/null@@ -1,12 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <translate- android:duration="@android:integer/config_mediumAnimTime"- android:fromYDelta="-100%p"- android:toYDelta="0%p" />-- <alpha- android:duration="@android:integer/config_mediumAnimTime"- android:fromAlpha="0.0"- android:toAlpha="1.0" />-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_up.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_up.xmldeleted file mode 100755index 03e6d4a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/anim/window_show_up.xml+++ /dev/null@@ -1,12 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<set xmlns:android="http://schemas.android.com/apk/res/android">- <translate- android:duration="@android:integer/config_mediumAnimTime"- android:fromYDelta="100%p"- android:toYDelta="0%p" />-- <alpha- android:duration="@android:integer/config_mediumAnimTime"- android:fromAlpha="0.0"- android:toAlpha="1.0" />-</set>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue3_to_blue5.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue3_to_blue5.xmldeleted file mode 100755index b08f40a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue3_to_blue5.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@color/material_blue_300"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@color/material_blue_300"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_blue_500"- />- <item- android:state_enabled="false"- android:color="@color/material_blue_200"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue5_to_blue7.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue5_to_blue7.xmldeleted file mode 100755index 56eb7b9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_blue5_to_blue7.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@color/material_blue_500"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@color/material_blue_500"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_blue_700"- />- <item- android:state_enabled="false"- android:color="@color/material_grey_300"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey3_to_grey5.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey3_to_grey5.xmldeleted file mode 100755index b7b522d..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey3_to_grey5.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@color/material_grey_300"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@color/material_grey_300"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_grey_500"- />- <item- android:state_enabled="false"- android:color="@color/material_grey_200"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey5_to_grey7.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey5_to_grey7.xmldeleted file mode 100755index 37fa8d2..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_grey5_to_grey7.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@color/material_grey_500"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@color/material_grey_500"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_grey_700"- />- <item- android:state_enabled="false"- android:color="@color/material_grey_200"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_pink5_to_pink7.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_pink5_to_pink7.xmldeleted file mode 100755index b9d511f..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_pink5_to_pink7.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@color/material_pink_500"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@color/material_pink_500"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_pink_700"- />- <item- android:state_enabled="false"- android:color="@color/material_grey_300"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_white_to_grey.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_white_to_grey.xmldeleted file mode 100755index c906c2b..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/color/btn_white_to_grey.xml+++ /dev/null@@ -1,24 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_checked="true"- android:state_pressed="false"- android:color="@android:color/white"- />- <item- android:state_enabled="true"- android:state_checked="false"- android:state_pressed="false"- android:color="@android:color/white"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:color="@color/material_grey_500"- />- <item- android:state_enabled="false"- android:color="@color/material_grey_600"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable-v24/ic_launcher_foreground.xmldeleted file mode 100755index 2b068d1..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable-v24/ic_launcher_foreground.xml+++ /dev/null@@ -1,30 +0,0 @@-<vector xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:aapt="http://schemas.android.com/aapt"- android:width="108dp"- android:height="108dp"- android:viewportWidth="108"- android:viewportHeight="108">- <path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">- <aapt:attr name="android:fillColor">- <gradient- android:endX="85.84757"- android:endY="92.4963"- android:startX="42.9492"- android:startY="49.59793"- android:type="linear">- <item- android:color="#44000000"- android:offset="0.0" />- <item- android:color="#00000000"- android:offset="1.0" />- </gradient>- </aapt:attr>- </path>- <path- android:fillColor="#FFFFFF"- android:fillType="nonZero"- android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"- android:strokeWidth="1"- android:strokeColor="#00000000" />-</vector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue3_to_blue5.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue3_to_blue5.xmldeleted file mode 100755index 64b5a2d..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue3_to_blue5.xml+++ /dev/null@@ -1,18 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector- xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_pressed="false"- android:drawable="@color/material_blue_300"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:drawable="@color/material_blue_500"- />- <item- android:state_enabled="false"- android:drawable="@color/material_grey_300"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue5_to_blue7.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue5_to_blue7.xmldeleted file mode 100755index 54f190c..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_blue5_to_blue7.xml+++ /dev/null@@ -1,17 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item- android:state_enabled="true"- android:state_pressed="false"- android:drawable="@color/material_blue_500"- />- <item- android:state_enabled="true"- android:state_pressed="true"- android:drawable="@color/material_blue_700"- />- <item- android:state_enabled="false"- android:drawable="@color/material_grey_300"- />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext.xmldeleted file mode 100755index 8db591c..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext.xml+++ /dev/null@@ -1,5 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">- <item android:state_window_focused="false" android:drawable="@drawable/bg_edittext_normal" />- <item android:state_focused="true" android:drawable="@drawable/bg_edittext_focused" />-</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_focused.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_focused.xmldeleted file mode 100755index 06e3e71..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_focused.xml+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<shape xmlns:android="http://schemas.android.com/apk/res/android">- <solid android:color="#FFFFFF" />- <corners android:radius="2dp"/>- <stroke- android:width="1dp"- android:color="#728ea3" />-</shape>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_normal.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_normal.xmldeleted file mode 100755index c162fb5..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_edittext_normal.xml+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<shape xmlns:android="http://schemas.android.com/apk/res/android">- <solid android:color="#FFFFFF" />- <corners android:radius="2dp"/>- <stroke- android:width="1dp"- android:color="#BDC7D8" />-</shape>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_transparent_to_transparent_half.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_transparent_to_transparent_half.xmldeleted file mode 100755index 3955426..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/bg_transparent_to_transparent_half.xml+++ /dev/null@@ -1,12 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<selector xmlns:android="http://schemas.android.com/apk/res/android">-- <item android:state_pressed="true">- <shape>- <corners android:radius="0dp" />- <solid android:color="@color/transparent_half_1" />- </shape>- </item>- <item android:drawable="@color/transparent" />--</selector>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_close.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_close.xmldeleted file mode 100755index 941f02e..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_close.xml+++ /dev/null@@ -1,10 +0,0 @@-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:height="200dp"- android:viewportHeight="1024"- android:viewportWidth="1024"- android:width="200dp">- <path android:fillColor="#FF000000"- android:pathData="M510.87,63.4c-247.33,0 -447.87,200.51 -447.87,447.87 0,247.33 200.54,447.87 447.87,447.87 247.36,0 447.87,-200.53 447.87,-447.87C958.74,263.91 758.23,63.4 510.87,63.4zM510.87,903.15c-216.42,0 -391.88,-175.47 -391.88,-391.88 0,-216.44 175.47,-391.88 391.88,-391.88 216.44,0 391.88,175.44 391.88,391.88C902.75,727.69 727.31,903.15 510.87,903.15z"/>- <path android:fillColor="#FF000000"- android:pathData="M640.09,333.12 L501.54,471.67 362.98,333.12 323.4,372.71 461.95,511.26 323.4,649.81 362.98,689.41 501.54,550.86 640.09,689.41 679.69,649.81 541.14,511.26 679.69,372.71Z"/>-</vector>diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_launcher_background.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_launcher_background.xmldeleted file mode 100755index 07d5da9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_launcher_background.xml+++ /dev/null@@ -1,170 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="108dp"- android:height="108dp"- android:viewportWidth="108"- android:viewportHeight="108">- <path- android:fillColor="#3DDC84"- android:pathData="M0,0h108v108h-108z" />- <path- android:fillColor="#00000000"- android:pathData="M9,0L9,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,0L19,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M29,0L29,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M39,0L39,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M49,0L49,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M59,0L59,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M69,0L69,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M79,0L79,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M89,0L89,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M99,0L99,108"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,9L108,9"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,19L108,19"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,29L108,29"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,39L108,39"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,49L108,49"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,59L108,59"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,69L108,69"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,79L108,79"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,89L108,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M0,99L108,99"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,29L89,29"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,39L89,39"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,49L89,49"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,59L89,59"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,69L89,69"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M19,79L89,79"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M29,19L29,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M39,19L39,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M49,19L49,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M59,19L59,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M69,19L69,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />- <path- android:fillColor="#00000000"- android:pathData="M79,19L79,89"- android:strokeWidth="0.8"- android:strokeColor="#33FFFFFF" />-</vector>diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_loading.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_loading.xmldeleted file mode 100755index f5fe962..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_loading.xml+++ /dev/null@@ -1,16 +0,0 @@-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="40dp"- android:height="40dp"- android:viewportWidth="40"- android:viewportHeight="40">-- <path- android:fillColor="#229EF8"- android:fillAlpha="0.2"- android:strokeAlpha="0.2"- android:strokeWidth="1"- android:pathData="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z" />- <path- android:fillColor="#03A9F4"- android:pathData="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z" />-</vector>diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_ocr.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_ocr.xmldeleted file mode 100755index 306b3b2..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/ic_ocr.xml+++ /dev/null@@ -1,15 +0,0 @@-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="128dp"- android:height="128dp"- android:viewportWidth="1024"- android:viewportHeight="1024">- <path- android:pathData="M0,0m85.33,0l853.33,0q85.33,0 85.33,85.33l0,853.33q0,85.33 -85.33,85.33l-853.33,0q-85.33,0 -85.33,-85.33l0,-853.33q0,-85.33 85.33,-85.33Z"- android:fillColor="#68882d"/>- <path- android:pathData="M855.17,586.24c17.49,0 31.74,13.91 32.3,31.32v190.85a79.1,79.1 0,0 1,-77.7 79.06h-168.79a32.3,32.3 0,0 1,-1.02 -64.6h168.41a14.51,14.51 0,0 0,14.51 -13.74v-190.59c0,-17.83 14.46,-32.3 32.3,-32.3zM168.83,585.47c17.49,0 31.74,13.91 32.3,31.27v191.62c0,7.77 6.06,14.08 13.74,14.51L370.35,822.87a32.3,32.3 0,0 1,1.02 64.6L215.64,887.47A79.1,79.1 0,0 1,136.53 809.77v-192c0,-17.83 14.46,-32.3 32.3,-32.3zM370.13,136.53a32.3,32.3 0,0 1,0.98 64.6L215.64,201.13a14.51,14.51 0,0 0,-14.51 13.74L201.13,385.11A32.3,32.3 0,0 1,136.53 386.13L136.53,215.64c0,-43.22 34.69,-78.38 77.7,-79.1h155.86zM808.36,136.53c43.22,0 78.38,34.69 79.1,77.7L887.47,381.91a32.3,32.3 0,0 1,-64.6 1.02L822.87,215.64a14.51,14.51 0,0 0,-13.74 -14.51h-169.86a32.3,32.3 0,0 1,-1.02 -64.6h170.11z"- android:fillColor="#FFFFFF"/>- <path- android:pathData="M310.83,396.8c60.59,0 101.76,41.47 101.76,114.01 0,72.83 -41.17,116.39 -101.76,116.39S209.07,583.64 209.07,510.81c0,-72.83 41.17,-114.01 101.76,-114.01zM542.12,396.8c28.97,0 52.22,13.44 67.46,28.93l-28.03,34.05c-11.09,-10.15 -22.7,-17.32 -38.53,-17.32 -28.63,0 -52.22,25.69 -52.22,68.95 0,44.16 20.31,69.85 51.63,69.85 17.62,0 31.96,-8.96 42.37,-20.31l28.07,33.45c-18.77,21.76 -43.56,32.81 -72.53,32.81 -56.41,0 -104.11,-38.83 -104.11,-114.01 0,-74.03 49.49,-116.39 105.9,-116.39zM719.4,400.98c47.45,0 86.87,16.13 86.87,69.85 0,32.51 -15.23,53.42 -38.23,64.17l49.54,88.02h-59.69l-40.87,-78.21h-25.64v78.21h-53.42L637.95,400.98h81.49zM310.83,442.45c-29.23,0 -47.15,25.39 -47.15,68.35 0,43.26 17.92,70.4 47.15,70.4 29.27,0 47.45,-27.14 47.45,-70.4 0,-42.97 -18.18,-68.35 -47.45,-68.35zM715.22,443.05h-23.89v59.73h23.89c25.39,0 38.83,-11.09 38.83,-32 0,-20.86 -13.44,-27.73 -38.83,-27.73z"- android:fillColor="#FFFFFF"/>-</vector>diff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/loading_anim.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/loading_anim.xmldeleted file mode 100755index 4f22ba4..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/drawable/loading_anim.xml+++ /dev/null@@ -1,10 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"- android:drawable="@drawable/ic_loading"- android:duration="200"- android:fromDegrees="0.0"- android:interpolator="@android:anim/accelerate_decelerate_interpolator"- android:pivotX="50.0%"- android:pivotY="50.0%"- android:repeatMode="restart"- android:toDegrees="360"/>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_camera.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_camera.xmldeleted file mode 100755index 541e4d8..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_camera.xml+++ /dev/null@@ -1,198 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:orientation="vertical"- tools:context=".MainActivity">-- <RelativeLayout- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_weight="1">-- <androidx.camera.view.PreviewView- android:id="@+id/viewFinder"- android:layout_width="match_parent"- android:layout_height="match_parent"- app:scaleType="fillCenter" />-- <jsc.kit.cameramask.CameraLensView- android:id="@+id/cameraLensView"- android:layout_width="match_parent"- android:layout_height="match_parent"- app:clvCameraLensGravity="center"- app:clvCameraLensHeightWeight="{9,10}"- app:clvCameraLensShape="rectangle"- app:clvCameraLensTopMargin="0dp"- app:clvCameraLensWidthWeight="{9,10}"- app:clvShowBoxAngle="true"- app:clvText="请把要识别的内容对准扫描框"- app:clvTextLocation="belowCameraLens"- app:clvTextMathParent="true"- app:clvTextSize="12sp"- app:clvTextVerticalMargin="6dp" />-- <ImageView- android:id="@+id/loadingImg"- android:layout_width="match_parent"- android:layout_height="match_parent" />-- </RelativeLayout>-- <TextView- android:id="@+id/timeTV"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:hint="识别时间:"- android:paddingLeft="8dp"- android:paddingRight="8dp"- android:textSize="12sp" />-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/maxSideLenTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="MaxSideLen:0(100%)" />-- <SeekBar- android:id="@+id/maxSideLenSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="10"- android:progress="100" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/paddingTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="padding:0" />-- <SeekBar- android:id="@+id/paddingSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="0"- android:progress="0" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/boxScoreThreshTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="@string/box_score_thresh" />-- <SeekBar- android:id="@+id/boxScoreThreshSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="1"- android:progress="50" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/boxThreshTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="BoxThresh:0.3" />-- <SeekBar- android:id="@+id/boxThreshSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="1"- android:progress="30" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/unClipRatioTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="@string/box_un_clip_ratio" />-- <SeekBar- android:id="@+id/scaleUnClipRatioSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="30"- android:min="10"- android:progress="20" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_marginBottom="2dp"- android:orientation="horizontal">-- <Button- android:id="@+id/clearBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="清除"- android:textSize="12sp" />-- <Button- android:id="@+id/detectBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="识别"- android:textSize="12sp" />-- <Button- android:id="@+id/resultBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="识别结果"- android:textSize="12sp" />-- <Button- android:id="@+id/debugBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="调试信息"- android:textSize="12sp" />- </LinearLayout>---</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_gallery.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_gallery.xmldeleted file mode 100755index 654ffc1..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_gallery.xml+++ /dev/null@@ -1,224 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:orientation="vertical"- tools:context=".MainActivity">-- <com.github.chrisbanes.photoview.PhotoView- android:id="@+id/imageView"- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_weight="1" />-- <TextView- android:id="@+id/timeTV"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:hint="识别时间:"- android:paddingLeft="8dp"- android:paddingRight="8dp"- android:textSize="12sp" />-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/maxSideLenTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="MaxSideLen:0(100%)" />-- <SeekBar- android:id="@+id/maxSideLenSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="10"- android:progress="100" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/paddingTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="padding:0" />-- <SeekBar- android:id="@+id/paddingSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="0"- android:progress="0" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/boxScoreThreshTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="@string/box_score_thresh" />-- <SeekBar- android:id="@+id/boxScoreThreshSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="1"- android:progress="50" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/boxThreshTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="BoxThresh:0.3" />-- <SeekBar- android:id="@+id/boxThreshSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="100"- android:min="1"- android:progress="30" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:id="@+id/unClipRatioTv"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="@string/box_un_clip_ratio" />-- <SeekBar- android:id="@+id/scaleUnClipRatioSeekBar"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:max="30"- android:min="10"- android:progress="20" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="@string/do_angle" />-- <Switch- android:id="@+id/doAngleSw"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:checked="true"- android:textOff="Off"- android:textOn="On" />-- <TextView- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_marginStart="5dp"- android:text="角度投票" />-- <Switch- android:id="@+id/mostAngleSw"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:checked="true"- android:textOff="Off"- android:textOn="On" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="32dp"- android:orientation="horizontal">-- <TextView- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="选中一张图片测试取平均耗时" />-- <Button- android:id="@+id/benchBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="测试"- android:textSize="12sp" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_marginBottom="2dp"- android:orientation="horizontal">-- <Button- android:id="@+id/selectBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="选图"- android:textSize="12sp" />-- <Button- android:id="@+id/detectBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="识别"- android:textSize="12sp" />-- <Button- android:id="@+id/resultBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="识别结果"- android:textSize="12sp" />-- <Button- android:id="@+id/debugBtn"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="调试信息"- android:textSize="12sp" />- </LinearLayout>---</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_idcard_front.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_idcard_front.xmldeleted file mode 100755index 7509e3f..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_idcard_front.xml+++ /dev/null@@ -1,353 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:keepScreenOn="true"- android:layoutDirection="ltr"- tools:context=".ui.CmiitActivity">-- <androidx.camera.view.PreviewView- android:id="@+id/viewFinder"- android:layout_width="match_parent"- android:layout_height="0dp"- app:layout_constraintDimensionRatio="h,856:540"- app:layout_constraintTop_toTopOf="parent"- app:scaleType="fillCenter" />-- <com.mywork.idcardview.IdCardFrontView- android:id="@+id/idCardFrontView"- android:layout_width="match_parent"- android:layout_height="0dp"- app:AddressHeight="155"- app:AddressLeft="60"- app:AddressTop="260"- app:AddressWidth="465"- app:BirthHeight="60"- app:BirthLeft="60"- app:BirthTop="195"- app:BirthWidth="400"- app:BoxBorderColor="@color/material_light_green_A400"- app:BoxBorderWidth="1dp"- app:CalcHeight="540"- app:CalcWidth="856"- app:GenderHeight="60"- app:GenderLeft="60"- app:GenderTop="130"- app:GenderWidth="170"- app:HeadHeight="320"- app:HeadLeft="530"- app:HeadTop="80"- app:HeadWidth="260"- app:NameHeight="65"- app:NameLeft="60"- app:NameTop="60"- app:NameWidth="400"- app:NationHeight="60"- app:NationLeft="230"- app:NationTop="130"- app:NationWidth="230"- app:NumberHeight="70"- app:NumberLeft="60"- app:NumberTop="420"- app:NumberWidth="710"- app:layout_constraintBottom_toBottomOf="@+id/viewFinder"- app:layout_constraintDimensionRatio="h,856:540"- app:layout_constraintTop_toTopOf="parent"- app:showBox="true" />--- <androidx.core.widget.NestedScrollView- android:layout_width="match_parent"- android:layout_height="0dp"- android:orientation="vertical"- app:layout_constraintBottom_toTopOf="@+id/controlLayout"- app:layout_constraintTop_toBottomOf="@+id/viewFinder">-- <LinearLayout- android:id="@+id/resultLayout"- android:layout_width="match_parent"- android:layout_height="0dp"- android:orientation="vertical"- app:layout_constraintBottom_toTopOf="@+id/controlLayout"- app:layout_constraintTop_toBottomOf="@+id/viewFinder">-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="姓名: "- android:textSize="18sp" />-- <EditText- android:id="@+id/nameEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp" />-- <ImageButton- android:id="@+id/clearNameBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="性别: "- android:textSize="18sp" />-- <EditText- android:id="@+id/genderEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp" />-- <ImageButton- android:id="@+id/clearGenderBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="民族: "- android:textSize="18sp" />-- <EditText- android:id="@+id/nationEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp" />-- <ImageButton- android:id="@+id/clearNationBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="出生: "- android:textSize="18sp" />-- <EditText- android:id="@+id/birthDateEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp" />-- <ImageButton- android:id="@+id/clearBirthBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="住址: "- android:textSize="18sp" />-- <EditText- android:id="@+id/addressEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:lines="3"- android:maxLines="3"- android:text=""- android:textSize="12sp" />-- <ImageButton- android:id="@+id/clearAddressBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:gravity="center_vertical"- android:text="号码: "- android:textSize="18sp" />-- <EditText- android:id="@+id/numberEdit"- android:layout_width="0dp"- android:layout_height="match_parent"- android:layout_marginStart="2dp"- android:layout_marginEnd="2dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp" />-- <ImageButton- android:id="@+id/clearNumberBtn"- android:layout_width="38dp"- android:layout_height="38dp"- android:layout_marginEnd="2dp"- android:background="@android:color/transparent"- android:padding="4dp"- android:scaleType="centerInside"- android:src="@drawable/ic_close"- app:tint="@color/btn_blue5_to_blue7" />-- </LinearLayout>-- </LinearLayout>-- </androidx.core.widget.NestedScrollView>--- <LinearLayout- android:id="@+id/controlLayout"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- app:layout_constraintBottom_toBottomOf="parent">-- <Button- android:id="@+id/startBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_margin="2dp"- android:layout_weight="1"- android:background="@drawable/bg_blue3_to_blue5"- android:text="开始识别"- android:textColor="@android:color/white"- android:textSize="16sp" />-- <Button- android:id="@+id/stopBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_margin="2dp"- android:layout_weight="1"- android:background="@drawable/bg_blue3_to_blue5"- android:text="停止识别"- android:textColor="@android:color/white"- android:textSize="16sp" />- </LinearLayout>--</androidx.constraintlayout.widget.ConstraintLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_imei.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_imei.xmldeleted file mode 100755index e428500..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_imei.xml+++ /dev/null@@ -1,108 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:keepScreenOn="true"- android:layoutDirection="ltr"- tools:context=".ImeiActivity">-- <androidx.camera.view.PreviewView- android:id="@+id/viewFinder"- android:layout_width="match_parent"- android:layout_height="0dp"- app:layout_constraintBottom_toTopOf="@+id/startBtn"- app:layout_constraintTop_toTopOf="parent"- app:scaleType="fillCenter" />-- <jsc.kit.cameramask.CameraLensView- android:id="@+id/cameraLensView"- android:layout_width="match_parent"- android:layout_height="0dp"- app:clvCameraLensGravity="center"- app:clvCameraLensHeightWeight="{1,15}"- app:clvCameraLensShape="rectangle"- app:clvCameraLensTopMargin="-80dp"- app:clvCameraLensWidthWeight="{5,6}"- app:clvShowBoxAngle="true"- app:clvText="请把IMEI号码对准镜头扫描框"- app:clvTextLocation="belowCameraLens"- app:clvTextMathParent="true"- app:clvTextSize="16sp"- app:clvTextVerticalMargin="10dp"- app:layout_constraintBottom_toBottomOf="@+id/viewFinder"- app:layout_constraintTop_toTopOf="parent" />-- <Button- android:id="@+id/startBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_marginStart="2dp"- android:layout_marginTop="2dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="8dp"- android:background="@drawable/bg_blue3_to_blue5"- android:text="开始识别"- android:textColor="@android:color/white"- android:textSize="16sp"- app:layout_constraintBottom_toTopOf="@+id/resultText"- app:layout_constraintEnd_toStartOf="@+id/stopBtn"- app:layout_constraintHorizontal_weight="1"- app:layout_constraintStart_toStartOf="parent"- app:layout_constraintTop_toBottomOf="@+id/viewFinder" />-- <Button- android:id="@+id/stopBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_marginStart="2dp"- android:layout_marginTop="2dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="8dp"- android:background="@drawable/bg_blue3_to_blue5"- android:text="停止识别"- android:textColor="@android:color/white"- android:textSize="16sp"- app:layout_constraintBaseline_toBaselineOf="@+id/startBtn"- app:layout_constraintBottom_toTopOf="@+id/resultText"- app:layout_constraintEnd_toEndOf="parent"- app:layout_constraintHorizontal_weight="1"- app:layout_constraintStart_toEndOf="@+id/startBtn"- app:layout_constraintTop_toBottomOf="@+id/viewFinder" />-- <TextView- android:id="@+id/resultText"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_marginStart="2dp"- android:layout_marginTop="8dp"- android:layout_marginBottom="16dp"- android:gravity="center_vertical"- android:text="识别结果: "- android:textSize="18sp"- app:layout_constraintBottom_toBottomOf="parent"- app:layout_constraintEnd_toStartOf="@+id/resultEdit"- app:layout_constraintStart_toStartOf="parent"- app:layout_constraintTop_toBottomOf="@+id/startBtn" />-- <EditText- android:id="@+id/resultEdit"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_marginStart="2dp"- android:layout_marginTop="8dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="16dp"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp"- app:layout_constraintBaseline_toBaselineOf="@+id/resultText"- app:layout_constraintBottom_toBottomOf="parent"- app:layout_constraintEnd_toEndOf="parent"- app:layout_constraintStart_toEndOf="@+id/resultText"- app:layout_constraintTop_toBottomOf="@+id/startBtn" />--</androidx.constraintlayout.widget.ConstraintLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_main.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_main.xmldeleted file mode 100755index f7b1f59..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_main.xml+++ /dev/null@@ -1,40 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:orientation="vertical"- tools:context=".MainActivity">-- <Button- android:id="@+id/galleryBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:text="相册识别" />-- <Button- android:id="@+id/cameraBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:text="相机识别" />-- <Button- android:id="@+id/imeiBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:text="手机IMEI号识别" />-- <Button- android:id="@+id/plateBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:text="车牌识别" />-- <Button- android:id="@+id/idCardBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:text="身份证人像面识别" />--</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_plate.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_plate.xmldeleted file mode 100755index 2c2a86a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/activity_plate.xml+++ /dev/null@@ -1,108 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- xmlns:tools="http://schemas.android.com/tools"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:keepScreenOn="true"- android:layoutDirection="ltr"- tools:context=".ImeiActivity">-- <androidx.camera.view.PreviewView- android:id="@+id/viewFinder"- android:layout_width="match_parent"- android:layout_height="0dp"- app:layout_constraintBottom_toTopOf="@+id/startBtn"- app:layout_constraintTop_toTopOf="parent"- app:scaleType="fillCenter" />-- <jsc.kit.cameramask.CameraLensView- android:id="@+id/cameraLensView"- android:layout_width="match_parent"- android:layout_height="0dp"- app:clvCameraLensGravity="center"- app:clvCameraLensHeightWeight="{1,5}"- app:clvCameraLensShape="rectangle"- app:clvCameraLensTopMargin="-80dp"- app:clvCameraLensWidthWeight="{5,6}"- app:clvShowBoxAngle="true"- app:clvText="请把车牌对准镜头扫描框"- app:clvTextLocation="belowCameraLens"- app:clvTextMathParent="true"- app:clvTextSize="16sp"- app:clvTextVerticalMargin="10dp"- app:layout_constraintBottom_toBottomOf="@+id/viewFinder"- app:layout_constraintTop_toTopOf="parent" />-- <Button- android:id="@+id/startBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_marginStart="2dp"- android:layout_marginTop="2dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="8dp"- android:background="@drawable/bg_blue3_to_blue5"- android:text="开始识别"- android:textColor="@android:color/white"- android:textSize="16sp"- app:layout_constraintBottom_toTopOf="@+id/resultText"- app:layout_constraintEnd_toStartOf="@+id/stopBtn"- app:layout_constraintHorizontal_weight="1"- app:layout_constraintStart_toStartOf="parent"- app:layout_constraintTop_toBottomOf="@+id/viewFinder" />-- <Button- android:id="@+id/stopBtn"- android:layout_width="0dp"- android:layout_height="40dp"- android:layout_marginStart="2dp"- android:layout_marginTop="2dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="8dp"- android:background="@drawable/bg_blue3_to_blue5"- android:text="停止识别"- android:textColor="@android:color/white"- android:textSize="16sp"- app:layout_constraintBaseline_toBaselineOf="@+id/startBtn"- app:layout_constraintBottom_toTopOf="@+id/resultText"- app:layout_constraintEnd_toEndOf="parent"- app:layout_constraintHorizontal_weight="1"- app:layout_constraintStart_toEndOf="@+id/startBtn"- app:layout_constraintTop_toBottomOf="@+id/viewFinder" />-- <TextView- android:id="@+id/resultText"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_marginStart="2dp"- android:layout_marginTop="8dp"- android:layout_marginBottom="16dp"- android:gravity="center_vertical"- android:text="识别结果: "- android:textSize="18sp"- app:layout_constraintBottom_toBottomOf="parent"- app:layout_constraintEnd_toStartOf="@+id/resultEdit"- app:layout_constraintStart_toStartOf="parent"- app:layout_constraintTop_toBottomOf="@+id/startBtn" />-- <EditText- android:id="@+id/resultEdit"- android:layout_width="0dp"- android:layout_height="wrap_content"- android:layout_marginStart="2dp"- android:layout_marginTop="8dp"- android:layout_marginEnd="2dp"- android:layout_marginBottom="16dp"- android:background="@drawable/bg_edittext"- android:gravity="start|center_vertical"- android:hint="请编辑内容"- android:text=""- android:textSize="18sp"- app:layout_constraintBaseline_toBaselineOf="@+id/resultText"- app:layout_constraintBottom_toBottomOf="parent"- app:layout_constraintEnd_toEndOf="parent"- app:layout_constraintStart_toEndOf="@+id/resultText"- app:layout_constraintTop_toBottomOf="@+id/startBtn" />--</androidx.constraintlayout.widget.ConstraintLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_debug.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_debug.xmldeleted file mode 100755index cb0c3ff..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_debug.xml+++ /dev/null@@ -1,56 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:orientation="vertical"- android:padding="8dp">-- <TextView- android:id="@+id/titleTV"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_margin="8dp"- android:gravity="center"- android:text="调试信息"- android:textColor="@color/colorPrimary"- android:textSize="22sp" />-- <com.airbnb.epoxy.EpoxyRecyclerView- android:id="@+id/debugRV"- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_weight="1" />-- <ImageView style="@style/ButtonSeparatorH" />-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <Button- android:id="@+id/negativeBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_weight="1"- android:background="@drawable/bg_transparent_to_transparent_half"- android:text="取消"- android:textColor="@color/material_blue_600"- android:textSize="20sp" />-- <ImageView style="@style/ButtonSeparatorV" />-- <Button- android:id="@+id/positiveBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_weight="1"- android:background="@drawable/bg_transparent_to_transparent_half"- android:text="确定"- android:textColor="@color/material_blue_600"- android:textSize="20sp" />-- </LinearLayout>--</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_text_result.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_text_result.xmldeleted file mode 100755index 38aada9..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/dialog_text_result.xml+++ /dev/null@@ -1,61 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:orientation="vertical"- android:padding="8dp">-- <TextView- android:id="@+id/titleTV"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_margin="8dp"- android:gravity="center"- android:text="识别结果"- android:textColor="@color/colorPrimary"- android:textSize="22sp" />-- <EditText- android:id="@+id/contentEdit"- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_margin="8dp"- android:layout_weight="1"- android:background="@drawable/bg_edittext"- android:gravity="start"- android:text=""- android:textSize="16sp" />-- <ImageView style="@style/ButtonSeparatorH" />-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <Button- android:id="@+id/negativeBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_weight="1"- android:background="@drawable/bg_transparent_to_transparent_half"- android:text="取消"- android:textColor="@color/material_blue_600"- android:textSize="20sp" />-- <ImageView style="@style/ButtonSeparatorV" />-- <Button- android:id="@+id/positiveBtn"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_weight="1"- android:background="@drawable/bg_transparent_to_transparent_half"- android:text="复制到剪切板"- android:textColor="@color/material_blue_600"- android:textSize="20sp" />-- </LinearLayout>--</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_dbnet_time_item.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_dbnet_time_item.xmldeleted file mode 100755index ebc86cc..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_dbnet_time_item.xml+++ /dev/null@@ -1,23 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal"- android:padding="2dp">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:text="框分割耗时:" />-- <TextView- android:id="@+id/dbNetTimeTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="match_parent"- android:text="1111" />---</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_item_content.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_item_content.xmldeleted file mode 100755index dcde637..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_item_content.xml+++ /dev/null@@ -1,186 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- android:layout_width="match_parent"- android:layout_height="match_parent"- android:background="@android:color/white"- android:orientation="vertical">-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="框坐标:" />-- <TextView- android:id="@+id/boxPointTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="坐标" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="框置信度:" />-- <TextView- android:id="@+id/boxScoreTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:background="@android:color/white"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="方向索引:" />-- <TextView- android:id="@+id/angleIndexTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="索引" />-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="方向置信度:" />-- <TextView- android:id="@+id/angleScoreTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="方向置信度" />-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="方向耗时:" />-- <TextView- android:id="@+id/angleTimeTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_weight="1"- android:text="识别时间" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="文字结果:" />-- <TextView- android:id="@+id/textTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="结果" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="字置信度"- android:textSize="12sp" />-- <TextView- android:id="@+id/charScoresTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="置信度"- android:textSize="12sp" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="字识别耗时:"- android:textSize="12sp" />-- <TextView- android:id="@+id/crnnTimeTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="时间"- android:textSize="12sp" />-- </LinearLayout>-- <LinearLayout- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:orientation="horizontal">-- <TextView- style="@style/TextItemTitle"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="框总耗时:"- android:textSize="12sp" />-- <TextView- android:id="@+id/blockTimeTv"- style="@style/TextItemContent"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="时间"- android:textSize="12sp" />-- </LinearLayout>--</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_view_item.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_view_item.xmldeleted file mode 100755index 32a3e89..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/layout/rv_debug_view_item.xml+++ /dev/null@@ -1,39 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:app="http://schemas.android.com/apk/res-auto"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:background="@drawable/bg_blue5_to_blue7"- android:orientation="horizontal"- android:padding="2dp">-- <LinearLayout- android:layout_width="40dp"- android:layout_height="match_parent"- android:orientation="vertical">-- <TextView- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_weight="1"- android:gravity="bottom|center_horizontal"- android:text="框"- android:textColor="@android:color/white"- android:textSize="14sp"- android:textStyle="bold" />-- <TextView- android:id="@+id/blockIndexTv"- android:layout_width="match_parent"- android:layout_height="0dp"- android:layout_weight="1"- android:gravity="top|center_horizontal"- android:textColor="@android:color/white"- android:textSize="14sp"- android:textStyle="bold" />-- </LinearLayout>-- <include layout="@layout/rv_debug_item_content" />--</LinearLayout>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmldeleted file mode 100755index eca70cf..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml+++ /dev/null@@ -1,5 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <background android:drawable="@drawable/ic_launcher_background" />- <foreground android:drawable="@drawable/ic_launcher_foreground" />-</adaptive-icon>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xmldeleted file mode 100755index eca70cf..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml+++ /dev/null@@ -1,5 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <background android:drawable="@drawable/ic_launcher_background" />- <foreground android:drawable="@drawable/ic_launcher_foreground" />-</adaptive-icon>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher.pngdeleted file mode 100755index a571e60..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher_round.pngdeleted file mode 100755index 61da551..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-hdpi/ic_launcher_round.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher.pngdeleted file mode 100755index c41dd28..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher_round.pngdeleted file mode 100755index db5080a..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-mdpi/ic_launcher_round.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher.pngdeleted file mode 100755index 6dba46d..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngdeleted file mode 100755index da31a87..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngdeleted file mode 100755index 15ac681..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngdeleted file mode 100755index b216f2d..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngdeleted file mode 100755index f25a419..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngdeleted file mode 100755index e96783c..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors.xmldeleted file mode 100755index d97fba2..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors.xml+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<resources>- <color name="colorPrimary">#6200EE</color>- <color name="colorPrimaryDark">#3700B3</color>- <color name="colorAccent">#03DAC5</color>- <color name="transparent_half_1">#10000000</color>- <color name="transparent">#00000000</color>-</resources>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors_material.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors_material.xmldeleted file mode 100755index b24b0ee..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/colors_material.xml+++ /dev/null@@ -1,294 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<resources>- <!-- red -->- <color name="material_red_50">#ffffebee</color>- <color name="material_red_100">#fff4c7c3</color>- <color name="material_red_200">#ffef9a9a</color>- <color name="material_red_300">#ffe67c73</color>- <color name="material_red_400">#ffef5350</color>- <color name="material_red_500">#ffdb4437</color>- <color name="material_red_600">#ffe53935</color>- <color name="material_red_700">#ffc53929</color>- <color name="material_red_800">#ffc62828</color>- <color name="material_red_900">#ffb71c1c</color>- <color name="material_red_A100">#ffff8a80</color>- <color name="material_red_A200">#ffff5252</color>- <color name="material_red_A400">#ffff1744</color>- <color name="material_red_A700">#ffd50000</color>-- <!-- pink -->- <color name="material_pink_50">#fffce4ec</color>- <color name="material_pink_100">#fff8bbd0</color>- <color name="material_pink_200">#fff48fb1</color>- <color name="material_pink_300">#fff06292</color>- <color name="material_pink_400">#ffec407a</color>- <color name="material_pink_500">#ffe91e63</color>- <color name="material_pink_600">#ffd81b60</color>- <color name="material_pink_700">#ffc2185b</color>- <color name="material_pink_800">#ffad1457</color>- <color name="material_pink_900">#ff880e4f</color>- <color name="material_pink_A100">#ffff80ab</color>- <color name="material_pink_A200">#ffff4081</color>- <color name="material_pink_A400">#fff50057</color>- <color name="material_pink_A700">#ffc51162</color>-- <!-- purple -->- <color name="material_purple_50">#fff3e5f5</color>- <color name="material_purple_100">#ffe1bee7</color>- <color name="material_purple_200">#ffce93d8</color>- <color name="material_purple_300">#ffba68c8</color>- <color name="material_purple_400">#ffab47bc</color>- <color name="material_purple_500">#ff9c27b0</color>- <color name="material_purple_600">#ff8e24aa</color>- <color name="material_purple_700">#ff7b1fa2</color>- <color name="material_purple_800">#ff6a1b9a</color>- <color name="material_purple_900">#ff4a148c</color>- <color name="material_purple_A100">#ffea80fc</color>- <color name="material_purple_A200">#ffe040fb</color>- <color name="material_purple_A400">#ffd500f9</color>- <color name="material_purple_A700">#ffaa00ff</color>-- <!-- deep purple -->- <color name="material_deep_purple_50">#ffede7f6</color>- <color name="material_deep_purple_100">#ffd1c4e9</color>- <color name="material_deep_purple_200">#ffb39ddb</color>- <color name="material_deep_purple_300">#ff9575cd</color>- <color name="material_deep_purple_400">#ff7e57c2</color>- <color name="material_deep_purple_500">#ff673ab7</color>- <color name="material_deep_purple_600">#ff5e35b1</color>- <color name="material_deep_purple_700">#ff512da8</color>- <color name="material_deep_purple_800">#ff4527a0</color>- <color name="material_deep_purple_900">#ff311b92</color>- <color name="material_deep_purple_A100">#ffb388ff</color>- <color name="material_deep_purple_A200">#ff7c4dff</color>- <color name="material_deep_purple_A400">#ff651fff</color>- <color name="material_deep_purple_A700">#ff6200ea</color>-- <!-- indigo -->- <color name="material_indigo_50">#ffe8eaf6</color>- <color name="material_indigo_100">#ffc5cae9</color>- <color name="material_indigo_200">#ff9fa8da</color>- <color name="material_indigo_300">#ff7986cb</color>- <color name="material_indigo_400">#ff5c6bc0</color>- <color name="material_indigo_500">#ff3f51b5</color>- <color name="material_indigo_600">#ff3949ab</color>- <color name="material_indigo_700">#ff303f9f</color>- <color name="material_indigo_800">#ff283593</color>- <color name="material_indigo_900">#ff1a237e</color>- <color name="material_indigo_A100">#ff8c9eff</color>- <color name="material_indigo_A200">#ff536dfe</color>- <color name="material_indigo_A400">#ff3d5afe</color>- <color name="material_indigo_A700">#ff304ffe</color>-- <!-- blue -->- <color name="material_blue_50">#ffe3f2fd</color>- <color name="material_blue_100">#ffbbdefb</color>- <color name="material_blue_200">#ff90caf9</color>- <color name="material_blue_300">#ff64b5f6</color>- <color name="material_blue_400">#ff42a5f5</color>- <color name="material_blue_500">#ff2196f3</color>- <color name="material_blue_600">#ff1e88e5</color>- <color name="material_blue_700">#ff1976d2</color>- <color name="material_blue_800">#ff1565c0</color>- <color name="material_blue_900">#ff0d47a1</color>- <color name="material_blue_A100">#ff82b1ff</color>- <color name="material_blue_A200">#ff448aff</color>- <color name="material_blue_A400">#ff2979ff</color>- <color name="material_blue_A700">#ff2962ff</color>-- <!-- light blue -->- <color name="material_light_blue_50">#ffe1f5fe</color>- <color name="material_light_blue_100">#ffb3e5fc</color>- <color name="material_light_blue_200">#ff81d4fa</color>- <color name="material_light_blue_300">#ff4fc3f7</color>- <color name="material_light_blue_400">#ff29b6f6</color>- <color name="material_light_blue_500">#ff03a9f4</color>- <color name="material_light_blue_600">#ff039be5</color>- <color name="material_light_blue_700">#ff0288d1</color>- <color name="material_light_blue_800">#ff0277bd</color>- <color name="material_light_blue_900">#ff01579b</color>- <color name="material_light_blue_A100">#ff80d8ff</color>- <color name="material_light_blue_A200">#ff40c4ff</color>- <color name="material_light_blue_A400">#ff00b0ff</color>- <color name="material_light_blue_A700">#ff0091ea</color>-- <!-- cyan -->- <color name="material_cyan_50">#ffe0f7fa</color>- <color name="material_cyan_100">#ffb2ebf2</color>- <color name="material_cyan_200">#ff80deea</color>- <color name="material_cyan_300">#ff4dd0e1</color>- <color name="material_cyan_400">#ff26c6da</color>- <color name="material_cyan_500">#ff00bcd4</color>- <color name="material_cyan_600">#ff00acc1</color>- <color name="material_cyan_700">#ff0097a7</color>- <color name="material_cyan_800">#ff00838f</color>- <color name="material_cyan_900">#ff006064</color>- <color name="material_cyan_A100">#ff84ffff</color>- <color name="material_cyan_A200">#ff18ffff</color>- <color name="material_cyan_A400">#ff00e5ff</color>- <color name="material_cyan_A700">#ff00b8d4</color>-- <!-- teal -->- <color name="material_teal_50">#ffe0f2f1</color>- <color name="material_teal_100">#ffb2dfdb</color>- <color name="material_teal_200">#ff80cbc4</color>- <color name="material_teal_300">#ff4db6ac</color>- <color name="material_teal_400">#ff26a69a</color>- <color name="material_teal_500">#ff009688</color>- <color name="material_teal_600">#ff00897b</color>- <color name="material_teal_700">#ff00796b</color>- <color name="material_teal_800">#ff00695c</color>- <color name="material_teal_900">#ff004d40</color>- <color name="material_teal_A100">#ffa7ffeb</color>- <color name="material_teal_A200">#ff64ffda</color>- <color name="material_teal_A400">#ff1de9b6</color>- <color name="material_teal_A700">#ff00bfa5</color>-- <!-- green -->- <color name="material_green_50">#ffe8f5e9</color>- <color name="material_green_100">#ffc8e6c9</color>- <color name="material_green_200">#ffa5d6a7</color>- <color name="material_green_300">#ff81c784</color>- <color name="material_green_400">#ff66bb6a</color>- <color name="material_green_500">#ff4caf50</color>- <color name="material_green_600">#ff43a047</color>- <color name="material_green_700">#ff388e3c</color>- <color name="material_green_800">#ff2e7d32</color>- <color name="material_green_900">#ff1b5e20</color>- <color name="material_green_A100">#ffb9f6ca</color>- <color name="material_green_A200">#ff69f0ae</color>- <color name="material_green_A400">#ff00e676</color>- <color name="material_green_A700">#ff00c853</color>-- <!--light green-->- <color name="material_light_green_50">#fff1f8e9</color>- <color name="material_light_green_100">#ffdcedc8</color>- <color name="material_light_green_200">#ffc5e1a5</color>- <color name="material_light_green_300">#ffaed581</color>- <color name="material_light_green_400">#ff9ccc65</color>- <color name="material_light_green_500">#ff8bc34a</color>- <color name="material_light_green_600">#ff7cb342</color>- <color name="material_light_green_700">#ff689f38</color>- <color name="material_light_green_800">#ff558b2f</color>- <color name="material_light_green_900">#ff33691e</color>- <color name="material_light_green_A100">#ffccff90</color>- <color name="material_light_green_A200">#ffb2ff59</color>- <color name="material_light_green_A400">#ff76ff03</color>- <color name="material_light_green_A700">#ff64dd17</color>-- <!-- lime -->- <color name="material_lime_50">#fff9fbe7</color>- <color name="material_lime_100">#fff0f4c3</color>- <color name="material_lime_200">#ffe6ee9c</color>- <color name="material_lime_300">#ffdce775</color>- <color name="material_lime_400">#ffd4e157</color>- <color name="material_lime_500">#ffcddc39</color>- <color name="material_lime_600">#ffc0ca33</color>- <color name="material_lime_700">#ffafb42b</color>- <color name="material_lime_800">#ff9e9d24</color>- <color name="material_lime_900">#ff827717</color>- <color name="material_lime_A100">#fff4ff81</color>- <color name="material_lime_A200">#ffeeff41</color>- <color name="material_lime_A400">#ffc6ff00</color>- <color name="material_lime_A700">#ffaeea00</color>-- <!-- yellow -->- <color name="material_yellow_50">#fffffde7</color>- <color name="material_yellow_100">#fffff9c4</color>- <color name="material_yellow_200">#fffff59d</color>- <color name="material_yellow_300">#fffff176</color>- <color name="material_yellow_400">#ffffee58</color>- <color name="material_yellow_500">#ffffeb3b</color>- <color name="material_yellow_600">#fffdd835</color>- <color name="material_yellow_700">#fffbc02d</color>- <color name="material_yellow_800">#fff9a825</color>- <color name="material_yellow_900">#fff57f17</color>- <color name="material_yellow_A100">#ffffff8d</color>- <color name="material_yellow_A200">#ffffff00</color>- <color name="material_yellow_A400">#ffffea00</color>- <color name="material_yellow_A700">#ffffd600</color>-- <!-- amber -->- <color name="material_amber_50">#fffff8e1</color>- <color name="material_amber_100">#ffffecb3</color>- <color name="material_amber_200">#ffffe082</color>- <color name="material_amber_300">#ffffd54f</color>- <color name="material_amber_400">#ffffca28</color>- <color name="material_amber_500">#ffffc107</color>- <color name="material_amber_600">#ffffb300</color>- <color name="material_amber_700">#ffffa000</color>- <color name="material_amber_800">#ffff8f00</color>- <color name="material_amber_900">#ffff6f00</color>- <color name="material_amber_A100">#ffffe57f</color>- <color name="material_amber_A200">#ffffd740</color>- <color name="material_amber_A400">#ffffc400</color>- <color name="material_amber_A700">#ffffab00</color>-- <!-- orange -->- <color name="material_orange_50">#fffff3e0</color>- <color name="material_orange_100">#ffffe0b2</color>- <color name="material_orange_200">#ffffcc80</color>- <color name="material_orange_300">#ffffb74d</color>- <color name="material_orange_400">#ffffa726</color>- <color name="material_orange_500">#ffff9800</color>- <color name="material_orange_600">#fffb8c00</color>- <color name="material_orange_700">#fff57c00</color>- <color name="material_orange_800">#ffef6c00</color>- <color name="material_orange_900">#ffe65100</color>- <color name="material_orange_A100">#ffffd180</color>- <color name="material_orange_A200">#ffffab40</color>- <color name="material_orange_A400">#ffff9100</color>- <color name="material_orange_A700">#ffff6d00</color>-- <!-- deep orange -->- <color name="material_deep_orange_50">#fffbe9e7</color>- <color name="material_deep_orange_100">#ffffccbc</color>- <color name="material_deep_orange_200">#ffffab91</color>- <color name="material_deep_orange_300">#ffff8a65</color>- <color name="material_deep_orange_400">#ffff7043</color>- <color name="material_deep_orange_500">#ffff5722</color>- <color name="material_deep_orange_600">#fff4511e</color>- <color name="material_deep_orange_700">#ffe64a19</color>- <color name="material_deep_orange_800">#ffd84315</color>- <color name="material_deep_orange_900">#ffbf360c</color>- <color name="material_deep_orange_A100">#ffff9e80</color>- <color name="material_deep_orange_A200">#ffff6e40</color>- <color name="material_deep_orange_A400">#ffff3d00</color>- <color name="material_deep_orange_A700">#ffdd2c00</color>-- <!-- brown -->- <color name="material_brown_50">#ffefebe9</color>- <color name="material_brown_100">#ffd7ccc8</color>- <color name="material_brown_200">#ffbcaaa4</color>- <color name="material_brown_300">#ffa1887f</color>- <color name="material_brown_400">#ff8d6e63</color>- <color name="material_brown_500">#ff795548</color>- <color name="material_brown_600">#ff6d4c41</color>- <color name="material_brown_700">#ff5d4037</color>- <color name="material_brown_800">#ff4e342e</color>- <color name="material_brown_900">#ff3e2723</color>-- <!-- grey -->- <color name="material_grey_50">#fffafafa</color>- <color name="material_grey_100">#fff5f5f5</color>- <color name="material_grey_200">#ffeeeeee</color>- <color name="material_grey_300">#ffe0e0e0</color>- <color name="material_grey_400">#ffbdbdbd</color>- <color name="material_grey_500">#ff9e9e9e</color>- <color name="material_grey_600">#ff757575</color>- <color name="material_grey_700">#ff616161</color>- <color name="material_grey_800">#ff424242</color>- <color name="material_grey_900">#ff212121</color>-- <!-- blue grey -->- <color name="material_blue_grey_50">#ffeceff1</color>- <color name="material_blue_grey_100">#ffcfd8dc</color>- <color name="material_blue_grey_200">#ffb0bec5</color>- <color name="material_blue_grey_300">#ff90a4ae</color>- <color name="material_blue_grey_400">#ff78909c</color>- <color name="material_blue_grey_500">#ff607d8b</color>- <color name="material_blue_grey_600">#ff546e7a</color>- <color name="material_blue_grey_700">#ff455a64</color>- <color name="material_blue_grey_800">#ff37474f</color>- <color name="material_blue_grey_900">#ff263238</color>-</resources>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/strings.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/strings.xmldeleted file mode 100755index 07b196a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/strings.xml+++ /dev/null@@ -1,8 +0,0 @@-<resources>- <string name="app_name">BaiPiaoOcrOnnx</string>-- <string name="box_score_thresh">框置信度门限</string>- <string name="box_un_clip_ratio">框大小倍率</string>- <string name="app_permission">获取相机权限</string>- <string name="do_angle">文字方向检测</string>-</resources>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/styles.xml b/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/styles.xmldeleted file mode 100755index 7f7e26f..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/main/res/values/styles.xml+++ /dev/null@@ -1,71 +0,0 @@-<resources>- <!-- Base application theme. -->- <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">- <!-- Customize your theme here. -->- <item name="colorPrimary">@color/colorPrimary</item>- <item name="colorPrimaryDark">@color/colorPrimaryDark</item>- <item name="colorAccent">@color/colorAccent</item>- </style>-- <style name="window_scale_animation" mce_bogus="1" parent="android:Animation">- <item name="android:windowEnterAnimation">@anim/window_enter_anim</item>- <item name="android:windowExitAnimation">@anim/window_exit_anim</item>- </style>-- <style name="diag_top_down_up_animation" parent="android:Animation">- <item name="android:windowEnterAnimation">@anim/window_show_down</item>- <item name="android:windowExitAnimation">@anim/window_close_up</item>- </style>-- <style name="diag_bottom_up_down_animation" parent="android:Animation">- <item name="android:windowEnterAnimation">@anim/window_show_up</item>- <item name="android:windowExitAnimation">@anim/window_close_down</item>- </style>-- <style name="diag_fade_animation" parent="android:Animation">- <item name="android:windowEnterAnimation">@anim/window_fade_in</item>- <item name="android:windowExitAnimation">@anim/window_fade_out</item>- </style>-- <style name="ButtonSeparatorH">- <item name="android:layout_width">match_parent</item>- <item name="android:layout_height">1dp</item>- <item name="android:paddingBottom">0dp</item>- <item name="android:paddingTop">0dp</item>- <item name="android:paddingLeft">0dp</item>- <item name="android:paddingRight">0dp</item>- <item name="android:background">@android:color/white</item>- <item name="android:src">@color/material_grey_300</item>- </style>-- <style name="ButtonSeparatorV">- <item name="android:layout_width">1dp</item>- <item name="android:layout_height">match_parent</item>- <item name="android:paddingBottom">0dp</item>- <item name="android:paddingTop">0dp</item>- <item name="android:paddingLeft">0dp</item>- <item name="android:paddingRight">0dp</item>- <item name="android:background">@android:color/white</item>- <item name="android:src">@color/material_grey_300</item>- </style>-- <style name="TextItemTitle">- <item name="android:gravity">start</item>- <item name="android:layout_marginLeft">8dp</item>- <item name="android:textColor">@android:color/black</item>- <item name="android:paddingTop">2dp</item>- <item name="android:paddingBottom">2dp</item>- <item name="android:textSize">12sp</item>- </style>-- <style name="TextItemContent">- <item name="android:textColor">@color/material_blue_500</item>- <item name="android:background">@drawable/bg_transparent_to_transparent_half</item>- <item name="android:textStyle">italic</item>- <item name="android:paddingTop">2dp</item>- <item name="android:paddingBottom">2dp</item>- <item name="android:textSize">12sp</item>- <item name="android:gravity">center</item>- </style>--</resources>\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/app/src/test/java/com/benjaminwan/ocr/onnx/ExampleUnitTest.kt b/android/BaiPiaoOcrAndroidOnnx/app/src/test/java/com/benjaminwan/ocr/onnx/ExampleUnitTest.ktdeleted file mode 100755index 7c58203..0000000--- a/android/BaiPiaoOcrAndroidOnnx/app/src/test/java/com/benjaminwan/ocr/onnx/ExampleUnitTest.kt+++ /dev/null@@ -1,17 +0,0 @@-package com.benjaminwan.ocr.onnx--import org.junit.Test--import org.junit.Assert.*--/**- * Example local unit test, which will execute on the development machine (host).- *- * See [testing documentation](http://d.android.com/tools/testing).- */-class ExampleUnitTest {- @Test- fun addition_isCorrect() {- assertEquals(4, 2 + 2)- }-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/build.gradle b/android/BaiPiaoOcrAndroidOnnx/build.gradledeleted file mode 100755index a5a562a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/build.gradle+++ /dev/null@@ -1,34 +0,0 @@-// Top-level build file where you can add configuration options common to all sub-projects/modules.-buildscript {- ext.kotlin_version = "1.4.21"- repositories {- maven { url 'https://maven.aliyun.com/repository/google' }- maven { url 'https://maven.aliyun.com/repository/jcenter' }- maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }- maven { url "https://jitpack.io" }- google()- jcenter()- }- dependencies {- classpath 'com.android.tools.build:gradle:4.1.1'- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"-- // NOTE: Do not place your application dependencies here; they belong- // in the individual module build.gradle files- }-}--allprojects {- repositories {- maven { url 'https://maven.aliyun.com/repository/google' }- maven { url 'https://maven.aliyun.com/repository/jcenter' }- maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }- maven { url "https://jitpack.io" }- google()- jcenter()- }-}--task clean(type: Delete) {- delete rootProject.buildDir-}\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/common-aar/IdCardView-1.0.aar b/android/BaiPiaoOcrAndroidOnnx/common-aar/IdCardView-1.0.aardeleted file mode 100755index 1169888..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/common-aar/IdCardView-1.0.aar and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/gradle.properties b/android/BaiPiaoOcrAndroidOnnx/gradle.propertiesdeleted file mode 100755index cfdd35e..0000000--- a/android/BaiPiaoOcrAndroidOnnx/gradle.properties+++ /dev/null@@ -1,22 +0,0 @@-# 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=-Xmx2048m-# 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-# AndroidX package structure to make it clearer which packages are bundled with the-# Android operating system, and which are packaged with your app"s APK-# https://developer.android.com/topic/libraries/support-library/androidx-rn-android.useAndroidX=true-# Automatically convert third-party libraries to use AndroidX-android.enableJetifier=true-# Kotlin code style for this project: "official" or "obsolete":-kotlin.code.style=official-android.injected.testOnly=false\ No newline at end of filediff --git a/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.jar b/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.jardeleted file mode 100755index f6b961f..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.jar and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.properties b/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.propertiesdeleted file mode 100755index 875850a..0000000--- a/android/BaiPiaoOcrAndroidOnnx/gradle/wrapper/gradle-wrapper.properties+++ /dev/null@@ -1,6 +0,0 @@-#Thu Nov 19 08:49:30 CST 2020-distributionBase=GRADLE_USER_HOME-distributionPath=wrapper/dists-zipStoreBase=GRADLE_USER_HOME-zipStorePath=wrapper/dists-distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zipdiff --git a/android/BaiPiaoOcrAndroidOnnx/gradlew b/android/BaiPiaoOcrAndroidOnnx/gradlewdeleted file mode 100755index cccdd3d..0000000--- a/android/BaiPiaoOcrAndroidOnnx/gradlew+++ /dev/null@@ -1,172 +0,0 @@-#!/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=""--# 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" "$@"diff --git a/android/BaiPiaoOcrAndroidOnnx/gradlew.bat b/android/BaiPiaoOcrAndroidOnnx/gradlew.batdeleted file mode 100755index f955316..0000000--- a/android/BaiPiaoOcrAndroidOnnx/gradlew.bat+++ /dev/null@@ -1,84 +0,0 @@-@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=--@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--:omegadiff --git a/android/BaiPiaoOcrAndroidOnnx/keystore/baipiao.keystore b/android/BaiPiaoOcrAndroidOnnx/keystore/baipiao.keystoredeleted file mode 100755index 1c5a3a0..0000000Binary files a/android/BaiPiaoOcrAndroidOnnx/keystore/baipiao.keystore and /dev/null differdiff --git a/android/BaiPiaoOcrAndroidOnnx/settings.gradle b/android/BaiPiaoOcrAndroidOnnx/settings.gradledeleted file mode 100755index 554c6c6..0000000--- a/android/BaiPiaoOcrAndroidOnnx/settings.gradle+++ /dev/null@@ -1,3 +0,0 @@-rootProject.name = "BaiPiaoOcrAndroidOnnx"-include ':app'-include ':OcrLibrary'diff --git a/android/RapidOcrAndroidOnnx b/android/RapidOcrAndroidOnnxnew file mode 160000index 0000000..d920bab--- /dev/null+++ b/android/RapidOcrAndroidOnnx@@ -0,0 +1 @@+Subproject commit d920bab50e55831c76f58e64e9d38954ecae262d