FastALPR allows you to replace the default OCR engine by implementing a custom class that inherits from BaseOCR. To integrate a new engine (like Tesseract or EasyOCR), you must implement the predict method, which accepts a np.ndarray representing the cropped license plate and returns an OcrResult object or None.
import numpy as np
import pytesseract
import re
from statistics import mean
from fast_alpr.alpr import ALPR, BaseOCR, OcrResult
class PytesseractOCR(BaseOCR):
def __init__(self) -> None:
pass
def predict(self, cropped_plate: np.ndarray) -> OcrResult | None:
if cropped_plate is None:
return None
# Example implementation using pytesseract
data = pytesseract.image_to_data(
cropped_plate,
lang="eng",
config="--oem 3 --psm 6",
output_type=pytesseract.Output.DICT,
)
plate_text = " ".join(data["text"]).strip()
plate_text = re.sub(r"[^A-Za-z0-9]", "", plate_text)
avg_confidence = mean(conf for conf in data["conf"] if conf > 0) / 100.0
return OcrResult(text=plate_text, confidence=avg_confidence)
# Initialize ALPR with the custom OCR
alpr = ALPR(detector_model="yolo-v9-t-384-license-plate-end2end", ocr=PytesseractOCR())
alpr_results = alpr.predict("assets/test_image.png")
print(alpr_results)