OCR with Master Data (Fuzzy Match)
This section explains how to detect text from master data using edit distance, allowing a certain margin of error.
What Is Edit Distance?
Edit distance is a metric that represents the similarity between two strings. It indicates the minimum number of insertions, deletions, and substitutions required to transform one string into another.
For example, the edit distance between kitten and sitting is 3.
kitten
-(replace k with s)-> sitten
-(replace e with i)-> sittin
-(insert g at end)-> sitting
Implementing FuzzySearch
Use the SDK's FuzzySearch class to calculate the similarity between detection results and master data.
- iOS (Swift)
- Android (Java)
class FuzzySearchAnalyzer {
let candidates: [String] = [
"東京都新宿区",
"群馬県前橋市",
"神奈川県横浜市",
"大阪府中央区",
"沖縄県那覇市",
"北海道札幌市",
]
let fuzzySearch = FuzzySearch(FuzzySearch.DistanceType.editDistance)
init() {
do {
try fuzzySearch.loadWeight(FuzzySearch.WeightType.NNDistance)
try fuzzySearch.loadMasterData(candidates)
} catch {
os_log("Failed to load weight or master data: %s",
log: .default, type: .error, error.localizedDescription)
}
}
func analyze(_ detections: [Text], minDist: Int) -> AnalyzerResult {
var targetDetections = [Text]()
var notTargetDetections = [Text]()
for detection in detections {
let text = detection.getText()
let ret = fuzzySearch.calcSimilarityWithMasterData(
text, parallel: true, normalized: false)
if let ret = ret {
let (matched, dist) = ret
if dist <= Double(minDist) {
detection.setText(matched)
targetDetections.append(detection)
continue
}
}
notTargetDetections.append(detection)
}
return AnalyzerResult(
targetDetections: targetDetections,
notTargetDetections: notTargetDetections)
}
}
On Android, use the FuzzySearch class in the same way to calculate similarity with master data. See the API reference for details.
Weight Types
The following three weight types can be specified with the loadWeight method.
| Weight Type | Description |
|---|---|
Default | Default weights |
Disabled | No weights used |
NNDistance | Similarity weights computed using a neural network |
Displaying Detection Results
Text that matches the master data (edit distance within the threshold) is displayed in green, while non-matching text is displayed in red.
- iOS (Swift)
- Android (Java)
let detections = result.getTextDetections()
let minDist = 1 // Allow edit distance of 1 or less
let analyzerResult = analyzer.analyze(detections, minDist: minDist)
for targetDetection in analyzerResult.getTargetDetections() {
let bbox = targetDetection.getBoundingBox()
drawDetection(bbox: bbox, text: targetDetection.getText())
}
for notTargetDetection in analyzerResult.getNotTargetDetections() {
let bbox = notTargetDetection.getBoundingBox()
drawDetection(
bbox: bbox, text: notTargetDetection.getText(),
boxColor: UIColor.red.withAlphaComponent(0.5).cgColor)
}
On Android, color-coded display is performed based on FuzzySearch results in the same way. See the sample app for details.