マスターデータを用いた OCR(曖昧一致)
サンプルコード
編集距離を用いて、一定の誤差を許容しながらマスターデータから文字を検出する方法を説明します。
編集距離とは
編集距離は、文字列間の類似度を表す指標です。一方の文字列をもう一方に変換するために必要な挿入・削除・置換の最小回数を表します。
たとえば kitten と sitting の編集距離は 3 です。
kitten
-(k を s に置換)-> sitten
-(e を i に置換)-> sittin
-(g を末尾に挿入)-> sitting
FuzzySearch の実装
SDK の FuzzySearch クラスを使用して、検出結果とマスターデータの類似度を計算します。
- 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)
}
}
Android でも同様に FuzzySearch クラスを使用してマスターデータとの類似度計算を行います。詳細は API リファレンスを参照してください。
重みの種類
loadWeight メソッドで指定できる重みは以下の 3 種類です。
| 重みタイプ | 説明 |
|---|---|
Default | デフォルトの重み |
Disabled | 重みを使用しない |
NNDistance | ニューラルネットワークを使用して算出した類似度重み |
検出結果の表示
マスターデータに一致(編集距離が閾値以下)したテキストは緑色、一致しないテキストは赤色で表示します。
- iOS (Swift)
- Android (Java)
let detections = result.getTextDetections()
let minDist = 1 // 編集距離 1 以下を許容
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)
}
Android でも同様に FuzzySearch の結果に基づいて色分け表示を行います。詳細はサンプルアプリを参照してください。