mirror of
https://github.com/PaddlePaddle/PaddleOCR.git
synced 2026-11-25 17:29:39 +08:00
[Feat] Add PP-OCRv6 Android Demo (#18121)
This commit is contained in:
1 parent
6d2e6fb9c7
commit
77ddbafccd
65 files changed
+4226
No files matched your search
@@ -0,0 +1,93 @@
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Built application files
|
||||
*.apk
|
||||
*.aar
|
||||
*.ap_
|
||||
*.aab
|
||||
|
||||
# Files for the ART/Dalvik VM
|
||||
*.dex
|
||||
|
||||
# Java class files
|
||||
*.class
|
||||
|
||||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
release/
|
||||
|
||||
# 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/
|
||||
|
||||
# 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
|
||||
.cxx/
|
||||
|
||||
# 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/
|
||||
|
||||
# Secrets
|
||||
*.env
|
||||
secrets.properties
|
||||
|
||||
# Kotlin
|
||||
.kotlin/
|
||||
|
||||
# Model
|
||||
*.onnx
|
||||
*.yml
|
||||
@@ -0,0 +1,5 @@
|
||||
# PaddleOCR Android Demo
|
||||
|
||||
中文 | [English](./README_en.md)
|
||||
|
||||
请查看 [文档](../../docs/version3.x/inference_deployment/cross_platform/android_deployment.md)。
|
||||
@@ -0,0 +1,5 @@
|
||||
# PaddleOCR Android Demo
|
||||
|
||||
[中文](./README.md) | English
|
||||
|
||||
Please refer to the [documentation](../../docs/version3.x/inference_deployment/cross_platform/android_deployment.en.md).
|
||||
@@ -0,0 +1,54 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.paddle.ocr.demo"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.paddle.ocr.demo"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "1.0.0"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":ppocr-sdk"))
|
||||
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.coil.compose)
|
||||
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
|
||||
<application
|
||||
android:name=".OCRApplication"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="PP-OCRv6 Demo"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.PaddleOCR"
|
||||
tools:targetApi="35">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.PaddleOCR">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import com.paddle.ocr.demo.ui.screen.HomeScreen
|
||||
import com.paddle.ocr.demo.ui.theme.PPOCRTheme
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
PPOCRTheme {
|
||||
HomeScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo
|
||||
|
||||
import android.app.Application
|
||||
import android.util.Log
|
||||
import com.paddle.ocr.PaddleOCR
|
||||
import com.paddle.ocr.PaddleOCRConfig
|
||||
import com.paddle.ocr.util.OpenCVUtils
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class OCRApplication : Application() {
|
||||
|
||||
sealed class ModelState {
|
||||
data object Loading : ModelState()
|
||||
data class Ready(val ocr: PaddleOCR) : ModelState()
|
||||
data class Error(val message: String) : ModelState()
|
||||
}
|
||||
|
||||
private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val _modelState = MutableStateFlow<ModelState>(ModelState.Loading)
|
||||
|
||||
val modelState: StateFlow<ModelState> = _modelState.asStateFlow()
|
||||
|
||||
val ocr: PaddleOCR?
|
||||
get() = (_modelState.value as? ModelState.Ready)?.ocr
|
||||
|
||||
val isModelLoaded: Boolean
|
||||
get() = _modelState.value is ModelState.Ready
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
loadModels()
|
||||
}
|
||||
|
||||
fun retryLoadModels() {
|
||||
if (_modelState.value is ModelState.Loading) return
|
||||
loadModels()
|
||||
}
|
||||
|
||||
private fun loadModels() {
|
||||
_modelState.value = ModelState.Loading
|
||||
applicationScope.launch {
|
||||
try {
|
||||
if (!OpenCVUtils.init(this@OCRApplication)) {
|
||||
throw IllegalStateException("Failed to initialize OpenCV native library")
|
||||
}
|
||||
val loadedOcr = PaddleOCR.create(
|
||||
context = this@OCRApplication,
|
||||
config = PaddleOCRConfig(
|
||||
recScoreThresh = 0.0f,
|
||||
recBatchSize = 1,
|
||||
),
|
||||
)
|
||||
_modelState.value = ModelState.Ready(loadedOcr)
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
val message = modelLoadErrorMessage(t)
|
||||
Log.e(TAG, message, t)
|
||||
_modelState.value = ModelState.Error(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun modelLoadErrorMessage(error: Throwable): String {
|
||||
val details = listOfNotNull(error.message, error.cause?.message)
|
||||
.distinct()
|
||||
.joinToString(": ")
|
||||
return if (details.isBlank()) {
|
||||
"Failed to load OCR models"
|
||||
} else {
|
||||
"Failed to load OCR models: $details"
|
||||
}
|
||||
}
|
||||
|
||||
override fun onTerminate() {
|
||||
super.onTerminate()
|
||||
applicationScope.launch {
|
||||
ocr?.release()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "OCRApplication"
|
||||
|
||||
lateinit var instance: OCRApplication
|
||||
private set
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ErrorDialog(
|
||||
message: String,
|
||||
onRetry: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Error") },
|
||||
text = {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onRetry) {
|
||||
Text("Retry")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text("Dismiss")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ImagePicker(
|
||||
onGalleryClick: () -> Unit,
|
||||
onSampleClick: (Int) -> Unit,
|
||||
sampleImages: List<Int>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Button(onClick = onGalleryClick) {
|
||||
Icon(Icons.Default.Add, contentDescription = null)
|
||||
Text(" Select from Gallery", modifier = Modifier.padding(start = 8.dp))
|
||||
}
|
||||
|
||||
if (sampleImages.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text("Or try a sample:", style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
sampleImages.forEach { resId ->
|
||||
Image(
|
||||
painter = painterResource(resId),
|
||||
contentDescription = "Sample image",
|
||||
modifier = Modifier
|
||||
.size(64.dp)
|
||||
.padding(4.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onSampleClick(resId) },
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Paint
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.nativeCanvas
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import com.paddle.ocr.model.OCRResult
|
||||
import kotlin.math.max
|
||||
|
||||
private val BOX_COLORS = listOf(
|
||||
Color(0xFFE53935),
|
||||
Color(0xFF1E88E5),
|
||||
Color(0xFF43A047),
|
||||
Color(0xFFFB8C00),
|
||||
Color(0xFF8E24AA),
|
||||
Color(0xFF00ACC1),
|
||||
Color(0xFFD81B60),
|
||||
Color(0xFF6D4C41),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ImagePreview(
|
||||
bitmap: Bitmap,
|
||||
results: List<OCRResult>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val imageBitmap: ImageBitmap = bitmap.asImageBitmap()
|
||||
val aspect = bitmap.width.toFloat() / bitmap.height.toFloat()
|
||||
|
||||
// Paints for index badges
|
||||
val numberPaint = remember {
|
||||
Paint().apply {
|
||||
color = android.graphics.Color.WHITE
|
||||
textSize = 36f
|
||||
isAntiAlias = true
|
||||
isFakeBoldText = true
|
||||
}
|
||||
}
|
||||
val badgePaint = remember {
|
||||
Paint().apply {
|
||||
color = 0xCC000000.toInt() // semi-transparent black
|
||||
isAntiAlias = true
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = modifier) {
|
||||
Image(
|
||||
bitmap = imageBitmap,
|
||||
contentDescription = "OCR Input",
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(aspect),
|
||||
)
|
||||
if (results.isNotEmpty()) {
|
||||
Canvas(modifier = Modifier.matchParentSize()) {
|
||||
// Canvas matches Image exactly (both have same aspectRatio),
|
||||
// and ContentScale.Fit fills the Image composable with the bitmap
|
||||
// (same aspect ratio → no letterboxing), so coordinates map 1:1.
|
||||
val scaleX = size.width / bitmap.width
|
||||
val scaleY = size.height / bitmap.height
|
||||
|
||||
results.forEachIndexed { index, result ->
|
||||
val color = BOX_COLORS[index % BOX_COLORS.size]
|
||||
val path = Path().apply {
|
||||
result.box.points.forEachIndexed { i, pt ->
|
||||
val x = pt.x * scaleX
|
||||
val y = pt.y * scaleY
|
||||
if (i == 0) moveTo(x, y) else lineTo(x, y)
|
||||
}
|
||||
close()
|
||||
}
|
||||
// Box fill
|
||||
drawPath(path, color = color.copy(alpha = 0.15f))
|
||||
// Box outline
|
||||
drawPath(path, color = color, style = Stroke(width = 3f))
|
||||
|
||||
// Number badge: rounded rect background + white text
|
||||
val topLeft = result.box.points.minByOrNull { it.y }?.let { pt ->
|
||||
Offset(pt.x * scaleX, pt.y * scaleY)
|
||||
} ?: Offset.Zero
|
||||
|
||||
val label = "${index + 1}"
|
||||
val textWidth = numberPaint.measureText(label)
|
||||
val badgeH = 44f
|
||||
val badgeW = textWidth + 20f
|
||||
val badgeX = topLeft.x
|
||||
val badgeY = max(0f, topLeft.y - badgeH)
|
||||
|
||||
// Draw badge background
|
||||
drawContext.canvas.nativeCanvas.drawRoundRect(
|
||||
badgeX, badgeY, badgeX + badgeW, badgeY + badgeH,
|
||||
8f, 8f, badgePaint,
|
||||
)
|
||||
// Draw number centered in badge
|
||||
drawContext.canvas.nativeCanvas.drawText(
|
||||
label,
|
||||
badgeX + (badgeW - textWidth) / 2f,
|
||||
badgeY + badgeH / 2f + 12f, // center vertically
|
||||
numberPaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun LoadingOverlay(message: String = "Loading models...", modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(48.dp))
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(text = message, style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.paddle.ocr.model.OCRResult
|
||||
|
||||
@Composable
|
||||
fun ResultList(
|
||||
results: List<OCRResult>,
|
||||
onCopyAll: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(modifier = modifier.padding(horizontal = 16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = "Results (${results.size})",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onCopyAll) {
|
||||
Text("Copy All")
|
||||
}
|
||||
}
|
||||
results.forEachIndexed { index, result ->
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = "${index + 1}.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.width(24.dp),
|
||||
)
|
||||
Text(
|
||||
text = result.text,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "${"%.2f".format(result.confidence * 100)}%",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
)
|
||||
}
|
||||
if (index < results.lastIndex) {
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.component
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun TimingBar(
|
||||
detectionMs: Long,
|
||||
recognitionMs: Long,
|
||||
totalMs: Long,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = {
|
||||
Text("Det: ${detectionMs}ms", style = MaterialTheme.typography.labelSmall)
|
||||
},
|
||||
)
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = {
|
||||
Text("Rec: ${recognitionMs}ms", style = MaterialTheme.typography.labelSmall)
|
||||
},
|
||||
)
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = {
|
||||
Text("Total: ${totalMs}ms", style = MaterialTheme.typography.labelSmall)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.screen
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.paddle.ocr.demo.ui.component.*
|
||||
import com.paddle.ocr.demo.ui.viewmodel.OCRViewModel
|
||||
|
||||
@Composable
|
||||
fun HomeScreen(viewModel: OCRViewModel = viewModel()) {
|
||||
val state by viewModel.uiState.collectAsState()
|
||||
val timing by viewModel.timing.collectAsState()
|
||||
|
||||
val galleryLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.PickVisualMedia()
|
||||
) { uri -> uri?.let { viewModel.onImageSelected(it) } }
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
when (val s = state) {
|
||||
is OCRViewModel.UIState.Loading -> {
|
||||
LoadingOverlay("Loading OCR models...")
|
||||
}
|
||||
is OCRViewModel.UIState.Ready -> {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
ImagePicker(
|
||||
onGalleryClick = { galleryLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
|
||||
onSampleClick = { viewModel.onSampleImageClicked(it) },
|
||||
sampleImages = emptyList(),
|
||||
)
|
||||
}
|
||||
}
|
||||
is OCRViewModel.UIState.Processing -> {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
ImagePreview(bitmap = s.bitmap, results = emptyList())
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
LoadingOverlay("Processing...")
|
||||
}
|
||||
}
|
||||
is OCRViewModel.UIState.Result -> {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
ImagePreview(
|
||||
bitmap = s.bitmap,
|
||||
results = s.result.results,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (timing != null) {
|
||||
TimingBar(
|
||||
detectionMs = timing!!.detectionMs,
|
||||
recognitionMs = timing!!.recognitionMs,
|
||||
totalMs = timing!!.totalMs,
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
ResultList(
|
||||
results = s.result.results,
|
||||
onCopyAll = { viewModel.copyAllResults(s.result.results) },
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
ImagePicker(
|
||||
onGalleryClick = { galleryLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
|
||||
onSampleClick = { viewModel.onSampleImageClicked(it) },
|
||||
sampleImages = emptyList(),
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
is OCRViewModel.UIState.Error -> {
|
||||
LoadingOverlay("Error occurred")
|
||||
ErrorDialog(
|
||||
message = s.message,
|
||||
onRetry = { viewModel.retry() },
|
||||
onDismiss = { viewModel.retry() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.theme
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = Color(0xFF1565C0),
|
||||
onPrimary = Color.White,
|
||||
primaryContainer = Color(0xFFD1E4FF),
|
||||
onPrimaryContainer = Color(0xFF001D36),
|
||||
secondary = Color(0xFF006874),
|
||||
onSecondary = Color.White,
|
||||
secondaryContainer = Color(0xFF9EEFF7),
|
||||
onSecondaryContainer = Color(0xFF001F24),
|
||||
surface = Color(0xFFFDFBFF),
|
||||
onSurface = Color(0xFF1A1C1E),
|
||||
background = Color(0xFFFDFBFF),
|
||||
onBackground = Color(0xFF1A1C1E),
|
||||
error = Color(0xFFBA1A1A),
|
||||
onError = Color.White,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun PPOCRTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(
|
||||
colorScheme = LightColorScheme,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.demo.ui.viewmodel
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.paddle.ocr.demo.OCRApplication
|
||||
import com.paddle.ocr.model.OCRResult
|
||||
import com.paddle.ocr.model.OCRRunResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class OCRViewModel : ViewModel() {
|
||||
|
||||
sealed class UIState {
|
||||
data object Loading : UIState()
|
||||
data object Ready : UIState()
|
||||
data class Processing(val bitmap: Bitmap) : UIState()
|
||||
data class Result(val bitmap: Bitmap, val result: OCRRunResult) : UIState()
|
||||
data class Error(val message: String) : UIState()
|
||||
}
|
||||
|
||||
data class TimingInfo(
|
||||
val detectionMs: Long,
|
||||
val recognitionMs: Long,
|
||||
val totalMs: Long,
|
||||
)
|
||||
|
||||
private val _uiState = MutableStateFlow<UIState>(
|
||||
uiStateForModelState(OCRApplication.instance.modelState.value)
|
||||
)
|
||||
val uiState: StateFlow<UIState> = _uiState.asStateFlow()
|
||||
|
||||
private val _timing = MutableStateFlow<TimingInfo?>(null)
|
||||
val timing: StateFlow<TimingInfo?> = _timing.asStateFlow()
|
||||
|
||||
private fun uiStateForModelState(modelState: OCRApplication.ModelState): UIState {
|
||||
return when (modelState) {
|
||||
is OCRApplication.ModelState.Loading -> UIState.Loading
|
||||
is OCRApplication.ModelState.Ready -> UIState.Ready
|
||||
is OCRApplication.ModelState.Error -> UIState.Error(modelState.message)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
OCRApplication.instance.modelState.collect { modelState ->
|
||||
when (modelState) {
|
||||
is OCRApplication.ModelState.Loading -> _uiState.value = UIState.Loading
|
||||
is OCRApplication.ModelState.Ready -> {
|
||||
if (_uiState.value is UIState.Loading || _uiState.value is UIState.Error) {
|
||||
_uiState.value = UIState.Ready
|
||||
}
|
||||
}
|
||||
is OCRApplication.ModelState.Error -> _uiState.value = UIState.Error(modelState.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onImageSelected(uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
OCRApplication.instance.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}
|
||||
if (bytes != null) {
|
||||
val bitmap = withContext(Dispatchers.IO) {
|
||||
decodeSampledBitmap(bytes, maxWidth = 2048, maxHeight = 2048)
|
||||
}
|
||||
if (bitmap != null) {
|
||||
processImageBytes(bytes, bitmap)
|
||||
} else {
|
||||
_uiState.value = UIState.Error("Failed to load image")
|
||||
}
|
||||
} else {
|
||||
_uiState.value = UIState.Error("Failed to load image")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = UIState.Error(e.message ?: "Unknown error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onSampleImageClicked(resId: Int) {
|
||||
viewModelScope.launch {
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
OCRApplication.instance.resources.openRawResource(resId).use { it.readBytes() }
|
||||
}
|
||||
val bitmap = withContext(Dispatchers.IO) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
}
|
||||
if (bitmap != null) {
|
||||
processImageBytes(bytes, bitmap)
|
||||
} else {
|
||||
_uiState.value = UIState.Error("Failed to load image")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun processImageBytes(bytes: ByteArray, bitmap: Bitmap) {
|
||||
_uiState.value = UIState.Processing(bitmap)
|
||||
|
||||
try {
|
||||
val ocr = OCRApplication.instance.ocr
|
||||
?: throw IllegalStateException("OCR engine not initialized")
|
||||
|
||||
val result = ocr.recognize(bytes)
|
||||
_uiState.value = UIState.Result(bitmap, result)
|
||||
_timing.value = TimingInfo(
|
||||
detectionMs = result.detectionTimeMs,
|
||||
recognitionMs = result.recognitionTimeMs,
|
||||
totalMs = result.totalTimeMs,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = UIState.Error(e.message ?: "OCR failed")
|
||||
}
|
||||
}
|
||||
|
||||
fun retry() {
|
||||
val app = OCRApplication.instance
|
||||
if (app.isModelLoaded) {
|
||||
_uiState.value = UIState.Ready
|
||||
} else {
|
||||
app.retryLoadModels()
|
||||
}
|
||||
}
|
||||
|
||||
fun copyAllResults(results: List<OCRResult>) {
|
||||
val text = results.joinToString("\n") { it.text }
|
||||
val clipboard = OCRApplication.instance.getSystemService(android.content.Context.CLIPBOARD_SERVICE)
|
||||
as android.content.ClipboardManager
|
||||
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("OCR Results", text))
|
||||
}
|
||||
|
||||
private fun decodeSampledBitmap(
|
||||
bytes: ByteArray,
|
||||
maxWidth: Int,
|
||||
maxHeight: Int,
|
||||
): Bitmap? {
|
||||
// First pass: decode bounds only
|
||||
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
|
||||
val (origW, origH) = opts.outWidth to opts.outHeight
|
||||
if (origW <= 0 || origH <= 0) return null
|
||||
|
||||
// Calculate sample size (power of 2)
|
||||
var sampleSize = 1
|
||||
while (sampleSize * 2 <= maxOf(origW / maxWidth, origH / maxHeight)) {
|
||||
sampleSize *= 2
|
||||
}
|
||||
|
||||
// Second pass: decode with sampling
|
||||
return BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
}.let { BitmapFactory.decodeByteArray(bytes, 0, bytes.size, it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?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="#FFFFFF"
|
||||
android:pathData="M54,28 L54,28 C68.36,28 80,39.64 80,54 L80,54 C80,68.36 68.36,80 54,80 L54,80 C39.64,80 28,68.36 28,54 L28,54 C28,39.64 39.64,28 54,28 Z" />
|
||||
<path
|
||||
android:fillColor="#1A73E8"
|
||||
android:pathData="M46,42 L62,42 L62,46 L50,46 L50,52 L60,52 L60,56 L50,56 L50,62 L62,62 L62,66 L46,66 Z" />
|
||||
<path
|
||||
android:fillColor="#1A73E8"
|
||||
android:pathData="M42,50 L42,46 L38,46 L38,62 L42,62 L42,58 C43.5,60.5 46,62 49,62 C53.97,62 58,57.97 58,54 C58,50.03 53.97,46 49,46 C46,46 43.5,47.5 42,50 Z M49,58 C46.79,58 45,56.21 45,54 C45,51.79 46.79,50 49,50 C51.21,50 53,51.79 53,54 C53,56.21 51.21,58 49,58 Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#1A73E8</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">PP-OCRv6 Demo</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.PaddleOCR" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.android.library) apply false
|
||||
alias(libs.plugins.kotlin.android) apply false
|
||||
alias(libs.plugins.kotlin.compose) apply false
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
kotlin.code.style=official
|
||||
android.nonTransitiveRClass=true
|
||||
@@ -0,0 +1,41 @@
|
||||
[versions]
|
||||
agp = "8.7.3"
|
||||
kotlin = "2.1.0"
|
||||
coreKtx = "1.15.0"
|
||||
lifecycleRuntime = "2.8.7"
|
||||
activityCompose = "1.9.3"
|
||||
composeBom = "2024.12.01"
|
||||
onnxruntime = "1.21.1"
|
||||
opencv = "4.5.3"
|
||||
coroutines = "1.9.0"
|
||||
coil = "2.7.0"
|
||||
test-runner = "1.2.0"
|
||||
test-ext-junit-ktx = "1.2.1"
|
||||
test-monitor = "1.7.2"
|
||||
junit = "4.13.2"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntime" }
|
||||
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntime" }
|
||||
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||
compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||
compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||
compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||
compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||
compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||
compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||
onnxruntime-android = { group = "com.microsoft.onnxruntime", name = "onnxruntime-android", version.ref = "onnxruntime" }
|
||||
opencv-android = { group = "com.quickbirdstudios", name = "opencv", version.ref = "opencv" }
|
||||
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
|
||||
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
|
||||
androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = "test-runner" }
|
||||
androidx-test-ext-junit-ktx = { group = "androidx.test.ext", name = "junit-ktx", version.ref = "test-ext-junit-ktx" }
|
||||
androidx-test-monitor = { group = "androidx.test", name = "monitor", version.ref = "test-monitor" }
|
||||
junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
android-library = { id = "com.android.library", version.ref = "agp" }
|
||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
Vendored
+72
@@ -0,0 +1,72 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
PRG="$0"
|
||||
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"`
|
||||
|
||||
DEFAULT_JVM_OPTS='-Xmx64m -Xms64m'
|
||||
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
OS_NAME="`uname`"
|
||||
case "$OS_NAME" in
|
||||
CYGWIN* | MINGW* | MSYS* )
|
||||
IS_WINDOWS=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
else
|
||||
JAVACMD="java"
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
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
|
||||
|
||||
GRADLE_OPTS="${GRADLE_OPTS} -Dorg.gradle.appname=${APP_BASE_NAME}"
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$DEFAULT_JVM_OPTS \
|
||||
$JAVA_OPTS \
|
||||
$GRADLE_OPTS \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
@@ -0,0 +1,42 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.paddle.ocr"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
consumerProguardFiles("proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.onnxruntime.android)
|
||||
implementation(libs.opencv.android)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
|
||||
androidTestImplementation(libs.androidx.test.runner)
|
||||
androidTestImplementation(libs.androidx.test.ext.junit.ktx)
|
||||
androidTestImplementation(libs.androidx.test.monitor)
|
||||
androidTestImplementation(libs.junit)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-keep class com.paddle.ocr.** { *; }
|
||||
-keep class ai.onnxruntime.** { *; }
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.benchmark
|
||||
|
||||
object BenchmarkFixtures {
|
||||
const val defaultReferenceImageName = "android_ocr_benchmark_reference.jpg"
|
||||
}
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.benchmark
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Debug
|
||||
import android.util.Log
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.paddle.ocr.EngineConfig
|
||||
import com.paddle.ocr.PaddleOCR
|
||||
import com.paddle.ocr.PaddleOCRConfig
|
||||
import com.paddle.ocr.model.OCRRunResult
|
||||
import com.paddle.ocr.util.OpenCVUtils
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.BeforeClass
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class OCRBenchmarkTest {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "OCRBenchmark"
|
||||
|
||||
// Instrumentation arguments (passed via -Pandroid.testInstrumentationRunnerArguments.*)
|
||||
private const val ARG_WARMUP = "warmup"
|
||||
private const val ARG_ITERATIONS = "iterations"
|
||||
private const val ARG_REC_BATCH_SIZE = "rec_batch_size"
|
||||
|
||||
private const val DEFAULT_WARMUP = 3
|
||||
private const val DEFAULT_ITERATIONS = 10
|
||||
|
||||
private lateinit var ocr: PaddleOCR
|
||||
private lateinit var outputDir: File
|
||||
|
||||
@JvmStatic
|
||||
@BeforeClass
|
||||
fun setUp() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
OpenCVUtils.init(context)
|
||||
|
||||
outputDir = File(context.getExternalFilesDir(null), "ocr_benchmark")
|
||||
outputDir.mkdirs()
|
||||
println("[OCRBenchmark] Output dir: ${outputDir.absolutePath}")
|
||||
|
||||
runBlocking {
|
||||
val batchSize = getInstrumentationArgument(ARG_REC_BATCH_SIZE)?.toIntOrNull() ?: 1
|
||||
val config = PaddleOCRConfig(recBatchSize = batchSize)
|
||||
ocr = PaddleOCR.create(context, config, EngineConfig())
|
||||
}
|
||||
println("[OCRBenchmark] Engine ready, coldLoadTimeMs=${ocr.coldLoadTimeMs}")
|
||||
}
|
||||
|
||||
private fun getInstrumentationArgument(key: String): String? {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
return args[key] as? String
|
||||
}
|
||||
|
||||
private fun saveAndPrint(filename: String, json: JSONObject) {
|
||||
val file = File(outputDir, filename)
|
||||
file.writeText(json.toString(2))
|
||||
println("[OCRBenchmark] Saved: ${file.absolutePath}")
|
||||
println("[OCRBenchmark] ---- $filename ----")
|
||||
json.toString(2).lines().forEach { println("[OCRBenchmark] $it") }
|
||||
println("[OCRBenchmark] ---- end ----")
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Accuracy
|
||||
// ========================================================================
|
||||
|
||||
@Test
|
||||
fun testOCRExportJSON() {
|
||||
val imageBytes = loadBenchmarkImageBytes()
|
||||
val result = runBlocking { ocr.recognize(imageBytes) }
|
||||
val payload = buildExportPayload(result)
|
||||
saveAndPrint("accuracy_export.json", payload)
|
||||
|
||||
assertTrue("Should have results", payload.getJSONArray("items").length() > 0)
|
||||
assertTrue("Should detect text", result.lineCount > 0)
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Latency
|
||||
// ========================================================================
|
||||
|
||||
@Test
|
||||
fun testLatencyBenchmark() {
|
||||
val imageBytes = loadBenchmarkImageBytes()
|
||||
val warmup = getInstrumentationArgument(ARG_WARMUP)?.toIntOrNull() ?: DEFAULT_WARMUP
|
||||
val iterations = getInstrumentationArgument(ARG_ITERATIONS)?.toIntOrNull() ?: DEFAULT_ITERATIONS
|
||||
|
||||
println("[OCRBenchmark] Warming up $warmup iterations...")
|
||||
runBlocking { repeat(warmup) { ocr.recognize(imageBytes) } }
|
||||
|
||||
println("[OCRBenchmark] Measuring $iterations iterations...")
|
||||
val totals = mutableListOf<Long>()
|
||||
val dets = mutableListOf<Long>()
|
||||
val detPre = mutableListOf<Long>()
|
||||
val detInf = mutableListOf<Long>()
|
||||
val detPost = mutableListOf<Long>()
|
||||
val recs = mutableListOf<Long>()
|
||||
val recPre = mutableListOf<Long>()
|
||||
val recInf = mutableListOf<Long>()
|
||||
val recPost = mutableListOf<Long>()
|
||||
val overheads = mutableListOf<Long>()
|
||||
val perLineMs = mutableListOf<Long>()
|
||||
val detShapes = mutableListOf<List<Int>>()
|
||||
val recShapes = mutableListOf<List<Int>>()
|
||||
var firstLineCount = 0
|
||||
|
||||
runBlocking {
|
||||
repeat(iterations) { i ->
|
||||
val r = ocr.recognize(imageBytes)
|
||||
if (i == 0) firstLineCount = r.lineCount
|
||||
totals.add(r.totalTimeMs)
|
||||
dets.add(r.detectionTimeMs)
|
||||
detPre.add(r.detPreprocessMs)
|
||||
detInf.add(r.detInferenceMs)
|
||||
detPost.add(r.detPostprocessMs)
|
||||
recs.add(r.recognitionTimeMs)
|
||||
recPre.add(r.recPreprocessMs)
|
||||
recInf.add(r.recInferenceMs)
|
||||
recPost.add(r.recPostprocessMs)
|
||||
overheads.add(r.pipelineOverheadMs)
|
||||
detShapes.add(r.detInputShape)
|
||||
recShapes.addAll(r.recInputShapes)
|
||||
perLineMs.addAll(r.perLineRecMs)
|
||||
if ((i + 1) % 5 == 0) println("[OCRBenchmark] $i/${iterations}...")
|
||||
}
|
||||
}
|
||||
|
||||
val memInfo = Debug.MemoryInfo()
|
||||
Debug.getMemoryInfo(memInfo)
|
||||
|
||||
val payload = JSONObject().apply {
|
||||
put("schemaVersion", 1)
|
||||
put("deviceModel", Build.MODEL)
|
||||
put("osVersion", Build.VERSION.RELEASE)
|
||||
put("ortExecutionProvider", "CPU")
|
||||
put("inputImage", BenchmarkFixtures.defaultReferenceImageName)
|
||||
put("inputBytes", imageBytes.size)
|
||||
put("warmupIterations", warmup)
|
||||
put("measuredIterations", iterations)
|
||||
put("firstMeasuredLineCount", firstLineCount)
|
||||
put("coldLoadTimeMs", ocr.coldLoadTimeMs)
|
||||
if (totals.isNotEmpty()) {
|
||||
put("firstMeasuredRun", JSONObject().apply {
|
||||
put("totalTimeMs", totals.first())
|
||||
put("detectionTimeMs", dets.first())
|
||||
put("recognitionTimeMs", recs.first())
|
||||
put("pipelineOverheadTimeMs", overheads.first())
|
||||
})
|
||||
}
|
||||
put("totalTimeMs", summarizeMs(totals).toJson())
|
||||
put("detectionTimeMs", summarizeMs(dets).toJson())
|
||||
put("detectionPreprocessTimeMs", summarizeMs(detPre).toJson())
|
||||
put("detectionInferenceTimeMs", summarizeMs(detInf).toJson())
|
||||
put("detectionPostprocessTimeMs", summarizeMs(detPost).toJson())
|
||||
put("recognitionTimeMs", summarizeMs(recs).toJson())
|
||||
put("recognitionPreprocessTimeMs", summarizeMs(recPre).toJson())
|
||||
put("recognitionInferenceTimeMs", summarizeMs(recInf).toJson())
|
||||
put("recognitionPostprocessTimeMs", summarizeMs(recPost).toJson())
|
||||
put("pipelineOverheadTimeMs", summarizeMs(overheads).toJson())
|
||||
put("memoryPssKb", memInfo.totalPss)
|
||||
put("inputShapeDistribution", JSONObject().apply {
|
||||
put("detection", summarizeShapes(detShapes))
|
||||
put("recognition", summarizeShapes(recShapes))
|
||||
})
|
||||
if (perLineMs.isNotEmpty()) {
|
||||
put("recognitionPerLine", JSONObject().apply {
|
||||
put("pooled", JSONObject().apply {
|
||||
put("count", perLineMs.size)
|
||||
put("totalMs", summarizeMs(perLineMs).toJson())
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
saveAndPrint("latency_benchmark.json", payload)
|
||||
printSpeedSummary(warmup, iterations, totals, dets, detPre, detInf, detPost, recs, recPre, recInf, recPost, overheads, firstLineCount)
|
||||
|
||||
assertTrue("Should complete all iterations", totals.size == iterations)
|
||||
assertTrue("Should detect text", firstLineCount > 0)
|
||||
}
|
||||
|
||||
private fun printSpeedSummary(
|
||||
warmup: Int,
|
||||
iterations: Int,
|
||||
totals: List<Long>,
|
||||
dets: List<Long>,
|
||||
detPre: List<Long>,
|
||||
detInf: List<Long>,
|
||||
detPost: List<Long>,
|
||||
recs: List<Long>,
|
||||
recPre: List<Long>,
|
||||
recInf: List<Long>,
|
||||
recPost: List<Long>,
|
||||
overheads: List<Long>,
|
||||
lineCount: Int,
|
||||
) {
|
||||
val bar = "+-----------------------------+----------+----------+----------+----------+"
|
||||
val header = "| Stage | Mean ms | Stdev | P90 | Min ms |"
|
||||
fun row(label: String, samples: List<Long>): String {
|
||||
if (samples.isEmpty()) return "| %-27s | %8s | %8s | %8s | %8s |".format(label, "-", "-", "-", "N/A")
|
||||
val mean = samples.map { it.toDouble() }.average()
|
||||
val variance = if (samples.size > 1) samples.map { (it - mean).pow(2) }.average() else 0.0
|
||||
val stdev = sqrt(variance)
|
||||
val sorted = samples.sorted()
|
||||
val p90 = sorted[(0.9 * (sorted.size - 1)).toInt()]
|
||||
val min = sorted.first()
|
||||
return "| %-27s | %8.2f | %8.2f | %8d | %8d |".format(label, mean, stdev, p90, min)
|
||||
}
|
||||
|
||||
println("[OCRBenchmark] ")
|
||||
println("[OCRBenchmark] ╔════════════════════════════════════════════════════════════════════════════════╗")
|
||||
println("[OCRBenchmark] ║ PP-OCRv6 Speed Benchmark Results ║")
|
||||
println("[OCRBenchmark] ╠════════════════════════════════════════════════════════════════════════════════╣")
|
||||
println("[OCRBenchmark] ║ Device: ${Build.MODEL} | OS: Android ${Build.VERSION.RELEASE} | Lines: $lineCount")
|
||||
println("[OCRBenchmark] ║ Cold load: ${ocr.coldLoadTimeMs}ms | Warmup: $warmup | Measured: $iterations")
|
||||
println("[OCRBenchmark] ╠════════════════════════════════════════════════════════════════════════════════╣")
|
||||
println("[OCRBenchmark] $bar")
|
||||
println("[OCRBenchmark] $header")
|
||||
println("[OCRBenchmark] $bar")
|
||||
println("[OCRBenchmark] ${row("Total pipeline", totals)}")
|
||||
println("[OCRBenchmark] $bar")
|
||||
println("[OCRBenchmark] ${row(" Detection (total)", dets)}")
|
||||
println("[OCRBenchmark] ${row(" Preprocess", detPre)}")
|
||||
println("[OCRBenchmark] ${row(" Inference", detInf)}")
|
||||
println("[OCRBenchmark] ${row(" Postprocess", detPost)}")
|
||||
println("[OCRBenchmark] ${row(" Recognition (total)", recs)}")
|
||||
println("[OCRBenchmark] ${row(" Preprocess", recPre)}")
|
||||
println("[OCRBenchmark] ${row(" Inference", recInf)}")
|
||||
println("[OCRBenchmark] ${row(" Postprocess", recPost)}")
|
||||
println("[OCRBenchmark] ${row(" Pipeline overhead", overheads)}")
|
||||
println("[OCRBenchmark] $bar")
|
||||
println("[OCRBenchmark] ╚════════════════════════════════════════════════════════════════════════════════╝")
|
||||
println("[OCRBenchmark] ")
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Memory
|
||||
// ========================================================================
|
||||
|
||||
@Test
|
||||
fun testMemoryBenchmark() {
|
||||
val imageBytes = loadBenchmarkImageBytes()
|
||||
val warmup = getInstrumentationArgument(ARG_WARMUP)?.toIntOrNull() ?: DEFAULT_WARMUP
|
||||
val iterations = getInstrumentationArgument(ARG_ITERATIONS)?.toIntOrNull() ?: DEFAULT_ITERATIONS
|
||||
|
||||
runBlocking { repeat(warmup) { ocr.recognize(imageBytes) } }
|
||||
Runtime.getRuntime().gc()
|
||||
Thread.sleep(500)
|
||||
|
||||
val before = Debug.MemoryInfo()
|
||||
Debug.getMemoryInfo(before)
|
||||
|
||||
runBlocking { repeat(iterations) { ocr.recognize(imageBytes) } }
|
||||
|
||||
val after = Debug.MemoryInfo()
|
||||
Debug.getMemoryInfo(after)
|
||||
|
||||
val payload = JSONObject().apply {
|
||||
put("schemaVersion", 1)
|
||||
put("deviceModel", Build.MODEL)
|
||||
put("iterations", iterations)
|
||||
put("memoryBeforePssKb", before.totalPss)
|
||||
put("memoryAfterPssKb", after.totalPss)
|
||||
put("memoryDeltaPssKb", after.totalPss - before.totalPss)
|
||||
put("nativeBeforeKb", before.nativePss)
|
||||
put("nativeAfterKb", after.nativePss)
|
||||
put("dalvikBeforeKb", before.dalvikPss)
|
||||
put("dalvikAfterKb", after.dalvikPss)
|
||||
}
|
||||
|
||||
saveAndPrint("memory_benchmark.json", payload)
|
||||
assertTrue("Memory should be measurable", after.totalPss > 0)
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Helpers
|
||||
// ========================================================================
|
||||
|
||||
private fun loadBenchmarkImageBytes(): ByteArray {
|
||||
val context = InstrumentationRegistry.getInstrumentation().context
|
||||
val stem = BenchmarkFixtures.defaultReferenceImageName.substringBeforeLast(".")
|
||||
val resId = context.resources.getIdentifier(stem, "raw", context.packageName)
|
||||
if (resId == 0) {
|
||||
throw IllegalStateException(
|
||||
"Missing ${BenchmarkFixtures.defaultReferenceImageName} " +
|
||||
"(package=${context.packageName})"
|
||||
)
|
||||
}
|
||||
return context.resources.openRawResource(resId).use { it.readBytes() }
|
||||
}
|
||||
|
||||
data class TimingSummary(val mean: Double, val stdev: Double, val p90: Double) {
|
||||
fun toJson() = JSONObject().apply {
|
||||
put("mean", mean)
|
||||
put("stdev", stdev)
|
||||
put("p90", p90)
|
||||
}
|
||||
}
|
||||
|
||||
private fun summarizeMs(samples: List<Long>): TimingSummary {
|
||||
if (samples.isEmpty()) return TimingSummary(0.0, 0.0, 0.0)
|
||||
val doubles = samples.map { it.toDouble() }
|
||||
val mean = doubles.average()
|
||||
val variance = if (doubles.size > 1)
|
||||
doubles.map { (it - mean).pow(2) }.average()
|
||||
else 0.0
|
||||
val stdev = sqrt(variance)
|
||||
val sorted = doubles.sorted()
|
||||
val p90Idx = (0.9 * (sorted.size - 1)).toInt().coerceIn(0, sorted.size - 1)
|
||||
return TimingSummary(mean, stdev, sorted[p90Idx])
|
||||
}
|
||||
|
||||
private fun summarizeShapes(shapes: List<List<Int>>): JSONArray {
|
||||
val counts = mutableMapOf<String, Int>()
|
||||
shapes.forEach { shape ->
|
||||
val key = shape.joinToString(",")
|
||||
counts[key] = (counts[key] ?: 0) + 1
|
||||
}
|
||||
return JSONArray().apply {
|
||||
counts.entries.sortedByDescending { it.value }.forEach { (shape, count) ->
|
||||
put(JSONObject().apply {
|
||||
put("shape", JSONArray(shape.split(",").map { it.toInt() }))
|
||||
put("count", count)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildExportPayload(result: OCRRunResult): JSONObject {
|
||||
val items = JSONArray().apply {
|
||||
result.results.forEach { r ->
|
||||
put(JSONObject().apply {
|
||||
put("polygon", JSONArray().apply {
|
||||
r.box.points.forEach { pt ->
|
||||
put(JSONArray(listOf(pt.x.toInt(), pt.y.toInt())))
|
||||
}
|
||||
})
|
||||
put("text", r.text)
|
||||
put("score", r.confidence.toDouble())
|
||||
})
|
||||
}
|
||||
}
|
||||
return JSONObject().apply {
|
||||
put("schemaVersion", 1)
|
||||
put("source", "android_ocr_demo")
|
||||
put("items", items)
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 389 KiB |
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr
|
||||
|
||||
data class EngineConfig(
|
||||
val numThreads: Int = 4,
|
||||
)
|
||||
@@ -0,0 +1,118 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import com.paddle.ocr.engine.OCREngine
|
||||
import com.paddle.ocr.engine.OCREngineResult
|
||||
import com.paddle.ocr.model.OCRRunResult
|
||||
import com.paddle.ocr.model.OCRError
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class PaddleOCR private constructor(
|
||||
private val engine: OCREngine,
|
||||
) {
|
||||
/** Time spent loading ONNX models (milliseconds). */
|
||||
val coldLoadTimeMs: Long get() = engine.coldLoadTimeMs
|
||||
|
||||
companion object {
|
||||
|
||||
suspend fun create(context: Context): PaddleOCR {
|
||||
val appContext = context.applicationContext
|
||||
return withContext(Dispatchers.IO) {
|
||||
val engine = OCREngine(appContext, PaddleOCRConfig(), EngineConfig())
|
||||
PaddleOCR(engine)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun create(
|
||||
context: Context,
|
||||
config: PaddleOCRConfig,
|
||||
engineConfig: EngineConfig = EngineConfig(),
|
||||
): PaddleOCR {
|
||||
val appContext = context.applicationContext
|
||||
return withContext(Dispatchers.IO) {
|
||||
val engine = OCREngine(appContext, config, engineConfig)
|
||||
PaddleOCR(engine)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun create(
|
||||
context: Context,
|
||||
config: PaddleOCRConfig,
|
||||
engineConfig: EngineConfig,
|
||||
detModelAssetPath: String,
|
||||
recModelAssetPath: String,
|
||||
recConfigAssetPath: String,
|
||||
): PaddleOCR {
|
||||
val appContext = context.applicationContext
|
||||
return withContext(Dispatchers.IO) {
|
||||
val engine = OCREngine(
|
||||
appContext, config, engineConfig,
|
||||
detModelAsset = detModelAssetPath,
|
||||
recModelAsset = recModelAssetPath,
|
||||
recConfigAsset = recConfigAssetPath,
|
||||
)
|
||||
PaddleOCR(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun recognize(bitmap: Bitmap): OCRRunResult {
|
||||
if (bitmap.width == 0 || bitmap.height == 0) {
|
||||
throw OCRError.InvalidImage()
|
||||
}
|
||||
return recognizeResult { engine.run(bitmap) }
|
||||
}
|
||||
|
||||
suspend fun recognize(imageBytes: ByteArray): OCRRunResult {
|
||||
if (imageBytes.isEmpty()) {
|
||||
throw OCRError.InvalidImage()
|
||||
}
|
||||
return recognizeResult { engine.run(imageBytes) }
|
||||
}
|
||||
|
||||
private suspend fun recognizeResult(runEngine: () -> OCREngineResult): OCRRunResult {
|
||||
return withContext(Dispatchers.IO) {
|
||||
val result = runEngine()
|
||||
OCRRunResult(
|
||||
results = result.results,
|
||||
detectionTimeMs = result.detectionTimeMs,
|
||||
recognitionTimeMs = result.recognitionTimeMs,
|
||||
totalTimeMs = result.totalTimeMs,
|
||||
lineCount = result.lineCount,
|
||||
detPreprocessMs = result.detPreprocessMs,
|
||||
detInferenceMs = result.detInferenceMs,
|
||||
detPostprocessMs = result.detPostprocessMs,
|
||||
recPreprocessMs = result.recPreprocessMs,
|
||||
recInferenceMs = result.recInferenceMs,
|
||||
recPostprocessMs = result.recPostprocessMs,
|
||||
pipelineOverheadMs = result.pipelineOverheadMs,
|
||||
coldLoadTimeMs = result.coldLoadTimeMs,
|
||||
detInputShape = result.detInputShape,
|
||||
recInputShapes = result.recInputShapes,
|
||||
perLineRecMs = result.perLineRecMs,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun release() {
|
||||
withContext(Dispatchers.IO) {
|
||||
engine.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr
|
||||
|
||||
data class PaddleOCRConfig(
|
||||
val detImgMode: String = "BGR",
|
||||
val detLimitSideLen: Int = 64,
|
||||
val detLimitType: String = "min",
|
||||
val detMaxSideLimit: Int = 4000,
|
||||
val detThresh: Float = 0.3f,
|
||||
val detBoxThresh: Float = 0.6f,
|
||||
val detUnclipRatio: Float = 1.5f,
|
||||
val detMaxCandidates: Int = 3000,
|
||||
val detUseDilation: Boolean = false,
|
||||
val detScoreMode: String = "fast",
|
||||
val detBoxType: String = "quad",
|
||||
val recScoreThresh: Float = 0.0f,
|
||||
val recBatchSize: Int = 1,
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.engine
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.paddle.ocr.PaddleOCRConfig
|
||||
import com.paddle.ocr.model.OCRBox
|
||||
import com.paddle.ocr.postprocess.DBPostProcessor
|
||||
import com.paddle.ocr.preprocess.DetPreprocessResult
|
||||
import com.paddle.ocr.preprocess.DetPreprocessor
|
||||
import org.opencv.core.Mat
|
||||
|
||||
class DetectionEngine(
|
||||
private val ortManager: ORTSessionManager,
|
||||
private val config: PaddleOCRConfig,
|
||||
) {
|
||||
data class DetectionResult(
|
||||
val boxes: List<OCRBox>,
|
||||
val preprocessMs: Long,
|
||||
val inferenceMs: Long,
|
||||
val postprocessMs: Long,
|
||||
val timeMs: Long,
|
||||
val inputShape: List<Int>,
|
||||
)
|
||||
|
||||
fun detect(bitmap: Bitmap): DetectionResult {
|
||||
return detect {
|
||||
DetPreprocessor.preprocess(
|
||||
bitmap,
|
||||
config.detLimitSideLen,
|
||||
config.detLimitType,
|
||||
config.detMaxSideLimit,
|
||||
config.detImgMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun detect(src: Mat): DetectionResult {
|
||||
return detect {
|
||||
DetPreprocessor.preprocess(
|
||||
src,
|
||||
config.detLimitSideLen,
|
||||
config.detLimitType,
|
||||
config.detMaxSideLimit,
|
||||
config.detImgMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun detect(preprocessor: () -> DetPreprocessResult): DetectionResult {
|
||||
val preStart = System.currentTimeMillis()
|
||||
val preResult = preprocessor()
|
||||
val preprocessMs = System.currentTimeMillis() - preStart
|
||||
|
||||
val infStart = System.currentTimeMillis()
|
||||
val (outputData, outputShape) = ortManager.runDetection(preResult.tensorData, preResult.shape)
|
||||
val inferenceMs = System.currentTimeMillis() - infStart
|
||||
|
||||
val postStart = System.currentTimeMillis()
|
||||
val boxes = DBPostProcessor.process(
|
||||
pred = outputData,
|
||||
predShape = outputShape,
|
||||
thresh = config.detThresh,
|
||||
boxThresh = config.detBoxThresh,
|
||||
unclipRatio = config.detUnclipRatio,
|
||||
maxCandidates = config.detMaxCandidates,
|
||||
useDilation = config.detUseDilation,
|
||||
scoreMode = config.detScoreMode,
|
||||
boxType = config.detBoxType,
|
||||
originalH = preResult.originalH,
|
||||
originalW = preResult.originalW,
|
||||
)
|
||||
val postprocessMs = System.currentTimeMillis() - postStart
|
||||
|
||||
return DetectionResult(
|
||||
boxes = boxes,
|
||||
preprocessMs = preprocessMs,
|
||||
inferenceMs = inferenceMs,
|
||||
postprocessMs = postprocessMs,
|
||||
timeMs = preprocessMs + inferenceMs + postprocessMs,
|
||||
inputShape = listOf(1, 3, preResult.shape[2].toInt(), preResult.shape[3].toInt()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.engine
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import com.paddle.ocr.EngineConfig
|
||||
import com.paddle.ocr.PaddleOCRConfig
|
||||
import com.paddle.ocr.model.ModelConfig
|
||||
import com.paddle.ocr.model.OCRError
|
||||
import com.paddle.ocr.model.OCRResult
|
||||
import com.paddle.ocr.postprocess.BoxSorter
|
||||
import com.paddle.ocr.postprocess.QuadTextCrop
|
||||
import com.paddle.ocr.util.BitmapUtils
|
||||
|
||||
class OCREngine(
|
||||
context: Context,
|
||||
private val config: PaddleOCRConfig,
|
||||
engineConfig: EngineConfig,
|
||||
detModelAsset: String = "models/det/inference.onnx",
|
||||
recModelAsset: String = "models/rec/inference.onnx",
|
||||
recConfigAsset: String = "models/rec/inference.yml",
|
||||
) {
|
||||
private val ortManager = ORTSessionManager(context, engineConfig)
|
||||
private val detectionEngine: DetectionEngine
|
||||
private val recognitionEngine: RecognitionEngine
|
||||
val coldLoadTimeMs: Long get() = ortManager.coldLoadTimeMs
|
||||
|
||||
init {
|
||||
val configured = try {
|
||||
ortManager.loadModels(detModelAsset, recModelAsset)
|
||||
val recModelConfig = ModelConfig.parse(context, recConfigAsset)
|
||||
recModelConfig
|
||||
} catch (t: Throwable) {
|
||||
ortManager.release()
|
||||
throw t
|
||||
}
|
||||
detectionEngine = DetectionEngine(ortManager, config)
|
||||
recognitionEngine = RecognitionEngine(ortManager, configured.characterList)
|
||||
}
|
||||
|
||||
fun run(bitmap: Bitmap): OCREngineResult {
|
||||
val srcMat = BitmapUtils.bitmapToBGRMat(bitmap)
|
||||
return runWithOwnedMat(srcMat)
|
||||
}
|
||||
|
||||
fun run(imageBytes: ByteArray): OCREngineResult {
|
||||
val srcMat = BitmapUtils.imdecodeBGR(imageBytes)
|
||||
if (srcMat.empty()) {
|
||||
srcMat.release()
|
||||
throw OCRError.InvalidImage()
|
||||
}
|
||||
return runWithOwnedMat(srcMat)
|
||||
}
|
||||
|
||||
private fun runWithOwnedMat(srcMat: org.opencv.core.Mat): OCREngineResult {
|
||||
return try {
|
||||
run(srcMat)
|
||||
} finally {
|
||||
srcMat.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun run(srcMat: org.opencv.core.Mat): OCREngineResult {
|
||||
val totalStart = System.currentTimeMillis()
|
||||
val detResult = detectionEngine.detect(srcMat)
|
||||
val boxes = detResult.boxes
|
||||
|
||||
if (boxes.isEmpty()) {
|
||||
val elapsed = System.currentTimeMillis() - totalStart
|
||||
return OCREngineResult(
|
||||
results = emptyList(),
|
||||
detectionTimeMs = detResult.timeMs,
|
||||
recognitionTimeMs = 0,
|
||||
totalTimeMs = elapsed,
|
||||
lineCount = 0,
|
||||
detPreprocessMs = detResult.preprocessMs,
|
||||
detInferenceMs = detResult.inferenceMs,
|
||||
detPostprocessMs = detResult.postprocessMs,
|
||||
detInputShape = detResult.inputShape,
|
||||
coldLoadTimeMs = ortManager.coldLoadTimeMs,
|
||||
)
|
||||
}
|
||||
|
||||
// 2. Sort boxes
|
||||
val sortedBoxes = BoxSorter.sortInReadingOrder(boxes)
|
||||
|
||||
// 3. Crop and recognize text regions
|
||||
var totalRecPreMs = 0L
|
||||
var totalRecInfMs = 0L
|
||||
var totalRecPostMs = 0L
|
||||
var totalRecMs = 0L
|
||||
val allResults = mutableListOf<OCRResult>()
|
||||
val recInputShapes = mutableListOf<List<Int>>()
|
||||
val perLineRecMs = mutableListOf<Long>()
|
||||
val batchSize = config.recBatchSize.coerceAtLeast(1)
|
||||
|
||||
var i = 0
|
||||
while (i < sortedBoxes.size) {
|
||||
val batchCrops = mutableListOf<org.opencv.core.Mat>()
|
||||
val batchBoxIndices = mutableListOf<Int>()
|
||||
var next = i
|
||||
while (next < sortedBoxes.size && batchCrops.size < batchSize) {
|
||||
val crop = QuadTextCrop.crop(srcMat, sortedBoxes[next])
|
||||
if (crop.rows() > 0 && crop.cols() > 0) {
|
||||
batchCrops.add(crop)
|
||||
batchBoxIndices.add(next)
|
||||
} else {
|
||||
crop.release()
|
||||
}
|
||||
next++
|
||||
}
|
||||
|
||||
try {
|
||||
if (batchCrops.isNotEmpty()) {
|
||||
val batchResult = recognitionEngine.recognize(batchCrops)
|
||||
totalRecPreMs += batchResult.preprocessMs
|
||||
totalRecInfMs += batchResult.inferenceMs
|
||||
totalRecPostMs += batchResult.postprocessMs
|
||||
totalRecMs += batchResult.timeMs
|
||||
recInputShapes.add(batchResult.inputShape)
|
||||
if (batchSize == 1) {
|
||||
perLineRecMs.add(batchResult.timeMs)
|
||||
}
|
||||
|
||||
for (j in batchResult.texts.indices) {
|
||||
val boxIdx = batchBoxIndices[j]
|
||||
val (text, confidence) = batchResult.texts[j]
|
||||
if (confidence >= config.recScoreThresh) {
|
||||
allResults.add(
|
||||
OCRResult(
|
||||
box = sortedBoxes[boxIdx],
|
||||
text = text,
|
||||
confidence = confidence,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
batchCrops.forEach { it.release() }
|
||||
}
|
||||
i = next
|
||||
}
|
||||
|
||||
val totalElapsed = System.currentTimeMillis() - totalStart
|
||||
val pipelineOverhead = totalElapsed - detResult.timeMs - totalRecMs
|
||||
|
||||
return OCREngineResult(
|
||||
results = allResults,
|
||||
detectionTimeMs = detResult.timeMs,
|
||||
recognitionTimeMs = totalRecMs,
|
||||
totalTimeMs = totalElapsed,
|
||||
lineCount = allResults.size,
|
||||
detPreprocessMs = detResult.preprocessMs,
|
||||
detInferenceMs = detResult.inferenceMs,
|
||||
detPostprocessMs = detResult.postprocessMs,
|
||||
recPreprocessMs = totalRecPreMs,
|
||||
recInferenceMs = totalRecInfMs,
|
||||
recPostprocessMs = totalRecPostMs,
|
||||
pipelineOverheadMs = pipelineOverhead,
|
||||
coldLoadTimeMs = ortManager.coldLoadTimeMs,
|
||||
detInputShape = detResult.inputShape,
|
||||
recInputShapes = recInputShapes,
|
||||
perLineRecMs = perLineRecMs,
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
ortManager.release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.engine
|
||||
|
||||
import com.paddle.ocr.model.OCRResult
|
||||
|
||||
data class OCREngineResult(
|
||||
val results: List<OCRResult>,
|
||||
val detectionTimeMs: Long,
|
||||
val recognitionTimeMs: Long,
|
||||
val totalTimeMs: Long,
|
||||
val lineCount: Int,
|
||||
// Detailed per-stage timing
|
||||
val detPreprocessMs: Long = 0,
|
||||
val detInferenceMs: Long = 0,
|
||||
val detPostprocessMs: Long = 0,
|
||||
val recPreprocessMs: Long = 0,
|
||||
val recInferenceMs: Long = 0,
|
||||
val recPostprocessMs: Long = 0,
|
||||
val pipelineOverheadMs: Long = 0,
|
||||
val coldLoadTimeMs: Long = 0,
|
||||
// Input tensor shapes
|
||||
val detInputShape: List<Int> = emptyList(),
|
||||
val recInputShapes: List<List<Int>> = emptyList(),
|
||||
// Per-line timing (only populated when recBatchSize == 1)
|
||||
val perLineRecMs: List<Long> = emptyList(),
|
||||
)
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.engine
|
||||
|
||||
import ai.onnxruntime.OnnxTensor
|
||||
import ai.onnxruntime.OrtEnvironment
|
||||
import ai.onnxruntime.OrtSession
|
||||
import android.content.Context
|
||||
import com.paddle.ocr.EngineConfig
|
||||
import com.paddle.ocr.model.OCRError
|
||||
import java.nio.FloatBuffer
|
||||
|
||||
class ORTSessionManager(
|
||||
private val context: Context,
|
||||
private val config: EngineConfig,
|
||||
) {
|
||||
private var env: OrtEnvironment? = null
|
||||
private var detSession: OrtSession? = null
|
||||
private var recSession: OrtSession? = null
|
||||
private var detInputName: String = "x"
|
||||
private var recInputName: String = "x"
|
||||
var coldLoadTimeMs: Long = 0
|
||||
private set
|
||||
|
||||
fun loadModels(detAssetPath: String, recAssetPath: String) {
|
||||
val loadStart = System.currentTimeMillis()
|
||||
env = OrtEnvironment.getEnvironment()
|
||||
val opts = OrtSession.SessionOptions().apply {
|
||||
setOptimizationLevel(OrtSession.SessionOptions.OptLevel.ALL_OPT)
|
||||
setIntraOpNumThreads(config.numThreads)
|
||||
}
|
||||
try {
|
||||
val ortEnv = env ?: throw OCRError.ModelLoadFailed("OCR", Exception("Environment not initialized"))
|
||||
val detBytes = readModelAsset(detAssetPath)
|
||||
val recBytes = readModelAsset(recAssetPath)
|
||||
try {
|
||||
detSession = ortEnv.createSession(detBytes, opts)
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ModelLoadFailed("detection", t)
|
||||
}
|
||||
try {
|
||||
recSession = ortEnv.createSession(recBytes, opts)
|
||||
} catch (t: Throwable) {
|
||||
detSession?.close()
|
||||
detSession = null
|
||||
throw OCRError.ModelLoadFailed("recognition", t)
|
||||
}
|
||||
|
||||
detInputName = try {
|
||||
detSession!!.inputNames.iterator().next()
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ModelLoadFailed("detection", t)
|
||||
}
|
||||
recInputName = try {
|
||||
recSession!!.inputNames.iterator().next()
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ModelLoadFailed("recognition", t)
|
||||
}
|
||||
coldLoadTimeMs = System.currentTimeMillis() - loadStart
|
||||
} finally {
|
||||
opts.close()
|
||||
}
|
||||
}
|
||||
|
||||
fun runDetection(input: FloatArray, shape: LongArray): Pair<FloatArray, LongArray> {
|
||||
val session = detSession
|
||||
?: throw OCRError.ModelLoadFailed("detection", Exception("Session not initialized"))
|
||||
val ortEnv = env
|
||||
?: throw OCRError.ModelLoadFailed("detection", Exception("Environment not initialized"))
|
||||
return runSession(ortEnv, session, detInputName, input, shape, "detection")
|
||||
}
|
||||
|
||||
fun runRecognition(input: FloatArray, shape: LongArray): Pair<FloatArray, LongArray> {
|
||||
val session = recSession
|
||||
?: throw OCRError.ModelLoadFailed("recognition", Exception("Session not initialized"))
|
||||
val ortEnv = env
|
||||
?: throw OCRError.ModelLoadFailed("recognition", Exception("Environment not initialized"))
|
||||
return runSession(ortEnv, session, recInputName, input, shape, "recognition")
|
||||
}
|
||||
|
||||
fun release() {
|
||||
try {
|
||||
detSession?.close()
|
||||
} finally {
|
||||
detSession = null
|
||||
try {
|
||||
recSession?.close()
|
||||
} finally {
|
||||
recSession = null
|
||||
env = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readModelAsset(assetPath: String): ByteArray {
|
||||
return try {
|
||||
context.assets.open(assetPath).use { it.readBytes() }
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ModelNotFound(assetPath, t)
|
||||
}
|
||||
}
|
||||
|
||||
private fun runSession(
|
||||
ortEnv: OrtEnvironment,
|
||||
session: OrtSession,
|
||||
inputName: String,
|
||||
input: FloatArray,
|
||||
shape: LongArray,
|
||||
modelName: String,
|
||||
): Pair<FloatArray, LongArray> {
|
||||
val tensor = try {
|
||||
OnnxTensor.createTensor(ortEnv, FloatBuffer.wrap(input), shape)
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.InferenceFailed(modelName, t)
|
||||
}
|
||||
val result = try {
|
||||
try {
|
||||
session.run(mapOf(inputName to tensor))
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.InferenceFailed(modelName, t)
|
||||
}
|
||||
} finally {
|
||||
tensor.close()
|
||||
}
|
||||
|
||||
return try {
|
||||
try {
|
||||
val outputName = session.outputNames.iterator().next()
|
||||
val ortValue = result.get(outputName)
|
||||
.orElseThrow { Exception("No output tensor found") }
|
||||
val outputTensor = ortValue as? OnnxTensor
|
||||
?: throw Exception("Output is not an ONNX tensor")
|
||||
Pair(copyFloatBuffer(outputTensor.floatBuffer), outputTensor.info.shape)
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.InferenceFailed(modelName, t)
|
||||
}
|
||||
} finally {
|
||||
result.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyFloatBuffer(buffer: FloatBuffer): FloatArray {
|
||||
val duplicate = buffer.duplicate()
|
||||
duplicate.rewind()
|
||||
val output = FloatArray(duplicate.remaining())
|
||||
duplicate.get(output)
|
||||
return output
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.engine
|
||||
|
||||
import com.paddle.ocr.postprocess.CTCDecoder
|
||||
import com.paddle.ocr.preprocess.RecPreprocessor
|
||||
import org.opencv.core.Mat
|
||||
|
||||
class RecognitionEngine(
|
||||
private val ortManager: ORTSessionManager,
|
||||
private val characterList: List<String>,
|
||||
) {
|
||||
data class RecognitionResult(
|
||||
val texts: List<Pair<String, Float>>,
|
||||
val preprocessMs: Long,
|
||||
val inferenceMs: Long,
|
||||
val postprocessMs: Long,
|
||||
val timeMs: Long,
|
||||
val inputShape: List<Int>,
|
||||
)
|
||||
|
||||
fun recognize(crops: List<Mat>): RecognitionResult {
|
||||
// Preprocess
|
||||
val preStart = System.currentTimeMillis()
|
||||
val preResult = RecPreprocessor.preprocessBatch(crops)
|
||||
val preprocessMs = System.currentTimeMillis() - preStart
|
||||
|
||||
// Inference
|
||||
val infStart = System.currentTimeMillis()
|
||||
val (outputData, outputShape) = ortManager.runRecognition(preResult.tensorData, preResult.shape)
|
||||
val inferenceMs = System.currentTimeMillis() - infStart
|
||||
|
||||
// Postprocess (CTC decode)
|
||||
val postStart = System.currentTimeMillis()
|
||||
val decoded = CTCDecoder.decode(outputData, outputShape, characterList)
|
||||
val postprocessMs = System.currentTimeMillis() - postStart
|
||||
|
||||
val inputShape = preResult.shape.map { it.toInt() }
|
||||
val timeMs = preprocessMs + inferenceMs + postprocessMs
|
||||
return RecognitionResult(
|
||||
texts = decoded,
|
||||
preprocessMs = preprocessMs,
|
||||
inferenceMs = inferenceMs,
|
||||
postprocessMs = postprocessMs,
|
||||
timeMs = timeMs,
|
||||
inputShape = inputShape,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.model
|
||||
|
||||
import android.content.Context
|
||||
import com.paddle.ocr.util.YamlUtils
|
||||
|
||||
data class ModelConfig(
|
||||
val characterList: List<String>,
|
||||
) {
|
||||
companion object {
|
||||
fun parse(context: Context, assetPath: String): ModelConfig {
|
||||
val content = try {
|
||||
context.assets.open(assetPath).bufferedReader().use { it.readText() }
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ConfigParseFailed(assetPath, t)
|
||||
}
|
||||
val characterDict = try {
|
||||
extractCharacterDict(content, assetPath)
|
||||
} catch (e: OCRError.ConfigParseFailed) {
|
||||
throw e
|
||||
} catch (t: Throwable) {
|
||||
throw OCRError.ConfigParseFailed(assetPath, t)
|
||||
}
|
||||
val charListWithSpace = characterDict.toMutableList().apply {
|
||||
if (lastOrNull() != " ") add(" ")
|
||||
}
|
||||
|
||||
return ModelConfig(characterList = charListWithSpace)
|
||||
}
|
||||
|
||||
private fun extractCharacterDict(content: String, assetPath: String): List<String> {
|
||||
val lines = content.replace("\r\n", "\n").replace('\r', '\n').lines()
|
||||
val postProcessLine = lines.indexOfFirst { it.trim() == "PostProcess:" }
|
||||
if (postProcessLine < 0) {
|
||||
throw OCRError.ConfigParseFailed("Missing PostProcess in $assetPath")
|
||||
}
|
||||
|
||||
val postProcessIndent = YamlUtils.leadingSpaces(lines[postProcessLine])
|
||||
val characterDictLine = findCharacterDictLine(lines, postProcessLine + 1, postProcessIndent)
|
||||
if (characterDictLine < 0) {
|
||||
throw OCRError.ConfigParseFailed("Missing character_dict in $assetPath")
|
||||
}
|
||||
|
||||
val characterDictIndent = YamlUtils.leadingSpaces(lines[characterDictLine])
|
||||
val characters = mutableListOf<String>()
|
||||
var lineIndex = characterDictLine + 1
|
||||
while (lineIndex < lines.size) {
|
||||
val line = lines[lineIndex]
|
||||
val indent = YamlUtils.leadingSpaces(line)
|
||||
val content = line.substring(indent)
|
||||
val keyLikeContent = content.trim()
|
||||
if (keyLikeContent.isEmpty() || keyLikeContent.startsWith("#")) {
|
||||
lineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (!content.startsWith("-")) {
|
||||
if (indent <= characterDictIndent) break
|
||||
lineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
characters.add(parseYamlListScalar(content.substring(1)))
|
||||
lineIndex++
|
||||
}
|
||||
|
||||
if (characters.isEmpty()) {
|
||||
throw OCRError.ConfigParseFailed("Empty character_dict in $assetPath")
|
||||
}
|
||||
return characters
|
||||
}
|
||||
|
||||
private fun findCharacterDictLine(
|
||||
lines: List<String>,
|
||||
startLine: Int,
|
||||
postProcessIndent: Int,
|
||||
): Int {
|
||||
var lineIndex = startLine
|
||||
while (lineIndex < lines.size) {
|
||||
val line = lines[lineIndex]
|
||||
val trimmed = line.trim()
|
||||
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
|
||||
lineIndex++
|
||||
continue
|
||||
}
|
||||
val indent = YamlUtils.leadingSpaces(line)
|
||||
if (indent <= postProcessIndent) break
|
||||
if (trimmed == "character_dict:") return lineIndex
|
||||
lineIndex++
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
private fun parseYamlListScalar(rawValue: String): String {
|
||||
val value = rawValue.dropWhile { it == ' ' }
|
||||
if (value.length >= 2 && value.first() == '\'' && value.last() == '\'') {
|
||||
return value.substring(1, value.length - 1).replace("''", "'")
|
||||
}
|
||||
if (value.length >= 2 && value.first() == '"' && value.last() == '"') {
|
||||
return value.substring(1, value.length - 1)
|
||||
.replace("\\\"", "\"")
|
||||
.replace("\\\\", "\\")
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\r", "\r")
|
||||
.replace("\\t", "\t")
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.model
|
||||
|
||||
import android.graphics.PointF
|
||||
|
||||
data class OCRBox(
|
||||
val points: List<PointF>,
|
||||
) {
|
||||
init {
|
||||
require(points.size == 4) { "OCRBox must have exactly 4 points, got ${points.size}" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.model
|
||||
|
||||
sealed class OCRError(message: String, cause: Throwable? = null) : Exception(message, cause) {
|
||||
class ModelNotFound(modelPath: String, cause: Throwable? = null) : OCRError("Model not found: $modelPath", cause)
|
||||
class ModelLoadFailed(modelName: String, cause: Throwable) : OCRError("Failed to load $modelName model", cause)
|
||||
class ConfigParseFailed(path: String, cause: Throwable? = null) : OCRError("Failed to parse config: $path", cause)
|
||||
class InvalidImage : OCRError("Input image is empty or invalid")
|
||||
class InferenceFailed(stage: String, cause: Throwable) : OCRError("Inference failed at stage '$stage'", cause)
|
||||
class DecodeError(message: String, cause: Throwable? = null) : OCRError(message, cause)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.model
|
||||
|
||||
data class OCRResult(
|
||||
val box: OCRBox,
|
||||
val text: String,
|
||||
val confidence: Float,
|
||||
val wordBoxes: List<OCRBox>? = null,
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.model
|
||||
|
||||
data class OCRRunResult(
|
||||
val results: List<OCRResult>,
|
||||
val detectionTimeMs: Long,
|
||||
val recognitionTimeMs: Long,
|
||||
val totalTimeMs: Long,
|
||||
val lineCount: Int,
|
||||
// Detailed per-stage timing
|
||||
val detPreprocessMs: Long = 0,
|
||||
val detInferenceMs: Long = 0,
|
||||
val detPostprocessMs: Long = 0,
|
||||
val recPreprocessMs: Long = 0,
|
||||
val recInferenceMs: Long = 0,
|
||||
val recPostprocessMs: Long = 0,
|
||||
val pipelineOverheadMs: Long = 0,
|
||||
val coldLoadTimeMs: Long = 0,
|
||||
// Input tensor shapes
|
||||
val detInputShape: List<Int> = emptyList(),
|
||||
val recInputShapes: List<List<Int>> = emptyList(),
|
||||
// Per-line timing (only populated when recBatchSize == 1)
|
||||
val perLineRecMs: List<Long> = emptyList(),
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
import com.paddle.ocr.model.OCRBox
|
||||
|
||||
object BoxSorter {
|
||||
private const val ROW_THRESHOLD_Y = 10f
|
||||
|
||||
fun sortInReadingOrder(boxes: List<OCRBox>): List<OCRBox> {
|
||||
if (boxes.size <= 1) return boxes
|
||||
|
||||
val list = boxes.toMutableList()
|
||||
list.sortWith(compareBy({ it.points[0].y }, { it.points[0].x }))
|
||||
|
||||
// Align with PaddleX SortQuadBoxes: bubble left-to-right inside a 10px row band.
|
||||
for (i in 0 until list.size - 1) {
|
||||
var j = i
|
||||
while (j >= 0) {
|
||||
val next = list[j + 1]
|
||||
val curr = list[j]
|
||||
if (kotlin.math.abs(next.points[0].y - curr.points[0].y) < ROW_THRESHOLD_Y &&
|
||||
next.points[0].x < curr.points[0].x
|
||||
) {
|
||||
list[j] = next
|
||||
list[j + 1] = curr
|
||||
j--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
object CTCDecoder {
|
||||
private const val BLANK_IDX = 0
|
||||
|
||||
fun decode(output: FloatArray, shape: LongArray, characterList: List<String>): List<Pair<String, Float>> {
|
||||
val batchSize = shape[0].toInt()
|
||||
val timeSteps = shape[1].toInt()
|
||||
val numClasses = shape[2].toInt()
|
||||
|
||||
val results = mutableListOf<Pair<String, Float>>()
|
||||
for (b in 0 until batchSize) {
|
||||
val baseOffset = b * timeSteps * numClasses
|
||||
|
||||
val indices = IntArray(timeSteps)
|
||||
val probs = FloatArray(timeSteps)
|
||||
for (t in 0 until timeSteps) {
|
||||
val offset = baseOffset + t * numClasses
|
||||
var maxIdx = 0
|
||||
var maxVal = output[offset]
|
||||
for (c in 1 until numClasses) {
|
||||
val v = output[offset + c]
|
||||
if (v > maxVal) {
|
||||
maxVal = v
|
||||
maxIdx = c
|
||||
}
|
||||
}
|
||||
indices[t] = maxIdx
|
||||
probs[t] = maxVal
|
||||
}
|
||||
|
||||
val keptProbs = mutableListOf<Float>()
|
||||
val sb = StringBuilder()
|
||||
var prevIdx = -1
|
||||
for (t in 0 until timeSteps) {
|
||||
val idx = indices[t]
|
||||
if (idx != BLANK_IDX && idx != prevIdx) {
|
||||
val charIdx = idx - 1
|
||||
if (charIdx >= 0 && charIdx < characterList.size) {
|
||||
sb.append(characterList[charIdx])
|
||||
keptProbs.add(probs[t])
|
||||
}
|
||||
}
|
||||
prevIdx = idx
|
||||
}
|
||||
|
||||
val confidence = if (keptProbs.isNotEmpty()) keptProbs.average().toFloat() else 0f
|
||||
results.add(Pair(sb.toString(), confidence))
|
||||
}
|
||||
return results
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
import android.graphics.PointF
|
||||
import com.paddle.ocr.model.OCRBox
|
||||
import com.paddle.ocr.util.MathUtils
|
||||
import org.opencv.core.Core
|
||||
import org.opencv.core.CvType
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.MatOfPoint
|
||||
import org.opencv.core.MatOfPoint2f
|
||||
import org.opencv.core.Point
|
||||
import org.opencv.core.Scalar
|
||||
import org.opencv.imgproc.Imgproc
|
||||
|
||||
object DBPostProcessor {
|
||||
private const val MIN_SIZE_BEFORE_UNCLIP = 3f
|
||||
private const val MIN_SIZE_AFTER_UNCLIP = 5f
|
||||
|
||||
fun process(
|
||||
pred: FloatArray,
|
||||
predShape: LongArray,
|
||||
thresh: Float,
|
||||
boxThresh: Float,
|
||||
unclipRatio: Float,
|
||||
maxCandidates: Int,
|
||||
useDilation: Boolean,
|
||||
scoreMode: String,
|
||||
boxType: String,
|
||||
originalH: Int,
|
||||
originalW: Int,
|
||||
): List<OCRBox> {
|
||||
require(boxType == "quad") { "Only DBPostProcess box_type=quad is supported" }
|
||||
|
||||
val pH = predShape[2].toInt()
|
||||
val pW = predShape[3].toInt()
|
||||
val scaleX = originalW.toDouble() / pW
|
||||
val scaleY = originalH.toDouble() / pH
|
||||
val normalizedScoreMode = scoreMode.lowercase()
|
||||
|
||||
val rawProb = Mat(pH, pW, CvType.CV_32FC1)
|
||||
val mask = Mat(pH, pW, CvType.CV_8UC1)
|
||||
val contours = mutableListOf<MatOfPoint>()
|
||||
val hierarchy = Mat()
|
||||
var contourMask = mask
|
||||
|
||||
return try {
|
||||
rawProb.put(0, 0, pred)
|
||||
val threshMat = Mat()
|
||||
try {
|
||||
Imgproc.threshold(rawProb, threshMat, thresh.toDouble(), 255.0, Imgproc.THRESH_BINARY)
|
||||
threshMat.convertTo(mask, CvType.CV_8UC1)
|
||||
} finally {
|
||||
threshMat.release()
|
||||
}
|
||||
|
||||
contourMask = if (useDilation) {
|
||||
val kernel = Mat.ones(2, 2, CvType.CV_8UC1)
|
||||
try {
|
||||
Mat().also { Imgproc.dilate(mask, it, kernel) }
|
||||
} finally {
|
||||
kernel.release()
|
||||
}
|
||||
} else {
|
||||
mask
|
||||
}
|
||||
|
||||
Imgproc.findContours(contourMask, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE)
|
||||
val boxes = mutableListOf<OCRBox>()
|
||||
val numContours = minOf(contours.size, maxCandidates)
|
||||
for (index in 0 until numContours) {
|
||||
val contour = contours[index]
|
||||
val contour2f = MatOfPoint2f(*contour.toArray())
|
||||
val rect = try {
|
||||
Imgproc.minAreaRect(contour2f)
|
||||
} finally {
|
||||
contour2f.release()
|
||||
}
|
||||
val sside = minOf(rect.size.width, rect.size.height)
|
||||
if (sside < MIN_SIZE_BEFORE_UNCLIP) continue
|
||||
|
||||
val rectPoints = Array(4) { Point() }
|
||||
rect.points(rectPoints)
|
||||
val orderedPoints = QuadGeometry.orderMinAreaRectPoints(rectPoints)
|
||||
val score = if (normalizedScoreMode == "slow") {
|
||||
computeBoxScore(rawProb, contour.toList())
|
||||
} else {
|
||||
computeBoxScore(rawProb, orderedPoints)
|
||||
}
|
||||
if (score < boxThresh) continue
|
||||
|
||||
val expandedPts = PolygonUnclip.unclip(orderedPoints, unclipRatio)
|
||||
val expandedRect = MatOfPoint2f().let { expanded2f ->
|
||||
try {
|
||||
expanded2f.fromList(expandedPts)
|
||||
Imgproc.minAreaRect(expanded2f)
|
||||
} finally {
|
||||
expanded2f.release()
|
||||
}
|
||||
}
|
||||
val sside2 = minOf(expandedRect.size.width, expandedRect.size.height)
|
||||
if (sside2 < MIN_SIZE_AFTER_UNCLIP) continue
|
||||
|
||||
val expandedBox = Array(4) { Point() }
|
||||
expandedRect.points(expandedBox)
|
||||
val ePts = QuadGeometry.orderMinAreaRectPoints(expandedBox)
|
||||
val scaled = listOf(
|
||||
scalePoint(ePts[0], scaleX, scaleY, originalW, originalH),
|
||||
scalePoint(ePts[1], scaleX, scaleY, originalW, originalH),
|
||||
scalePoint(ePts[2], scaleX, scaleY, originalW, originalH),
|
||||
scalePoint(ePts[3], scaleX, scaleY, originalW, originalH),
|
||||
)
|
||||
|
||||
val boxW = kotlin.math.hypot(
|
||||
scaled[1].x - scaled[0].x,
|
||||
scaled[1].y - scaled[0].y,
|
||||
)
|
||||
val boxH = kotlin.math.hypot(
|
||||
scaled[3].x - scaled[0].x,
|
||||
scaled[3].y - scaled[0].y,
|
||||
)
|
||||
if (boxW <= 3 || boxH <= 3) continue
|
||||
|
||||
boxes.add(OCRBox(points = scaled))
|
||||
}
|
||||
boxes
|
||||
} finally {
|
||||
hierarchy.release()
|
||||
if (contourMask !== mask) {
|
||||
contourMask.release()
|
||||
}
|
||||
contours.forEach { it.release() }
|
||||
mask.release()
|
||||
rawProb.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun scalePoint(
|
||||
point: Point,
|
||||
scaleX: Double,
|
||||
scaleY: Double,
|
||||
originalW: Int,
|
||||
originalH: Int,
|
||||
): PointF {
|
||||
return PointF(
|
||||
MathUtils.roundHalfToEven(point.x * scaleX).coerceIn(0, originalW).toFloat(),
|
||||
MathUtils.roundHalfToEven(point.y * scaleY).coerceIn(0, originalH).toFloat(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun computeBoxScore(probMap: Mat, points: List<Point>): Float {
|
||||
if (points.isEmpty()) return 0f
|
||||
|
||||
val h = probMap.rows()
|
||||
val w = probMap.cols()
|
||||
val xmin = points.minOf { kotlin.math.floor(it.x).toInt() }.coerceIn(0, w - 1)
|
||||
val xmax = points.maxOf { kotlin.math.ceil(it.x).toInt() }.coerceIn(0, w - 1)
|
||||
val ymin = points.minOf { kotlin.math.floor(it.y).toInt() }.coerceIn(0, h - 1)
|
||||
val ymax = points.maxOf { kotlin.math.ceil(it.y).toInt() }.coerceIn(0, h - 1)
|
||||
|
||||
val mask = Mat(ymax - ymin + 1, xmax - xmin + 1, CvType.CV_8UC1, Scalar(0.0))
|
||||
val pts = MatOfPoint().apply {
|
||||
fromList(
|
||||
points.map { Point((it.x - xmin).toInt().toDouble(), (it.y - ymin).toInt().toDouble()) }
|
||||
)
|
||||
}
|
||||
Imgproc.fillPoly(mask, mutableListOf(pts), Scalar(1.0))
|
||||
|
||||
val roi = probMap.submat(ymin, ymax + 1, xmin, xmax + 1)
|
||||
val mean = Core.mean(roi, mask)
|
||||
roi.release()
|
||||
mask.release()
|
||||
pts.release()
|
||||
return mean.`val`[0].toFloat()
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
import org.opencv.core.Point
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.acos
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.sin
|
||||
|
||||
internal object PolygonUnclip {
|
||||
private const val EPS = 1e-6
|
||||
private const val ARC_TOLERANCE = 0.25
|
||||
|
||||
fun unclip(points: List<Point>, unclipRatio: Float): List<Point> {
|
||||
if (points.size < 3) return points
|
||||
|
||||
val signedArea = signedArea(points)
|
||||
val area = abs(signedArea)
|
||||
val perimeter = perimeter(points)
|
||||
if (!area.isFinite() || !perimeter.isFinite() || area <= EPS || perimeter <= EPS) {
|
||||
return points
|
||||
}
|
||||
|
||||
val distance = area * unclipRatio / perimeter
|
||||
if (!distance.isFinite() || distance <= EPS) return points
|
||||
|
||||
val clockwiseInImageCoords = signedArea > 0.0
|
||||
val normals = mutableListOf<Point>()
|
||||
for (i in points.indices) {
|
||||
val start = points[i]
|
||||
val end = points[(i + 1) % points.size]
|
||||
val dx = end.x - start.x
|
||||
val dy = end.y - start.y
|
||||
val len = hypot(dx, dy)
|
||||
if (!len.isFinite() || len <= EPS) return points
|
||||
|
||||
val normal = if (clockwiseInImageCoords) {
|
||||
Point(dy / len, -dx / len)
|
||||
} else {
|
||||
Point(-dy / len, dx / len)
|
||||
}
|
||||
normals.add(normal)
|
||||
}
|
||||
|
||||
val expanded = mutableListOf<Point>()
|
||||
for (i in points.indices) {
|
||||
appendRoundJoin(
|
||||
output = expanded,
|
||||
center = points[i],
|
||||
fromNormal = normals[(i - 1 + normals.size) % normals.size],
|
||||
toNormal = normals[i],
|
||||
distance = distance,
|
||||
clockwiseInImageCoords = clockwiseInImageCoords,
|
||||
)
|
||||
}
|
||||
return if (expanded.size >= 3) expanded else points
|
||||
}
|
||||
|
||||
private fun appendRoundJoin(
|
||||
output: MutableList<Point>,
|
||||
center: Point,
|
||||
fromNormal: Point,
|
||||
toNormal: Point,
|
||||
distance: Double,
|
||||
clockwiseInImageCoords: Boolean,
|
||||
) {
|
||||
var startAngle = atan2(fromNormal.y, fromNormal.x)
|
||||
var endAngle = atan2(toNormal.y, toNormal.x)
|
||||
if (clockwiseInImageCoords) {
|
||||
while (endAngle < startAngle) endAngle += 2.0 * PI
|
||||
} else {
|
||||
while (endAngle > startAngle) endAngle -= 2.0 * PI
|
||||
}
|
||||
|
||||
val sweep = endAngle - startAngle
|
||||
val steps = ceil(abs(sweep) / arcStepAngle(distance)).toInt().coerceAtLeast(1)
|
||||
for (step in 0..steps) {
|
||||
val angle = startAngle + sweep * step.toDouble() / steps.toDouble()
|
||||
appendPoint(
|
||||
output,
|
||||
Point(
|
||||
center.x + cos(angle) * distance,
|
||||
center.y + sin(angle) * distance,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun arcStepAngle(distance: Double): Double {
|
||||
val ratio = (1.0 - ARC_TOLERANCE / distance).coerceIn(-1.0, 1.0)
|
||||
val step = 2.0 * acos(ratio)
|
||||
return if (step.isFinite() && step > EPS) step else PI / 8.0
|
||||
}
|
||||
|
||||
private fun appendPoint(output: MutableList<Point>, point: Point) {
|
||||
val last = output.lastOrNull()
|
||||
if (last == null || hypot(point.x - last.x, point.y - last.y) > EPS) {
|
||||
output.add(point)
|
||||
}
|
||||
}
|
||||
|
||||
private fun signedArea(points: List<Point>): Double {
|
||||
var sum = 0.0
|
||||
for (i in points.indices) {
|
||||
val p1 = points[i]
|
||||
val p2 = points[(i + 1) % points.size]
|
||||
sum += p1.x * p2.y - p2.x * p1.y
|
||||
}
|
||||
return sum / 2.0
|
||||
}
|
||||
|
||||
private fun perimeter(points: List<Point>): Double {
|
||||
var length = 0.0
|
||||
for (i in points.indices) {
|
||||
val p1 = points[i]
|
||||
val p2 = points[(i + 1) % points.size]
|
||||
length += hypot(p2.x - p1.x, p2.y - p1.y)
|
||||
}
|
||||
return length
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
import org.opencv.core.Point
|
||||
|
||||
internal object QuadGeometry {
|
||||
fun orderMinAreaRectPoints(points: Array<Point>): List<Point> {
|
||||
val sorted = points.sortedBy { it.x }
|
||||
val topLeft: Point
|
||||
val bottomLeft: Point
|
||||
if (sorted[1].y > sorted[0].y) {
|
||||
topLeft = sorted[0]
|
||||
bottomLeft = sorted[1]
|
||||
} else {
|
||||
topLeft = sorted[1]
|
||||
bottomLeft = sorted[0]
|
||||
}
|
||||
|
||||
val topRight: Point
|
||||
val bottomRight: Point
|
||||
if (sorted[3].y > sorted[2].y) {
|
||||
topRight = sorted[2]
|
||||
bottomRight = sorted[3]
|
||||
} else {
|
||||
topRight = sorted[3]
|
||||
bottomRight = sorted[2]
|
||||
}
|
||||
return listOf(topLeft, topRight, bottomRight, bottomLeft)
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.postprocess
|
||||
|
||||
import com.paddle.ocr.model.OCRBox
|
||||
import org.opencv.core.Core
|
||||
import org.opencv.core.CvType
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.MatOfPoint2f
|
||||
import org.opencv.core.Point
|
||||
import org.opencv.core.Size
|
||||
import org.opencv.imgproc.Imgproc
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.max
|
||||
|
||||
object QuadTextCrop {
|
||||
private const val VERTICAL_CROP_RATIO = 1.5
|
||||
|
||||
fun crop(src: Mat, box: OCRBox): Mat {
|
||||
// Align with PaddleX CropByPolys.get_minarea_rect_crop: recompute minAreaRect
|
||||
// from the detected quad before perspective transform.
|
||||
val rectPoints = box.points.map { Point(it.x.toDouble(), it.y.toDouble()) }
|
||||
val rectInput = MatOfPoint2f()
|
||||
rectInput.fromList(rectPoints)
|
||||
val boundingBox = Imgproc.minAreaRect(rectInput)
|
||||
rectInput.release()
|
||||
|
||||
val boxPoints = Array(4) { Point() }
|
||||
boundingBox.points(boxPoints)
|
||||
val ordered = QuadGeometry.orderMinAreaRectPoints(boxPoints)
|
||||
|
||||
val widthTop = hypot(ordered[0].x - ordered[1].x, ordered[0].y - ordered[1].y)
|
||||
val widthBottom = hypot(ordered[2].x - ordered[3].x, ordered[2].y - ordered[3].y)
|
||||
val heightLeft = hypot(ordered[0].x - ordered[3].x, ordered[0].y - ordered[3].y)
|
||||
val heightRight = hypot(ordered[1].x - ordered[2].x, ordered[1].y - ordered[2].y)
|
||||
|
||||
val dstW = max(widthTop, widthBottom).toInt().coerceAtLeast(1)
|
||||
val dstH = max(heightLeft, heightRight).toInt().coerceAtLeast(1)
|
||||
|
||||
val srcPts = MatOfPoint2f()
|
||||
srcPts.fromList(ordered)
|
||||
val dstPts = MatOfPoint2f()
|
||||
dstPts.fromList(
|
||||
listOf(
|
||||
Point(0.0, 0.0),
|
||||
Point(dstW.toDouble(), 0.0),
|
||||
Point(dstW.toDouble(), dstH.toDouble()),
|
||||
Point(0.0, dstH.toDouble()),
|
||||
)
|
||||
)
|
||||
val m = Imgproc.getPerspectiveTransform(srcPts, dstPts)
|
||||
srcPts.release()
|
||||
dstPts.release()
|
||||
|
||||
val dst = Mat(dstH, dstW, CvType.CV_8UC3)
|
||||
Imgproc.warpPerspective(
|
||||
src,
|
||||
dst,
|
||||
m,
|
||||
Size(dstW.toDouble(), dstH.toDouble()),
|
||||
Imgproc.INTER_CUBIC,
|
||||
Core.BORDER_REPLICATE,
|
||||
)
|
||||
m.release()
|
||||
|
||||
if (dst.rows().toDouble() / dst.cols() >= VERTICAL_CROP_RATIO) {
|
||||
val rotated = Mat()
|
||||
Core.rotate(dst, rotated, Core.ROTATE_90_COUNTERCLOCKWISE)
|
||||
dst.release()
|
||||
return rotated
|
||||
}
|
||||
return dst
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.preprocess
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.paddle.ocr.util.BitmapUtils
|
||||
import com.paddle.ocr.util.ImageUtils
|
||||
import org.opencv.core.Core
|
||||
import org.opencv.core.CvType
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.Scalar
|
||||
import org.opencv.imgproc.Imgproc
|
||||
|
||||
data class DetPreprocessResult(
|
||||
val tensorData: FloatArray,
|
||||
val shape: LongArray,
|
||||
val originalH: Int,
|
||||
val originalW: Int,
|
||||
)
|
||||
|
||||
object DetPreprocessor {
|
||||
private val mean = doubleArrayOf(0.485, 0.456, 0.406)
|
||||
private val std = doubleArrayOf(0.229, 0.224, 0.225)
|
||||
private const val scale = 1.0 / 255.0
|
||||
|
||||
fun preprocess(
|
||||
bitmap: Bitmap,
|
||||
limitSideLen: Int,
|
||||
limitType: String,
|
||||
maxSideLimit: Int,
|
||||
imgMode: String,
|
||||
): DetPreprocessResult {
|
||||
val src = BitmapUtils.bitmapToBGRMat(bitmap)
|
||||
return try {
|
||||
preprocess(src, limitSideLen, limitType, maxSideLimit, imgMode)
|
||||
} finally {
|
||||
src.release()
|
||||
}
|
||||
}
|
||||
|
||||
fun preprocess(
|
||||
src: Mat,
|
||||
limitSideLen: Int,
|
||||
limitType: String,
|
||||
maxSideLimit: Int,
|
||||
imgMode: String,
|
||||
): DetPreprocessResult {
|
||||
val originalH = src.rows()
|
||||
val originalW = src.cols()
|
||||
val input = if (imgMode.uppercase() == "RGB") {
|
||||
Mat().also { Imgproc.cvtColor(src, it, Imgproc.COLOR_BGR2RGB) }
|
||||
} else {
|
||||
src
|
||||
}
|
||||
|
||||
val resized = ImageUtils.resizeToMultipleOf32(input, limitSideLen, limitType, maxSideLimit)
|
||||
if (input !== src) input.release()
|
||||
|
||||
val h = resized.rows()
|
||||
val w = resized.cols()
|
||||
val floatMat = Mat(h, w, CvType.CV_32FC3)
|
||||
resized.convertTo(floatMat, CvType.CV_32F)
|
||||
|
||||
val channels = mutableListOf<Mat>()
|
||||
Core.split(floatMat, channels)
|
||||
for (c in 0..2) {
|
||||
Core.multiply(channels[c], Scalar(scale), channels[c])
|
||||
Core.subtract(channels[c], Scalar(mean[c]), channels[c])
|
||||
Core.divide(channels[c], Scalar(std[c]), channels[c])
|
||||
}
|
||||
resized.release()
|
||||
floatMat.release()
|
||||
|
||||
val channelSize = h * w
|
||||
val tensorData = FloatArray(3 * channelSize)
|
||||
for (c in 0..2) {
|
||||
val chan = channels[c]
|
||||
val buf = FloatArray(channelSize)
|
||||
chan.get(0, 0, buf)
|
||||
System.arraycopy(buf, 0, tensorData, c * channelSize, channelSize)
|
||||
chan.release()
|
||||
}
|
||||
|
||||
return DetPreprocessResult(
|
||||
tensorData = tensorData,
|
||||
shape = longArrayOf(1, 3, h.toLong(), w.toLong()),
|
||||
originalH = originalH,
|
||||
originalW = originalW,
|
||||
)
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.preprocess
|
||||
|
||||
import org.opencv.core.Core
|
||||
import org.opencv.core.CvType
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.Size
|
||||
import org.opencv.imgproc.Imgproc
|
||||
import kotlin.math.ceil
|
||||
|
||||
data class RecPreprocessResult(
|
||||
val tensorData: FloatArray,
|
||||
val shape: LongArray,
|
||||
)
|
||||
|
||||
object RecPreprocessor {
|
||||
private const val FIXED_HEIGHT = 48
|
||||
private const val MAX_IMG_W = 3200
|
||||
|
||||
fun preprocessBatch(crops: List<Mat>): RecPreprocessResult {
|
||||
// Convert BGR to RGB and resize to fixed height while preserving aspect ratio
|
||||
val resizedMats = mutableListOf<Mat>()
|
||||
for (crop in crops) {
|
||||
// Convert BGR to RGB (model expects RGB input)
|
||||
val rgb = Mat()
|
||||
Imgproc.cvtColor(crop, rgb, Imgproc.COLOR_BGR2RGB)
|
||||
val h = rgb.rows()
|
||||
val w = rgb.cols()
|
||||
val aspectRatio = if (h > 0) w.toDouble() / h else 1.0
|
||||
val newW = ceil(FIXED_HEIGHT * aspectRatio).toInt().coerceAtMost(MAX_IMG_W)
|
||||
val dst = Mat()
|
||||
Imgproc.resize(rgb, dst, Size(newW.toDouble(), FIXED_HEIGHT.toDouble()), 0.0, 0.0, Imgproc.INTER_LINEAR)
|
||||
rgb.release()
|
||||
resizedMats.add(dst)
|
||||
}
|
||||
|
||||
// Convert to float and normalize: (x / 255 - 0.5) / 0.5 = x / 127.5 - 1
|
||||
val floatMats = mutableListOf<Mat>()
|
||||
for (mat in resizedMats) {
|
||||
val floatMat = Mat(mat.rows(), mat.cols(), CvType.CV_32FC3)
|
||||
mat.convertTo(floatMat, CvType.CV_32F)
|
||||
// Use Scalar with all 3 channels set — single-value Scalar only sets val[0]!
|
||||
Core.divide(floatMat, org.opencv.core.Scalar(127.5, 127.5, 127.5), floatMat)
|
||||
Core.subtract(floatMat, org.opencv.core.Scalar(1.0, 1.0, 1.0), floatMat)
|
||||
|
||||
floatMats.add(floatMat)
|
||||
mat.release() // Release resized mat
|
||||
}
|
||||
resizedMats.clear()
|
||||
|
||||
val maxW = floatMats.maxOf { it.cols() }
|
||||
val n = floatMats.size
|
||||
|
||||
// Pad to max width
|
||||
val paddedMats = mutableListOf<Mat>()
|
||||
for (mat in floatMats) {
|
||||
if (mat.cols() == maxW) {
|
||||
paddedMats.add(mat)
|
||||
} else {
|
||||
val padded = Mat(FIXED_HEIGHT, maxW, CvType.CV_32FC3, org.opencv.core.Scalar(0.0))
|
||||
val roi = padded.submat(0, FIXED_HEIGHT, 0, mat.cols())
|
||||
mat.copyTo(roi)
|
||||
roi.release()
|
||||
mat.release()
|
||||
paddedMats.add(padded)
|
||||
}
|
||||
}
|
||||
floatMats.clear()
|
||||
|
||||
// Build tensor data
|
||||
val channelSize = FIXED_HEIGHT * maxW
|
||||
val tensorData = FloatArray(n * 3 * channelSize)
|
||||
for (b in 0 until n) {
|
||||
val mat = paddedMats[b]
|
||||
val channels = mutableListOf<Mat>()
|
||||
Core.split(mat, channels)
|
||||
for (c in 0..2) {
|
||||
val buf = FloatArray(channelSize)
|
||||
channels[c].get(0, 0, buf)
|
||||
System.arraycopy(buf, 0, tensorData, (b * 3 + c) * channelSize, channelSize)
|
||||
channels[c].release()
|
||||
}
|
||||
mat.release()
|
||||
}
|
||||
paddedMats.clear()
|
||||
|
||||
return RecPreprocessResult(
|
||||
tensorData = tensorData,
|
||||
shape = longArrayOf(n.toLong(), 3, FIXED_HEIGHT.toLong(), maxW.toLong()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import org.opencv.android.Utils
|
||||
import org.opencv.core.CvType
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.MatOfByte
|
||||
import org.opencv.imgcodecs.Imgcodecs
|
||||
import org.opencv.imgproc.Imgproc
|
||||
|
||||
object BitmapUtils {
|
||||
|
||||
fun imdecodeBGR(imageBytes: ByteArray): Mat {
|
||||
val encoded = MatOfByte(*imageBytes)
|
||||
return try {
|
||||
Imgcodecs.imdecode(encoded, Imgcodecs.IMREAD_COLOR)
|
||||
} finally {
|
||||
encoded.release()
|
||||
}
|
||||
}
|
||||
|
||||
fun bitmapToBGRMat(bitmap: Bitmap): Mat {
|
||||
return bitmapToMat(bitmap, Imgproc.COLOR_RGBA2BGR)
|
||||
}
|
||||
|
||||
fun bitmapToRGBMat(bitmap: Bitmap): Mat {
|
||||
return bitmapToMat(bitmap, Imgproc.COLOR_RGBA2RGB)
|
||||
}
|
||||
|
||||
fun bgrMatToBitmap(mat: Mat): Bitmap {
|
||||
val rgba = Mat()
|
||||
return try {
|
||||
Imgproc.cvtColor(mat, rgba, Imgproc.COLOR_BGR2RGBA)
|
||||
Bitmap.createBitmap(rgba.cols(), rgba.rows(), Bitmap.Config.ARGB_8888).also { bitmap ->
|
||||
Utils.matToBitmap(rgba, bitmap)
|
||||
}
|
||||
} finally {
|
||||
rgba.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun bitmapToMat(bitmap: Bitmap, colorConversionCode: Int): Mat {
|
||||
val bmp = bitmap.copy(Bitmap.Config.ARGB_8888, false)
|
||||
val rgba = Mat(bmp.height, bmp.width, CvType.CV_8UC4)
|
||||
val dst = Mat()
|
||||
return try {
|
||||
Utils.bitmapToMat(bmp, rgba)
|
||||
Imgproc.cvtColor(rgba, dst, colorConversionCode)
|
||||
dst
|
||||
} catch (t: Throwable) {
|
||||
dst.release()
|
||||
throw t
|
||||
} finally {
|
||||
bmp.recycle()
|
||||
rgba.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.util
|
||||
|
||||
import org.opencv.core.Mat
|
||||
import org.opencv.core.Size
|
||||
import org.opencv.imgproc.Imgproc
|
||||
|
||||
object ImageUtils {
|
||||
|
||||
fun resizeToMultipleOf32(
|
||||
src: Mat,
|
||||
limitSideLen: Int,
|
||||
limitType: String,
|
||||
maxSideLimit: Int,
|
||||
): Mat {
|
||||
val h = src.rows()
|
||||
val w = src.cols()
|
||||
var ratio = when (limitType.lowercase()) {
|
||||
"max" -> if (maxOf(h, w) > limitSideLen) limitSideLen.toDouble() / maxOf(h, w) else 1.0
|
||||
"min" -> if (minOf(h, w) < limitSideLen) limitSideLen.toDouble() / minOf(h, w) else 1.0
|
||||
"resize_long" -> limitSideLen.toDouble() / maxOf(h, w)
|
||||
else -> throw IllegalArgumentException("Unsupported det limit type: $limitType")
|
||||
}
|
||||
|
||||
var newH = (h * ratio).toInt()
|
||||
var newW = (w * ratio).toInt()
|
||||
if (maxOf(newH, newW) > maxSideLimit) {
|
||||
ratio = maxSideLimit.toDouble() / maxOf(newH, newW)
|
||||
newH = (newH * ratio).toInt()
|
||||
newW = (newW * ratio).toInt()
|
||||
}
|
||||
|
||||
newH = maxOf(MathUtils.roundHalfToEven(newH / 32.0) * 32, 32)
|
||||
newW = maxOf(MathUtils.roundHalfToEven(newW / 32.0) * 32, 32)
|
||||
val dst = Mat()
|
||||
Imgproc.resize(src, dst, Size(newW.toDouble(), newH.toDouble()), 0.0, 0.0, Imgproc.INTER_LINEAR)
|
||||
return dst
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.util
|
||||
|
||||
import kotlin.math.floor
|
||||
|
||||
object MathUtils {
|
||||
|
||||
fun roundHalfToEven(value: Double): Int {
|
||||
val floored = floor(value)
|
||||
val diff = value - floored
|
||||
return when {
|
||||
diff < 0.5 -> floored.toInt()
|
||||
diff > 0.5 -> floored.toInt() + 1
|
||||
floored.toInt() % 2 == 0 -> floored.toInt()
|
||||
else -> floored.toInt() + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.util
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
|
||||
object OpenCVUtils {
|
||||
|
||||
private var initialized = false
|
||||
|
||||
fun init(context: Context): Boolean {
|
||||
if (initialized) return true
|
||||
try {
|
||||
System.loadLibrary("opencv_java4")
|
||||
initialized = true
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.e("OpenCVUtils", "Failed to initialize OpenCV: ${e.message}")
|
||||
}
|
||||
return initialized
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package com.paddle.ocr.util
|
||||
|
||||
object YamlUtils {
|
||||
|
||||
fun leadingSpaces(line: String): Int {
|
||||
return line.indexOfFirst { it != ' ' }.let { if (it < 0) line.length else it }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# PP-OCRv6 Android Speed Benchmark
|
||||
# Usage: JAVA_HOME=/opt/android-jdk ./run_benchmark.sh [iterations] [warmup]
|
||||
# e.g. JAVA_HOME=/opt/android-jdk ./run_benchmark.sh 20 5
|
||||
# defaults: 10 iterations, 3 warmup
|
||||
|
||||
set -e
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
ITERATIONS="${1:-50}"
|
||||
WARMUP="${2:-30}"
|
||||
|
||||
echo "========================================"
|
||||
echo " PP-OCRv6 Android Speed Benchmark"
|
||||
echo "========================================"
|
||||
echo " Warmup: ${WARMUP}"
|
||||
echo " Iterations: ${ITERATIONS}"
|
||||
echo "========================================"
|
||||
echo ""
|
||||
|
||||
adb logcat -c 2>/dev/null || true
|
||||
|
||||
echo "[1/2] Running speed benchmark (warmup + ${ITERATIONS} measured iterations)..."
|
||||
echo "----------------------------------------"
|
||||
./gradlew :ppocr-sdk:connectedAndroidTest \
|
||||
-Pandroid.testInstrumentationRunnerArguments.class=com.paddle.ocr.benchmark.OCRBenchmarkTest#testLatencyBenchmark \
|
||||
-Pandroid.testInstrumentationRunnerArguments.warmup="${WARMUP}" \
|
||||
-Pandroid.testInstrumentationRunnerArguments.iterations="${ITERATIONS}" \
|
||||
2>&1
|
||||
echo "----------------------------------------"
|
||||
echo ""
|
||||
|
||||
echo "[2/2] Speed benchmark results:"
|
||||
echo "========================================"
|
||||
adb logcat -d -s System.out:I 2>/dev/null | grep "OCRBenchmark" | sed 's/^.*System.out/I/'
|
||||
echo "========================================"
|
||||
echo ""
|
||||
echo " Done"
|
||||
@@ -0,0 +1,29 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven { url = uri("https://maven.aliyun.com/repository/google") }
|
||||
maven { url = uri("https://maven.aliyun.com/repository/central") }
|
||||
maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") }
|
||||
google {
|
||||
content {
|
||||
includeGroupByRegex("com\\.android.*")
|
||||
includeGroupByRegex("com\\.google.*")
|
||||
includeGroupByRegex("androidx.*")
|
||||
}
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
maven { url = uri("https://maven.aliyun.com/repository/google") }
|
||||
maven { url = uri("https://maven.aliyun.com/repository/central") }
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "ppocr-android"
|
||||
include(":app")
|
||||
include(":ppocr-sdk")
|
||||
@@ -0,0 +1,251 @@
|
||||
# PP-OCRv6 Android Demo
|
||||
|
||||
## Introduction
|
||||
|
||||
This project is an Android deployment example for PaddleOCR v6, implementing mobile OCR inference using ONNX Runtime. The project adopts a **SDK and Demo separation** architecture, where the SDK module can be independently integrated into third-party applications.
|
||||
|
||||
## Features
|
||||
|
||||
- End-to-end text detection and recognition pipeline
|
||||
- Supports PP-OCRv6 series ONNX models
|
||||
- Detailed performance timing (detection/recognition stage breakdown)
|
||||
- MVVM + Jetpack Compose Demo application
|
||||
- AAR integration support
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
ppocr-android/
|
||||
├── ppocr-sdk/ # OCR SDK (Android Library)
|
||||
│ ├── src/main/
|
||||
│ │ ├── assets/models/ # Model files directory
|
||||
│ │ │ ├── det/ # Detection model: inference.onnx
|
||||
│ │ │ └── rec/ # Recognition model: inference.onnx, inference.yml
|
||||
│ │ └── java/com/paddle/ocr/
|
||||
│ │ ├── PaddleOCR.kt # [Public API] SDK entry point
|
||||
│ │ ├── PaddleOCRConfig.kt # [Public API] Inference configuration
|
||||
│ │ └── ...
|
||||
│ └── build.gradle.kts
|
||||
├── app/ # Demo App
|
||||
│ ├── src/main/java/com/paddle/ocr/demo/
|
||||
│ │ ├── OCRApplication.kt # Initialize SDK
|
||||
│ │ └── ui/ # Compose UI
|
||||
│ └── build.gradle.kts
|
||||
├── run_benchmark.sh # Performance test script
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
| Dependency | Version |
|
||||
|------------|---------|
|
||||
| Android Studio | Ladybug (2024.2+) |
|
||||
| JDK | 17 |
|
||||
| Kotlin | 2.1.0 |
|
||||
| minSdk | 26 (Android 8.0) |
|
||||
| ONNX Runtime | 1.21.1 |
|
||||
| OpenCV | 4.5.3 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Clone the Project
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PaddlePaddle/PaddleOCR.git
|
||||
cd PaddleOCR/deploy/ppocr-android
|
||||
```
|
||||
|
||||
### 2. Prepare Models
|
||||
|
||||
This project supports the following models:
|
||||
|
||||
| Model | HuggingFace | BOS |
|
||||
|------|-------------|-----|
|
||||
| **PP-OCRv6_small** | [Detection model](https://huggingface.co/PaddlePaddle/PP-OCRv6_small_det_onnx) / [Recognition model](https://huggingface.co/PaddlePaddle/PP-OCRv6_small_rec_onnx) | [Detection model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_onnx_infer.tar) / [Recognition model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_onnx_infer.tar) |
|
||||
| **PP-OCRv6_tiny** | [Detection model](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx) / [Recognition model](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx) | [Detection model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_onnx_infer.tar) / [Recognition model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_onnx_infer.tar) |
|
||||
| **PP-OCRv5_mobile** | [Detection model](https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx) / [Recognition model](https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_rec_onnx) | [Detection model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_mobile_det_onnx_infer.tar) / [Recognition model](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_mobile_rec_onnx_infer.tar) |
|
||||
|
||||
After downloading and extracting, place the files in `ppocr-sdk/src/main/assets/models/`:
|
||||
|
||||
- Detection model: place `inference.onnx` in `models/det/`
|
||||
- Recognition model: place `inference.onnx` and `inference.yml` in `models/rec/`
|
||||
|
||||
### 3. Build and Run
|
||||
|
||||
```bash
|
||||
# Build Debug APK
|
||||
./gradlew :app:assembleDebug
|
||||
|
||||
# Install to device
|
||||
./gradlew :app:installDebug
|
||||
```
|
||||
|
||||
Or run directly from Android Studio.
|
||||
|
||||
### 4. Try the Demo
|
||||
|
||||
1. Open "PP-OCRv6 Demo" application
|
||||
2. Wait for model loading to complete
|
||||
3. Tap "Select from Gallery" to choose an image
|
||||
4. View recognition results and timing statistics
|
||||
|
||||
## SDK Integration
|
||||
|
||||
### Option 1: Source Code Dependency
|
||||
|
||||
1. Copy `ppocr-sdk/` to your project root
|
||||
2. Add to `settings.gradle.kts`:
|
||||
```kotlin
|
||||
include(":ppocr-sdk")
|
||||
```
|
||||
3. Add to your app module's `build.gradle.kts`:
|
||||
```kotlin
|
||||
implementation(project(":ppocr-sdk"))
|
||||
```
|
||||
|
||||
### Option 2: AAR Dependency
|
||||
|
||||
```bash
|
||||
# Build AAR
|
||||
./gradlew :ppocr-sdk:assembleRelease
|
||||
```
|
||||
|
||||
AAR output: `ppocr-sdk/build/outputs/aar/ppocr-sdk-release.aar`
|
||||
|
||||
Add to your app module's `build.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
dependencies {
|
||||
implementation(files("libs/ppocr-sdk-release.aar"))
|
||||
// AAR doesn't transit dependencies, add manually
|
||||
implementation("com.microsoft.onnxruntime:onnxruntime-android:1.21.1")
|
||||
implementation("com.quickbirdstudios:opencv:4.5.3")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Create Instance
|
||||
|
||||
```kotlin
|
||||
// Default configuration
|
||||
val ocr = PaddleOCR.create(context)
|
||||
|
||||
// Custom configuration
|
||||
val ocr = PaddleOCR.create(
|
||||
context = context,
|
||||
config = PaddleOCRConfig(
|
||||
detThresh = 0.3f,
|
||||
detBoxThresh = 0.6f,
|
||||
recScoreThresh = 0.0f,
|
||||
recBatchSize = 1,
|
||||
),
|
||||
engineConfig = EngineConfig(numThreads = 4),
|
||||
detModelAssetPath = "models/det/inference.onnx",
|
||||
recModelAssetPath = "models/rec/inference.onnx",
|
||||
recConfigAssetPath = "models/rec/inference.yml",
|
||||
)
|
||||
```
|
||||
|
||||
### Perform OCR
|
||||
|
||||
```kotlin
|
||||
// Pass Bitmap
|
||||
val result = ocr.recognize(bitmap)
|
||||
|
||||
// Pass image bytes (recommended, consistent with Python pipeline)
|
||||
val result = ocr.recognize(imageBytes)
|
||||
|
||||
// Read results
|
||||
result.results.forEach { item ->
|
||||
println("Text: ${item.text}, Confidence: ${item.confidence}")
|
||||
println("Box: ${item.box.points}")
|
||||
}
|
||||
println("Detection: ${result.detectionTimeMs}ms, Recognition: ${result.recognitionTimeMs}ms")
|
||||
```
|
||||
|
||||
### Release Resources
|
||||
|
||||
```kotlin
|
||||
ocr.release()
|
||||
```
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
```kotlin
|
||||
data class PaddleOCRConfig(
|
||||
val detImgMode: String = "BGR", // Input color mode
|
||||
val detLimitSideLen: Int = 64, // Detection side length limit
|
||||
val detLimitType: String = "min", // Limit strategy
|
||||
val detMaxSideLimit: Int = 4000, // Maximum side length
|
||||
val detThresh: Float = 0.3f, // Binarization threshold
|
||||
val detBoxThresh: Float = 0.6f, // Detection box confidence threshold
|
||||
val detUnclipRatio: Float = 1.5f, // Detection box expansion ratio
|
||||
val detMaxCandidates: Int = 3000, // Maximum candidate boxes
|
||||
val detUseDilation: Boolean = false, // Whether to dilate
|
||||
val detScoreMode: String = "fast", // Scoring mode
|
||||
val detBoxType: String = "quad", // Detection box type
|
||||
val recScoreThresh: Float = 0.0f, // Recognition confidence threshold
|
||||
val recBatchSize: Int = 1, // Recognition batch size
|
||||
)
|
||||
```
|
||||
|
||||
### Result Models
|
||||
|
||||
```kotlin
|
||||
data class OCRRunResult(
|
||||
val results: List<OCRResult>, // Recognition result list
|
||||
val detectionTimeMs: Long, // Detection time
|
||||
val recognitionTimeMs: Long, // Recognition time
|
||||
val totalTimeMs: Long, // Total time
|
||||
val lineCount: Int, // Number of lines
|
||||
// Detailed timing...
|
||||
)
|
||||
|
||||
data class OCRResult(
|
||||
val box: OCRBox, // Detection box coordinates
|
||||
val text: String, // Recognized text
|
||||
val confidence: Float, // Confidence score
|
||||
)
|
||||
```
|
||||
|
||||
## Performance Testing
|
||||
|
||||
The project provides an automated performance testing script:
|
||||
|
||||
```bash
|
||||
# Run benchmark (10 tests, 3 warmup)
|
||||
./run_benchmark.sh 10 3
|
||||
|
||||
# Sample output
|
||||
╔═════════════════════════════════════════════════════════════════════════╗
|
||||
║ PP-OCRv6 Speed Benchmark Results ║
|
||||
╠═════════════════════════════════════════════════════════════════════════╣
|
||||
║ Device: GM1900 | OS: Android 9 | Lines: 5 ║
|
||||
║ Cold load: 158ms | Warmup: 3 | Measured: 10 ║
|
||||
╠═════════════════════════════════════════════════════════════════════════╣
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Stage | Mean ms | Stdev | P90 | Min ms|
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Total pipeline | 420.40 | 6.37 | 427 | 413 |
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Detection (total) | 348.70 | 4.67 | 356 | 343 |
|
||||
| Preprocess | 33.30 | 2.90 | 36 | 28 |
|
||||
| Inference | 311.00 | 2.93 | 315 | 304 |
|
||||
| Postprocess | 4.40 | 0.49 | 5 | 4 |
|
||||
| Recognition (total) | 66.20 | 3.16 | 68 | 64 |
|
||||
| Preprocess | 3.00 | 0.89 | 4 | 2 |
|
||||
| Inference | 60.60 | 3.14 | 63 | 58 |
|
||||
| Postprocess | 2.60 | 0.92 | 4 | 1 |
|
||||
| Pipeline overhead | 5.50 | 0.50 | 6 | 5 |
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
╚═════════════════════════════════════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
1. **OpenCV Initialization**: Call `OpenCVUtils.init(context)` before `PaddleOCR.create()`
|
||||
2. **Coroutine Usage**: `create()` and `recognize()` are suspend functions, call them in coroutines
|
||||
3. **Memory Management**: Call `release()` when no longer needed
|
||||
4. **ProGuard Rules**: Refer to `ppocr-sdk/proguard-rules.pro`
|
||||
@@ -0,0 +1,251 @@
|
||||
# PP-OCRv6 Android Demo
|
||||
|
||||
## 简介
|
||||
|
||||
本项目是 PaddleOCR v6 在 Android 平台的部署示例,基于 ONNX Runtime 实现移动端 OCR 推理。项目采用 **SDK 与 Demo 分离** 架构,SDK 模块可独立集成到第三方应用。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 文本检测 + 文本识别端到端流程
|
||||
- 支持 PP-OCRv6 系列 ONNX 模型
|
||||
- 详细的性能计时(检测/识别各阶段耗时)
|
||||
- MVVM + Jetpack Compose Demo 应用
|
||||
- 支持 AAR 方式集成
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
ppocr-android/
|
||||
├── ppocr-sdk/ # OCR SDK(Android Library)
|
||||
│ ├── src/main/
|
||||
│ │ ├── assets/models/ # 模型文件目录
|
||||
│ │ │ ├── det/ # 检测模型:inference.onnx
|
||||
│ │ │ └── rec/ # 识别模型:inference.onnx, inference.yml
|
||||
│ │ └── java/com/paddle/ocr/
|
||||
│ │ ├── PaddleOCR.kt # [公开 API] SDK 入口
|
||||
│ │ ├── PaddleOCRConfig.kt # [公开 API] 推理参数配置
|
||||
│ │ └── ...
|
||||
│ └── build.gradle.kts
|
||||
├── app/ # Demo App
|
||||
│ ├── src/main/java/com/paddle/ocr/demo/
|
||||
│ │ ├── OCRApplication.kt # 初始化 SDK
|
||||
│ │ └── ui/ # Compose UI
|
||||
│ └── build.gradle.kts
|
||||
├── run_benchmark.sh # 性能测试脚本
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 环境要求
|
||||
|
||||
| 依赖 | 版本 |
|
||||
|------|------|
|
||||
| Android Studio | Ladybug (2024.2+) |
|
||||
| JDK | 17 |
|
||||
| Kotlin | 2.1.0 |
|
||||
| minSdk | 26 (Android 8.0) |
|
||||
| ONNX Runtime | 1.21.1 |
|
||||
| OpenCV | 4.5.3 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 克隆项目
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PaddlePaddle/PaddleOCR.git
|
||||
cd PaddleOCR/deploy/ppocr-android
|
||||
```
|
||||
|
||||
### 2. 准备模型
|
||||
|
||||
本项目支持以下模型:
|
||||
|
||||
| 模型 | HuggingFace | BOS |
|
||||
|------|-------------|-----|
|
||||
| **PP-OCRv6_small** | [检测模型](https://huggingface.co/PaddlePaddle/PP-OCRv6_small_det_onnx) / [识别模型](https://huggingface.co/PaddlePaddle/PP-OCRv6_small_rec_onnx) | [检测模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_onnx_infer.tar) / [识别模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_onnx_infer.tar) |
|
||||
| **PP-OCRv6_tiny** | [检测模型](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx) / [识别模型](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx) | [检测模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_onnx_infer.tar) / [识别模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_onnx_infer.tar) |
|
||||
| **PP-OCRv5_mobile** | [检测模型](https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx) / [识别模型](https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_rec_onnx) | [检测模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_mobile_det_onnx_infer.tar) / [识别模型](https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_mobile_rec_onnx_infer.tar) |
|
||||
|
||||
下载并解压后,将文件放入 `ppocr-sdk/src/main/assets/models/` 目录:
|
||||
|
||||
- 检测模型:将 `inference.onnx` 放入 `models/det/`
|
||||
- 识别模型:将 `inference.onnx` 和 `inference.yml` 放入 `models/rec/`
|
||||
|
||||
### 3. 编译运行
|
||||
|
||||
```bash
|
||||
# 编译 Debug APK
|
||||
./gradlew :app:assembleDebug
|
||||
|
||||
# 安装到设备
|
||||
./gradlew :app:installDebug
|
||||
```
|
||||
|
||||
或使用 Android Studio 直接运行。
|
||||
|
||||
### 4. 体验 Demo
|
||||
|
||||
1. 打开 "PP-OCRv6 Demo" 应用
|
||||
2. 等待模型加载完成
|
||||
3. 点击 "Select from Gallery" 选择图片
|
||||
4. 查看识别结果和耗时统计
|
||||
|
||||
## SDK 集成
|
||||
|
||||
### 方式一:源码依赖
|
||||
|
||||
1. 将 `ppocr-sdk/` 复制到项目根目录
|
||||
2. 在 `settings.gradle.kts` 添加:
|
||||
```kotlin
|
||||
include(":ppocr-sdk")
|
||||
```
|
||||
3. 在 App 模块 `build.gradle.kts` 添加:
|
||||
```kotlin
|
||||
implementation(project(":ppocr-sdk"))
|
||||
```
|
||||
|
||||
### 方式二:AAR 依赖
|
||||
|
||||
```bash
|
||||
# 构建 AAR
|
||||
./gradlew :ppocr-sdk:assembleRelease
|
||||
```
|
||||
|
||||
AAR 输出:`ppocr-sdk/build/outputs/aar/ppocr-sdk-release.aar`
|
||||
|
||||
在 App 模块 `build.gradle.kts` 添加:
|
||||
|
||||
```kotlin
|
||||
dependencies {
|
||||
implementation(files("libs/ppocr-sdk-release.aar"))
|
||||
// AAR 不传递依赖,需手动添加
|
||||
implementation("com.microsoft.onnxruntime:onnxruntime-android:1.21.1")
|
||||
implementation("com.quickbirdstudios:opencv:4.5.3")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
}
|
||||
```
|
||||
|
||||
## API 参考
|
||||
|
||||
### 创建实例
|
||||
|
||||
```kotlin
|
||||
// 默认配置
|
||||
val ocr = PaddleOCR.create(context)
|
||||
|
||||
// 自定义配置
|
||||
val ocr = PaddleOCR.create(
|
||||
context = context,
|
||||
config = PaddleOCRConfig(
|
||||
detThresh = 0.3f,
|
||||
detBoxThresh = 0.6f,
|
||||
recScoreThresh = 0.0f,
|
||||
recBatchSize = 1,
|
||||
),
|
||||
engineConfig = EngineConfig(numThreads = 4),
|
||||
detModelAssetPath = "models/det/inference.onnx",
|
||||
recModelAssetPath = "models/rec/inference.onnx",
|
||||
recConfigAssetPath = "models/rec/inference.yml",
|
||||
)
|
||||
```
|
||||
|
||||
### 执行 OCR
|
||||
|
||||
```kotlin
|
||||
// 传入 Bitmap
|
||||
val result = ocr.recognize(bitmap)
|
||||
|
||||
// 传入图片字节数据(推荐,与 Python 流程一致)
|
||||
val result = ocr.recognize(imageBytes)
|
||||
|
||||
// 读取结果
|
||||
result.results.forEach { item ->
|
||||
println("文本: ${item.text}, 置信度: ${item.confidence}")
|
||||
println("坐标: ${item.box.points}")
|
||||
}
|
||||
println("检测: ${result.detectionTimeMs}ms, 识别: ${result.recognitionTimeMs}ms")
|
||||
```
|
||||
|
||||
### 释放资源
|
||||
|
||||
```kotlin
|
||||
ocr.release()
|
||||
```
|
||||
|
||||
### 配置参数
|
||||
|
||||
```kotlin
|
||||
data class PaddleOCRConfig(
|
||||
val detImgMode: String = "BGR", // 输入色彩模式
|
||||
val detLimitSideLen: Int = 64, // 检测侧边长限制
|
||||
val detLimitType: String = "min", // 限制策略
|
||||
val detMaxSideLimit: Int = 4000, // 最长边上限
|
||||
val detThresh: Float = 0.3f, // 二值化阈值
|
||||
val detBoxThresh: Float = 0.6f, // 检测框置信度阈值
|
||||
val detUnclipRatio: Float = 1.5f, // 检测框扩展比例
|
||||
val detMaxCandidates: Int = 3000, // 最大候选框数
|
||||
val detUseDilation: Boolean = false, // 是否膨胀
|
||||
val detScoreMode: String = "fast", // 打分模式
|
||||
val detBoxType: String = "quad", // 检测框类型
|
||||
val recScoreThresh: Float = 0.0f, // 识别置信度阈值
|
||||
val recBatchSize: Int = 1, // 识别批大小
|
||||
)
|
||||
```
|
||||
|
||||
### 结果模型
|
||||
|
||||
```kotlin
|
||||
data class OCRRunResult(
|
||||
val results: List<OCRResult>, // 识别结果列表
|
||||
val detectionTimeMs: Long, // 检测耗时
|
||||
val recognitionTimeMs: Long, // 识别耗时
|
||||
val totalTimeMs: Long, // 总耗时
|
||||
val lineCount: Int, // 识别行数
|
||||
// 详细计时...
|
||||
)
|
||||
|
||||
data class OCRResult(
|
||||
val box: OCRBox, // 检测框坐标
|
||||
val text: String, // 识别文本
|
||||
val confidence: Float, // 置信度
|
||||
)
|
||||
```
|
||||
|
||||
## 性能测试
|
||||
|
||||
项目提供自动化性能测试脚本:
|
||||
|
||||
```bash
|
||||
# 运行 benchmark(10次测试,3次预热)
|
||||
./run_benchmark.sh 10 3
|
||||
|
||||
# 输出示例
|
||||
╔═════════════════════════════════════════════════════════════════════════╗
|
||||
║ PP-OCRv6 Speed Benchmark Results ║
|
||||
╠═════════════════════════════════════════════════════════════════════════╣
|
||||
║ Device: GM1900 | OS: Android 9 | Lines: 5 ║
|
||||
║ Cold load: 158ms | Warmup: 3 | Measured: 10 ║
|
||||
╠═════════════════════════════════════════════════════════════════════════╣
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Stage | Mean ms | Stdev | P90 | Min ms|
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Total pipeline | 420.40 | 6.37 | 427 | 413 |
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
| Detection (total) | 348.70 | 4.67 | 356 | 343 |
|
||||
| Preprocess | 33.30 | 2.90 | 36 | 28 |
|
||||
| Inference | 311.00 | 2.93 | 315 | 304 |
|
||||
| Postprocess | 4.40 | 0.49 | 5 | 4 |
|
||||
| Recognition (total) | 66.20 | 3.16 | 68 | 64 |
|
||||
| Preprocess | 3.00 | 0.89 | 4 | 2 |
|
||||
| Inference | 60.60 | 3.14 | 63 | 58 |
|
||||
| Postprocess | 2.60 | 0.92 | 4 | 1 |
|
||||
| Pipeline overhead | 5.50 | 0.50 | 6 | 5 |
|
||||
+-----------------------------+----------+----------+----------+----------+
|
||||
╚═════════════════════════════════════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **OpenCV 初始化**:调用 `PaddleOCR.create()` 前需先调用 `OpenCVUtils.init(context)`
|
||||
2. **协程调用**:`create()` 和 `recognize()` 都是 suspend 函数,需在协程中调用
|
||||
3. **内存管理**:不再使用时调用 `release()` 释放资源
|
||||
4. **混淆规则**:参考 `ppocr-sdk/proguard-rules.pro`
|
||||
@@ -139,6 +139,7 @@ plugins:
|
||||
打包 PaddleOCR 项目: Package PaddleOCR Projects
|
||||
获取ONNX模型: Obtaining ONNX Models
|
||||
端侧部署: On-Device Deployment
|
||||
Android 部署: Android Deployment
|
||||
服务化部署: Serving
|
||||
浏览器端部署: Browser Deployment
|
||||
模块列表: Module List
|
||||
@@ -362,6 +363,7 @@ nav:
|
||||
- CLI: version3.x/inference_deployment/serving/paddleocr_official_api/cli.md
|
||||
- 跨端部署:
|
||||
- 端侧部署: version3.x/inference_deployment/cross_platform/on_device_deployment.md
|
||||
- Android 部署: version3.x/inference_deployment/cross_platform/android_deployment.md
|
||||
- 浏览器端部署: version3.x/inference_deployment/cross_platform/browser.md
|
||||
- 其它:
|
||||
- 获取ONNX模型: version3.x/inference_deployment/others/obtaining_onnx_models.md
|
||||
|
||||
Reference in new issue
Block a user