テキスト範囲の検出フィルタ
サンプルコード
EdgeOCR では「テキスト範囲の検出 → テキスト認識」の流れで OCR を行います。検出段階で得られた位置情報を利用して、テキスト認識の前にフィルタリングを行うことができます。
DetectionFilter の実装
DetectionFilter クラスを継承し、filter メソッドを実装します。以下は画面中心に最も近いテキストのみを返すフィルタの例です。
- iOS (Swift)
- Android (Java)
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
}
}
public class GetCenterDetectionFilter extends DetectionFilter {
@Override
public List<Detection> filter(List<Detection> list) {
Detection mostLikelyBox = null;
double minDistance = Double.MAX_VALUE;
for (Detection detection : list) {
RectF box = detection.getBoundingBox();
double distance = Math.pow(box.centerX() - 0.5, 2)
+ Math.pow(box.centerY() - 0.5, 2);
if (distance < minDistance) {
minDistance = distance;
mostLikelyBox = detection;
}
}
if (mostLikelyBox != null) {
return Collections.singletonList(mostLikelyBox);
} else {
return Collections.emptyList();
}
}
}
注記
filter メソッドに渡される Detection はテキスト認識前のため、Text や Barcode にキャストすることはできません。位置情報のみを使ってフィルタリングを行います。
フィルタの設定
作成したフィルタを ModelSettings の setDetectionFilter で設定し、useModel に渡します。
- iOS (Swift)
- Android (Java)
let modelSettings = ModelSettings()
modelSettings.setDetectionFilter(CenterDetectionFilter())
loadModelAndNavigate(destination: .detectionFilterView, modelSettings: modelSettings)
ModelSettings modelSettings = new ModelSettings();
modelSettings.setDetectionFilter(new GetCenterDetectionFilter());
loadModelAndStartActivity(intent, modelSettings);