Simplest Example
Sample Code
- iOS: SimpleTextViewController.swift
- Android: SimpleTextScannerActivity.java
This is the simplest OCR example: it starts the camera and logs the text displayed on the screen.
Calling the scan Method
By calling the scan method on each frame captured from the camera, you can detect and recognize text.
- iOS (Swift)
- Android (Java)
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
do {
let scanResult = try edgeOCR.scan(sampleBuffer, viewBounds: viewBounds)
for detection in scanResult.getTextDetections() {
let text = detection.getText()
if !text.isEmpty {
os_log("detected: %@", type: .debug, text)
}
}
} catch {
os_log("Failed to scan texts: %@", type: .debug, error.localizedDescription)
return
}
}
In addition to sampleBuffer, pass viewBounds (the size of the view displaying the camera output) as an argument to edgeOCR.scan.
imageAnalysis.setAnalyzer(analysisExecutor, image -> {
if (!api.isReady()) {
image.close();
return;
}
try {
ScanResult scanResult = api.scan(image);
List<Text> detections = scanResult.getTextDetections();
for (Text detection : detections) {
String text = detection.getText();
if (!text.isEmpty()) {
Log.d("EdgeOCR", "detected: " + text);
}
}
} catch (EdgeError e) {
Log.e("EdgeOCR", "Failed to analyze image", e);
} finally {
image.close();
}
});
About ScanResult
The return value of the scan method is a ScanResult object. You can retrieve detection results using the following methods.
| Method | Description |
|---|---|
getDetections() | Returns all detection results (Detection). Can be cast to Text or Barcode |
getTextDetections() | Returns only text detection results |
getBarcodeDetections() | Returns only barcode detection results |
Since all objects within the scan area are scanned, multiple Detection objects are returned. The types of objects detected are text, barcode, or both, depending on the model selected with useModel.