Skip to main content

Text Region Detection Filter

EdgeOCR performs OCR in two stages: text region detection followed by text recognition. You can apply filtering using the position information obtained during the detection stage, before text recognition takes place.

Implementing DetectionFilter​

Extend the DetectionFilter class and implement the filter method. The following example is a filter that returns only the text closest to the center of the screen.

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
}
}
note

The Detection objects passed to the filter method have not yet undergone text recognition, so they cannot be cast to Text or Barcode. Use only position information for filtering.

Configuring the Filter​

Set the filter you created using setDetectionFilter on ModelSettings, then pass it to useModel.

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