### Install Dependencies Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/contributing.md Installs all project dependencies. Ensure you have uv installed prior to running this command. ```shell make install ``` -------------------------------- ### Install FastALPR with ONNX Runtime Backends Source: https://context7.com/ankandrew/fast-alpr/llms.txt Install FastALPR using pip, selecting the appropriate ONNX Runtime backend for your hardware. Options include CPU, NVIDIA GPU (CUDA), Intel OpenVINO, Windows DirectML, and Qualcomm QNN. ```bash pip install fast-alpr[onnx] ``` ```bash pip install fast-alpr[onnx-gpu] ``` ```bash pip install fast-alpr[onnx-openvino] ``` ```bash pip install fast-alpr[onnx-directml] ``` ```bash pip install fast-alpr[onnx-qnn] ``` -------------------------------- ### Initialize ALPR with Custom ONNX Runtime Providers Source: https://context7.com/ankandrew/fast-alpr/llms.txt Initialize the ALPR class with custom ONNX Runtime execution providers for hardware acceleration. This example configures CUDA and CPU providers and sets session options for threading. ```python import onnxruntime as ort alpr_gpu = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", detector_providers=["CUDAExecutionProvider", "CPUExecutionProvider"], detector_sess_options=sess_opts, ocr_model="cct-s-v2-global-model", ocr_device="cuda", ) ``` -------------------------------- ### Install fast-alpr with ONNX GPU support Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/installation.md Install fast-alpr with ONNX runtime for NVIDIA GPU inference. This is one of several optional ONNX extras required for inference. ```shell pip install fast-alpr[onnx-gpu] ``` -------------------------------- ### Clone the Repository Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/contributing.md Use this command to get a local copy of the fast-alpr repository. ```shell git clone https://github.com/ankandrew/fast-alpr.git ``` -------------------------------- ### Implement Custom Detector with BaseDetector Source: https://context7.com/ankandrew/fast-alpr/llms.txt Provides an example of creating a custom detector by inheriting from BaseDetector. Requires implementing the predict method to return DetectionResult objects. ```python import numpy as np from open_image_models.detection.core.base import BoundingBox, DetectionResult from fast_alpr import ALPR from fast_alpr.base import BaseDetector class MyYOLODetector(BaseDetector): """Example: wrap any detection model.""" def __init__(self, model_path: str, conf_thresh: float = 0.5): # Load your model here (e.g., ultralytics YOLO, torchvision, etc.) self.model = ... # your model self.conf_thresh = conf_thresh def predict(self, frame: np.ndarray) -> list[DetectionResult]: # Run inference; return list of DetectionResult raw = self.model(frame) # hypothetical call results = [] for box, conf, label in raw: if conf >= self.conf_thresh: results.append( DetectionResult( label=label, confidence=float(conf), bounding_box=BoundingBox( x1=int(box[0]), y1=int(box[1]), x2=int(box[2]), y2=int(box[3]), ), ) ) return results # Pass custom detector; keep default OCR alpr = ALPR( detector=MyYOLODetector("my_model.onnx", conf_thresh=0.45), ocr_model="cct-xs-v2-global-model", ) results = alpr.predict("assets/test_image.png") ``` -------------------------------- ### ALPR.predict() Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/reference.md Get structured ALPR results from an image. ```APIDOC ## ALPR.predict() ### Description This method processes an image to detect and recognize license plates, returning structured results. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (NumPy array or string) - Required - A NumPy image in BGR format or a string path to an image file. ### Request Example ```python # Example usage with a NumPy array import numpy as np from fast_alpr import ALPR alpr = ALPR() image_bgr = np.zeros((100, 200, 3), dtype=np.uint8) results = alpr.predict(image_bgr) # Example usage with an image path # results = alpr.predict("path/to/your/image.jpg") ``` ### Response #### Success Response (200) - **results** (list[ALPRResult]) - A list of ALPRResult objects, each containing detection and OCR information. #### Response Example ```json { "results": [ { "detection": { "box": [x1, y1, x2, y2], "label": "plate", "confidence": 0.95 }, "ocr": { "text": "ABC 123", "confidence": 0.98 } } ] } ``` ``` -------------------------------- ### Integrate Tesseract OCR with FastALPR Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/custom_models.md Implement a custom OCR class inheriting from BaseOCR to use Tesseract. This allows leveraging Tesseract's capabilities for plate recognition within FastALPR. Ensure Tesseract is installed and configured correctly. ```python import re from statistics import mean import numpy as np import pytesseract from fast_alpr.alpr import ALPR, BaseOCR, OcrResult class PytesseractOCR(BaseOCR): def __init__(self) -> None: """ Init PytesseractOCR. """ def predict(self, cropped_plate: np.ndarray) -> OcrResult | None: if cropped_plate is None: return None # You can change 'eng' to the appropriate language code as needed 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) alpr = ALPR(detector_model="yolo-v9-t-384-license-plate-end2end", ocr=PytesseractOCR()) alpr_results = alpr.predict("assets/test_image.png") print(alpr_results) ``` -------------------------------- ### ALPR.draw_predictions() Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/reference.md Get an annotated image with ALPR results. ```APIDOC ## ALPR.draw_predictions() ### Description This method processes an image, draws bounding boxes and recognized text on it, and returns the annotated image along with the ALPR results. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (NumPy array or string) - Required - A NumPy image in BGR format or a string path to an image file. ### Request Example ```python # Example usage with a NumPy array import numpy as np from fast_alpr import ALPR alpr = ALPR() image_bgr = np.zeros((100, 200, 3), dtype=np.uint8) draw_result = alpr.draw_predictions(image_bgr) # Example usage with an image path # draw_result = alpr.draw_predictions("path/to/your/image.jpg") ``` ### Response #### Success Response (200) - **draw_result** (DrawPredictionsResult) - An object containing the annotated image and the ALPR results. #### Response Example ```json { "image": "base64_encoded_image_string", "results": [ { "detection": { "box": [x1, y1, x2, y2], "label": "plate", "confidence": 0.95 }, "ocr": { "text": "ABC 123", "confidence": 0.98 } } ] } ``` ``` -------------------------------- ### Run Linting and Tests Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/contributing.md Executes linting and tests to ensure code quality before submitting changes. This command should be run before creating a Pull Request. ```shell make checks ``` -------------------------------- ### Initialize ALPR Class with Default Models Source: https://context7.com/ankandrew/fast-alpr/llms.txt Instantiate the ALPR class using default detection and OCR models. Specify the detector model name, confidence threshold, OCR model name, and the device for OCR processing. ```python from fast_alpr import ALPR alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", # PlateDetectorModel detector_conf_thresh=0.4, # detection confidence threshold ocr_model="cct-xs-v2-global-model", # OcrModel hub name ocr_device="auto", # "auto" | "cpu" | "cuda" ) ``` -------------------------------- ### Initialize ALPR with Detector and OCR Models Source: https://context7.com/ankandrew/fast-alpr/llms.txt Initializes the ALPR class with specified detector and OCR models. Accesses results and prints detected text with average confidence. ```python from fast_alpr import ALPR, ALPRResult from fast_alpr.base import OcrResult alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) results: list[ALPRResult] = alpr.predict("assets/test_image.png") for r in results: # r.detection -> DetectionResult (from open-image-models) # .label str # .confidence float # .bounding_box BoundingBox(x1, y1, x2, y2) — pixel coords, int # r.ocr -> OcrResult | None # .text str recognized plate string # .confidence float | list[float] # .region str | None # .region_confidence float | None ocr: OcrResult | None = r.ocr if ocr: avg_conf = ( sum(ocr.confidence) / len(ocr.confidence) if isinstance(ocr.confidence, list) else ocr.confidence ) print(f"{ocr.text} avg_conf={avg_conf:.2%}") ``` -------------------------------- ### ALPR Class Initialization Source: https://context7.com/ankandrew/fast-alpr/llms.txt Instantiate the ALPR class with specified detector and OCR models. You can also configure detection confidence thresholds and OCR device. Custom ONNX Runtime execution providers can be specified for hardware acceleration. ```APIDOC ## ALPR ### Description The central class of the library. Instantiates a detector and OCR model (from the model hub or custom implementations) and exposes `predict()` and `draw_predictions()` methods. ### Initialization ```python from fast_alpr import ALPR # Default models: YOLOv9-t detector + CCT-XS OCR (global) alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", # PlateDetectorModel detector_conf_thresh=0.4, # detection confidence threshold ocr_model="cct-xs-v2-global-model", # OcrModel hub name ocr_device="auto", # "auto" | "cpu" | "cuda" ) # With custom ONNX Runtime execution providers import onnxruntime as ort sess_opts = ort.SessionOptions() sess_opts.intra_op_num_threads = 4 alpr_gpu = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", detector_providers=["CUDAExecutionProvider", "CPUExecutionProvider"], detector_sess_options=sess_opts, ocr_model="cct-s-v2-global-model", ocr_device="cuda", ) ``` ``` -------------------------------- ### Implement Custom OCR with BaseOCR and Pytesseract Source: https://context7.com/ankandrew/fast-alpr/llms.txt Demonstrates creating a custom OCR backend using Pytesseract by inheriting from BaseOCR. The predict method should return an OcrResult object. ```python import re from statistics import mean import numpy as np import pytesseract from fast_alpr import ALPR from fast_alpr.base import BaseOCR, OcrResult class PytesseractOCR(BaseOCR): """Drop-in OCR using Tesseract.""" def predict(self, cropped_plate: np.ndarray) -> OcrResult | None: if cropped_plate is None: return None data = pytesseract.image_to_data( cropped_plate, lang="eng", config="--oem 3 --psm 6", output_type=pytesseract.Output.DICT, ) plate_text = re.sub(r"[^A-Za-z0-9]", "", " ".join(data["text"]).strip()) confidences = [c for c in data["conf"] if c > 0] avg_confidence = mean(confidences) / 100.0 if confidences else 0.0 return OcrResult(text=plate_text, confidence=avg_confidence) # Use default detector + Tesseract OCR alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr=PytesseractOCR(), ) results = alpr.predict("assets/test_image.png") for r in results: if r.ocr: print(f"Tesseract: {r.ocr.text} ({r.ocr.confidence:.2%})") ``` -------------------------------- ### Initialize ALPR with Default Detector Source: https://context7.com/ankandrew/fast-alpr/llms.txt Shows the import statement for the DefaultDetector, which is used automatically when no custom detector is provided to the ALPR class. ```python import onnxruntime as ort from fast_alpr.default_detector import DefaultDetector import cv2 ``` -------------------------------- ### Initialize ALPR with custom models and predict Source: https://github.com/ankandrew/fast-alpr/blob/master/README.md Initialize the ALPR with specific detector and OCR models, then predict license plates from an image. Ensure the image path is correct. ```python from fast_alpr import ALPR # You can also initialize the ALPR with custom plate detection and OCR models. alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # The "assets/test_image.png" can be found in repo root dir alpr_results = alpr.predict("assets/test_image.png") print(alpr_results) ``` -------------------------------- ### Custom OCR Interface Source: https://context7.com/ankandrew/fast-alpr/llms.txt Illustrates how to integrate a custom OCR engine by implementing the `BaseOCR` interface. ```APIDOC ## `BaseOCR` — Custom OCR Interface Abstract base class for plugging in a custom OCR backend. Implement `predict(cropped_plate)` to return `OcrResult | None`. ### Method `predict(cropped_plate: np.ndarray) -> OcrResult | None` ### Parameters - **cropped_plate** (np.ndarray) - A NumPy array representing the cropped image of the license plate. ### Response - **OcrResult | None** - An `OcrResult` object containing the recognized text and confidence, or None if OCR fails. ### Request Example ```python import re from statistics import mean import numpy as np import pytesseract from fast_alpr import ALPR from fast_alpr.base import BaseOCR, OcrResult class PytesseractOCR(BaseOCR): def predict(self, cropped_plate: np.ndarray) -> OcrResult | None: if cropped_plate is None: return None data = pytesseract.image_to_data( cropped_plate, lang="eng", config="--oem 3 --psm 6", output_type=pytesseract.Output.DICT, ) plate_text = re.sub(r"[^A-Za-z0-9]", "", " ".join(data["text"]).strip()) confidences = [c for c in data["conf"] if c > 0] avg_confidence = mean(confidences) / 100.0 if confidences else 0.0 return OcrResult(text=plate_text, confidence=avg_confidence) alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr=PytesseractOCR(), ) results = alpr.predict("assets/test_image.png") for r in results: if r.ocr: print(f"Tesseract: {r.ocr.text} ({r.ocr.confidence:.2%})") ``` ``` -------------------------------- ### Import FastALPR Components Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/reference.md Import necessary classes from the fast_alpr library for ALPR processing and result handling. ```python from fast_alpr import ALPR, ALPRResult, DrawPredictionsResult, OcrResult ``` -------------------------------- ### Standalone Detector Usage Source: https://context7.com/ankandrew/fast-alpr/llms.txt Instantiate and use the DefaultDetector for license plate detection. Configure session options for optimization. ```python import cv2 import onnxruntime as ort from fast_alpr.detector import DefaultDetector sess_opts = ort.SessionOptions() sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL detector = DefaultDetector( model_name="yolo-v9-t-384-license-plate-end2end", conf_thresh=0.35, providers=["CPUExecutionProvider"], sess_options=sess_opts, ) frame = cv2.imread("assets/test_image.png") detections = detector.predict(frame) for d in detections: print(f"Label: {d.label}, Conf: {d.confidence:.2%}") print(f"Box: ({d.bounding_box.x1},{d.bounding_box.y1}) -> ({d.bounding_box.x2},{d.bounding_box.y2})") ``` -------------------------------- ### ALPR Prediction and Result Access Source: https://context7.com/ankandrew/fast-alpr/llms.txt Demonstrates how to initialize the ALPR model, perform predictions on an image, and iterate through the results to access detection and OCR information. ```APIDOC ## `ALPR` — Main Class ### Description Initializes the ALPR pipeline with specified detector and OCR models, and provides methods for prediction. ### Method `predict(frame: str | np.ndarray) -> list[ALPRResult]` ### Parameters - **frame** (str | np.ndarray) - Path to the image file or a NumPy array representing the image. ### Response - **list[ALPRResult]** - A list of ALPRResult objects, each containing detection and OCR data for a detected plate. #### `ALPRResult` — Detection + OCR Result Dataclass Immutable dataclass returned per detected plate from `predict()` and `draw_predictions()`. - **detection** (`DetectionResult`) - Detection details including label, confidence, and bounding box. - **ocr** (`OcrResult` | None) - OCR results including the recognized text, confidence, region, and region confidence. ### Request Example ```python from fast_alpr import ALPR alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) results = alpr.predict("assets/test_image.png") for r in results: if r.ocr: avg_conf = ( sum(r.ocr.confidence) / len(r.ocr.confidence) if isinstance(r.ocr.confidence, list) else r.ocr.confidence ) print(f"{r.ocr.text} avg_conf={avg_conf:.2%}") ``` ``` -------------------------------- ### Custom Detector Interface Source: https://context7.com/ankandrew/fast-alpr/llms.txt Shows how to implement a custom detector by inheriting from `BaseDetector` and plugging it into the ALPR pipeline. ```APIDOC ## `BaseDetector` — Custom Detector Interface Abstract base class for plugging in a custom plate detector. Implement `predict(frame)` to return `list[DetectionResult]`. ### Method `predict(frame: np.ndarray) -> list[DetectionResult]` ### Parameters - **frame** (np.ndarray) - The input image frame. ### Response - **list[DetectionResult]** - A list of `DetectionResult` objects. ### Request Example ```python import numpy as np from open_image_models.detection.core.base import BoundingBox, DetectionResult from fast_alpr import ALPR from fast_alpr.base import BaseDetector class MyYOLODetector(BaseDetector): def __init__(self, model_path: str, conf_thresh: float = 0.5): self.model = ... # your model self.conf_thresh = conf_thresh def predict(self, frame: np.ndarray) -> list[DetectionResult]: raw = self.model(frame) # hypothetical call results = [] for box, conf, label in raw: if conf >= self.conf_thresh: results.append( DetectionResult( label=label, confidence=float(conf), bounding_box=BoundingBox( x1=int(box[0]), y1=int(box[1]), x2=int(box[2]), y2=int(box[3]), ), ) ) return results alpr = ALPR( detector=MyYOLODetector("my_model.onnx", conf_thresh=0.45), ocr_model="cct-xs-v2-global-model", ) results = alpr.predict("assets/test_image.png") ``` ``` -------------------------------- ### ALPR.predict() Source: https://context7.com/ankandrew/fast-alpr/llms.txt Runs the full plate detection and OCR pipeline on an image. Accepts either a file path or a NumPy BGR array and returns a list of ALPRResult objects, each containing detection and OCR details. ```APIDOC ## ALPR.predict() ### Description Runs the full plate detection + OCR pipeline on an image. Accepts a file path string or a NumPy BGR array. Returns a `list[ALPRResult]`. ### Method ```python alpr.predict(image_source: str | np.ndarray) -> list[ALPRResult] ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cv2 from fast_alpr import ALPR, ALPRResult alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # --- From file path --- results: list[ALPRResult] = alpr.predict("assets/test_image.png") # --- From NumPy BGR array --- frame = cv2.imread("assets/test_image.png") results = alpr.predict(frame) # Inspect results for r in results: bbox = r.detection.bounding_box # BoundingBox(x1, y1, x2, y2) det_conf = r.detection.confidence # float, detector confidence label = r.detection.label # e.g. "license-plate" if r.ocr is not None: plate_text = r.ocr.text # e.g. "5AU5341" char_confs = r.ocr.confidence # float or list[float] per character region = r.ocr.region # e.g. "Argentina" or None region_conf = r.ocr.region_confidence # float or None print(f"Plate: {plate_text} | BBox: ({bbox.x1},{bbox.y1})-({bbox.x2},{bbox.y2})") print(f" Det confidence : {det_conf:.2%}") print(f" OCR confidence : {char_confs}") if region: print(f" Region: {region} ({region_conf:.2%})") ``` ### Response #### Success Response (200) - **results** (list[ALPRResult]) - A list of detected license plates, each with bounding box, detection confidence, OCR text, and optional region/confidence. #### Response Example ```json [ { "detection": { "bounding_box": {"x1": 142, "y1": 310, "x2": 398, "y2": 370}, "confidence": 0.943, "label": "license-plate" }, "ocr": { "text": "5AU5341", "confidence": [0.99, 0.98, 0.97, 0.99, 0.96, 0.98, 0.99], "region": "US", "region_confidence": 0.85 } } ] ``` ``` -------------------------------- ### Run ALPR Prediction from File Path or NumPy Array Source: https://context7.com/ankandrew/fast-alpr/llms.txt Use the `predict` method to run the full ALPR pipeline on an image. It accepts either a file path or a NumPy BGR array and returns a list of ALPRResult objects. ```python import cv2 from fast_alpr import ALPR, ALPRResult alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # --- From file path --- results: list[ALPRResult] = alpr.predict("assets/test_image.png") # --- From NumPy BGR array --- frame = cv2.imread("assets/test_image.png") results = alpr.predict(frame) # Inspect results for r in results: bbox = r.detection.bounding_box # BoundingBox(x1, y1, x2, y2) det_conf = r.detection.confidence # float, detector confidence label = r.detection.label # e.g. "license-plate" if r.ocr is not None: plate_text = r.ocr.text # e.g. "5AU5341" char_confs = r.ocr.confidence # float or list[float] per character region = r.ocr.region # e.g. "Argentina" or None region_conf = r.ocr.region_confidence # float or None print(f"Plate: {plate_text} | BBox: ({bbox.x1},{bbox.y1})-({bbox.x2},{bbox.y2})") print(f" Det confidence : {det_conf:.2%}") print(f" OCR confidence : {char_confs}") if region: print(f" Region: {region} ({region_conf:.2%})") ``` -------------------------------- ### Standalone OCR Usage Source: https://context7.com/ankandrew/fast-alpr/llms.txt Initialize and utilize the DefaultOCR for license plate text recognition. Supports downloading models from hub or using local files. ```python import cv2 from fast_alpr.default_ocr import DefaultOCR from fast_alpr.base import OcrResult # Standalone usage of the OCR ocr = DefaultOCR( hub_ocr_model="cct-s-v2-global-model", # larger/more accurate variant device="auto", # auto-select GPU or CPU ) # Provide a cropped BGR plate image frame = cv2.imread("assets/test_image.png") # ... crop to plate region first: crop = frame[310:370, 142:398] result: OcrResult | None = ocr.predict(crop) if result: print(f"Text : {result.text}") print(f"Confidence: {result.confidence}") print(f"Region : {result.region} ({result.region_confidence})") # Use a local model file instead of downloading from hub ocr_local = DefaultOCR( hub_ocr_model=None, model_path="/models/my_ocr.onnx", config_path="/models/my_ocr_config.yaml", ) ``` -------------------------------- ### Make Predictions with FastALPR Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/quick_start.md Initialize the ALPR with custom models and predict license plates from an image. You can also pass a NumPy array containing a cropped plate image. ```python from fast_alpr import ALPR # You can also initialize the ALPR with custom plate detection and OCR models. alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # The "assets/test_image.png" can be found in repo root dir # You can also pass a NumPy array containing cropped plate image alpr_results = alpr.predict("assets/test_image.png") print(alpr_results) ``` -------------------------------- ### ALPR.draw_predictions() Source: https://context7.com/ankandrew/fast-alpr/llms.txt Runs the ALPR pipeline and draws bounding boxes and OCR text directly onto the image. Returns a DrawPredictionsResult containing the annotated image and the detection results. ```APIDOC ## ALPR.draw_predictions() ### Description Runs the ALPR pipeline and draws bounding boxes and OCR text (with confidence) directly on the image. Returns a `DrawPredictionsResult` containing the annotated `image` (NumPy array) and the `results` list. ### Method ```python alpr.draw_predictions(image_source: str | np.ndarray) -> DrawPredictionsResult ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cv2 from fast_alpr import ALPR, DrawPredictionsResult alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # From file path drawn: DrawPredictionsResult = alpr.draw_predictions("assets/test_image.png") # From NumPy array (use a copy to preserve original) frame = cv2.imread("assets/test_image.png") drawn = alpr.draw_predictions(frame.copy()) annotated_frame = drawn.image # np.ndarray with boxes and text rendered results = drawn.results # list[ALPRResult], same as predict() ``` ### Response #### Success Response (200) - **drawn** (DrawPredictionsResult) - An object containing the annotated image as a NumPy array and the list of ALPRResult objects. #### Response Example ```json { "image": "", "results": [ { "detection": { "bounding_box": {"x1": 142, "y1": 310, "x2": 398, "y2": 370}, "confidence": 0.943, "label": "license-plate" }, "ocr": { "text": "5AU5341", "confidence": [0.99, 0.98, 0.97, 0.99, 0.96, 0.98, 0.99], "region": "US", "region_confidence": 0.85 } } ] } ``` ``` -------------------------------- ### Draw Predictions on Image with FastALPR Source: https://github.com/ankandrew/fast-alpr/blob/master/docs/quick_start.md Load an image, draw the license plate predictions directly on it, and retrieve both the annotated image and the prediction results. ```python import cv2 from fast_alpr import ALPR # Initialize the ALPR alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # Load the image image_path = "assets/test_image.png" frame = cv2.imread(image_path) # Draw predictions on the image and get the ALPR results drawn = alpr.draw_predictions(frame) annotated_frame = drawn.image results = drawn.results ``` -------------------------------- ### Draw ALPR Predictions on Image Source: https://context7.com/ankandrew/fast-alpr/llms.txt Use the `draw_predictions` method to run the ALPR pipeline and directly render bounding boxes and OCR text onto the image. It returns a DrawPredictionsResult containing the annotated image and prediction results. ```python import cv2 from fast_alpr import ALPR, DrawPredictionsResult alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ) # From file path drawn: DrawPredictionsResult = alpr.draw_predictions("assets/test_image.png") # From NumPy array (use a copy to preserve original) frame = cv2.imread("assets/test_image.png") drawn = alpr.draw_predictions(frame.copy()) annotated_frame = drawn.image # np.ndarray with boxes and text rendered results = drawn.results # list[ALPRResult], same as predict() ``` -------------------------------- ### Video Stream Processing with ALPR Source: https://context7.com/ankandrew/fast-alpr/llms.txt Process real-time video streams using ALPR for license plate detection and recognition. Displays predictions on the video feed. ```python import cv2 from fast_alpr import ALPR alpr = ALPR( detector_model="yolo-v9-t-384-license-plate-end2end", ocr_model="cct-xs-v2-global-model", ocr_device="auto", ) cap = cv2.VideoCapture(0) # 0 = default webcam; or pass a video file path while cap.isOpened(): ret, frame = cap.read() if not ret: break drawn = alpr.draw_predictions(frame) for r in drawn.results: if r.ocr and r.ocr.text: print(f"[LIVE] Plate: {r.ocr.text}") cv2.imshow("FastALPR", drawn.image) if cv2.waitKey(1) & 0xFF == ord("q"): break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Save Annotated Image and Access ALPR Data Source: https://context7.com/ankandrew/fast-alpr/llms.txt Saves the annotated frame to a file and iterates through results to print detected plate text if OCR was performed. ```python cv2.imwrite("output_annotated.jpg", annotated_frame) # Access ALPR data from the same call for r in results: if r.ocr: print(f"Detected: {r.ocr.text}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.