メインコンテンツまでスキップ

テキスト範囲の検出フィルタ

EdgeOCR では「テキスト範囲の検出 → テキスト認識」の流れで OCR を行います。検出段階で得られた位置情報を利用して、テキスト認識の前にフィルタリングを行うことができます。

DetectionFilter の実装

DetectionFilter クラスを継承し、filter メソッドを実装します。以下は画面中心に最も近いテキストのみを返すフィルタの例です。

class CenterDetectionFilter: DetectionFilter {
override func filter(_ detections: [Detection]) -> [Detection] {
var filteredDetections: [Detection] = []
if detections.count > 0 {
var mostCenteredBox = detections[0]
var distanceFromCenter = 100.0
for detection in detections {
let dist = calcDistanceFromCenter(detection: detection)
if dist < distanceFromCenter {
distanceFromCenter = dist
mostCenteredBox = detection
}
}
filteredDetections.append(mostCenteredBox)
}
return filteredDetections
}

private func calcDistanceFromCenter(detection: Detection) -> CGFloat {
let bbox = detection.getBoundingBox()
let boxCenterX = bbox.minX + 0.5 * (bbox.maxX - bbox.minX)
let boxCenterY = bbox.minY + 0.5 * (bbox.maxY - bbox.minY)
let a = 0.5 - boxCenterX
let b = 0.5 - boxCenterY
return a * a + b * b
}
}
注記

filter メソッドに渡される Detection はテキスト認識前のため、TextBarcode にキャストすることはできません。位置情報のみを使ってフィルタリングを行います。

フィルタの設定

作成したフィルタを ModelSettingssetDetectionFilter で設定し、useModel に渡します。

let modelSettings = ModelSettings()
modelSettings.setDetectionFilter(CenterDetectionFilter())
loadModelAndNavigate(destination: .detectionFilterView, modelSettings: modelSettings)