-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathVerticalOCR.kt
173 lines (148 loc) · 5.81 KB
/
VerticalOCR.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package com.swmansion.rnexecutorch
import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.swmansion.rnexecutorch.utils.ETError
import com.swmansion.rnexecutorch.utils.ImageProcessor
import org.opencv.android.OpenCVLoader
import com.swmansion.rnexecutorch.models.ocr.Recognizer
import com.swmansion.rnexecutorch.models.ocr.VerticalDetector
import com.swmansion.rnexecutorch.models.ocr.utils.CTCLabelConverter
import com.swmansion.rnexecutorch.models.ocr.utils.Constants
import com.swmansion.rnexecutorch.models.ocr.utils.RecognizerUtils
import org.opencv.core.Core
import org.opencv.core.Mat
class VerticalOCR(reactContext: ReactApplicationContext) :
NativeVerticalOCRSpec(reactContext) {
private lateinit var detectorLarge: VerticalDetector
private lateinit var detectorNarrow: VerticalDetector
private lateinit var recognizer: Recognizer
private lateinit var converter: CTCLabelConverter
private var independentCharacters = true
companion object {
const val NAME = "VerticalOCR"
}
init {
if (!OpenCVLoader.initLocal()) {
Log.d("rn_executorch", "OpenCV not loaded")
} else {
Log.d("rn_executorch", "OpenCV loaded")
}
}
override fun loadModule(
detectorLargeSource: String,
detectorNarrowSource: String,
recognizerSource: String,
symbols: String,
independentCharacters: Boolean,
promise: Promise
) {
try {
this.independentCharacters = independentCharacters
detectorLarge = VerticalDetector(false, reactApplicationContext)
detectorLarge.loadModel(detectorLargeSource)
detectorNarrow = VerticalDetector(true, reactApplicationContext)
detectorNarrow.loadModel(detectorNarrowSource)
recognizer = Recognizer(reactApplicationContext)
recognizer.loadModel(recognizerSource)
converter = CTCLabelConverter(symbols)
promise.resolve(0)
} catch (e: Exception) {
promise.reject(e.message!!, ETError.InvalidModelSource.toString())
}
}
override fun forward(input: String, promise: Promise) {
try {
val inputImage = ImageProcessor.readImage(input)
val result = detectorLarge.runModel(inputImage)
val largeDetectorSize = detectorLarge.getModelImageSize()
val resizedImage = ImageProcessor.resizeWithPadding(
inputImage,
largeDetectorSize.width.toInt(),
largeDetectorSize.height.toInt()
)
val predictions = Arguments.createArray()
for (box in result) {
val cords = box.bBox
val boxWidth = cords[2].x - cords[0].x
val boxHeight = cords[2].y - cords[0].y
val boundingBox = RecognizerUtils.extractBoundingBox(cords)
val croppedImage = Mat(resizedImage, boundingBox)
val paddings = RecognizerUtils.calculateResizeRatioAndPaddings(
inputImage.width(),
inputImage.height(),
largeDetectorSize.width.toInt(),
largeDetectorSize.height.toInt()
)
var text = ""
var confidenceScore = 0.0
val boxResult = detectorNarrow.runModel(croppedImage)
val narrowDetectorSize = detectorNarrow.getModelImageSize()
val croppedCharacters = mutableListOf<Mat>()
for (characterBox in boxResult) {
val boxCords = characterBox.bBox
val paddingsBox = RecognizerUtils.calculateResizeRatioAndPaddings(
boxWidth.toInt(),
boxHeight.toInt(),
narrowDetectorSize.width.toInt(),
narrowDetectorSize.height.toInt()
)
var croppedCharacter = RecognizerUtils.cropImageWithBoundingBox(
inputImage,
boxCords,
cords,
paddingsBox,
paddings
)
if (this.independentCharacters) {
croppedCharacter = RecognizerUtils.cropSingleCharacter(croppedCharacter)
croppedCharacter = RecognizerUtils.normalizeForRecognizer(croppedCharacter, 0.0, true)
val recognitionResult = recognizer.runModel(croppedCharacter)
val predIndex = recognitionResult.first
val decodedText = converter.decodeGreedy(predIndex, predIndex.size)
text += decodedText[0]
confidenceScore += recognitionResult.second
} else {
croppedCharacters.add(croppedCharacter)
}
}
if (this.independentCharacters) {
confidenceScore /= boxResult.size
} else {
var mergedCharacters = Mat()
Core.hconcat(croppedCharacters, mergedCharacters)
mergedCharacters = ImageProcessor.resizeWithPadding(
mergedCharacters,
Constants.LARGE_MODEL_WIDTH,
Constants.MODEL_HEIGHT
)
mergedCharacters = RecognizerUtils.normalizeForRecognizer(mergedCharacters, 0.0)
val recognitionResult = recognizer.runModel(mergedCharacters)
val predIndex = recognitionResult.first
val decodedText = converter.decodeGreedy(predIndex, predIndex.size)
text = decodedText[0]
confidenceScore = recognitionResult.second
}
for (bBox in box.bBox) {
bBox.x =
(bBox.x - paddings["left"] as Int) * paddings["resizeRatio"] as Float
bBox.y =
(bBox.y - paddings["top"] as Int) * paddings["resizeRatio"] as Float
}
val resMap = Arguments.createMap()
resMap.putString("text", text)
resMap.putArray("bbox", box.toWritableArray())
resMap.putDouble("score", confidenceScore)
predictions.pushMap(resMap)
}
promise.resolve(predictions)
} catch (e: Exception) {
Log.d("rn_executorch", "Error running model: ${e.message}")
promise.reject(e.message!!, e.message)
}
}
override fun getName(): String {
return NAME
}
}