SimpleLPR is an Automatic Number Plate Recognition (ANPR) library that provides powerful license plate detection and recognition capabilities. The Python wrapper pySimpleLPR3 exposes the full functionality of the native SimpleLPR library through a clean, Pythonic interface.
SimpleLPR can be easily installed from PyPI:
pip install simplelpr
import simplelpr
# Basic engine setup
setup_params = simplelpr.EngineSetupParms()
engine = simplelpr.SimpleLPR(setup_params)
# Set license key
engine.set_productKey("path/to/license.xml")
# or from bytes
# with open("license.xml", "rb") as f:
# engine.set_productKey(f.read())
Note: The PyPI version (pip install simplelpr) does not include CUDA GPU acceleration support. For CUDA support, use the SDK version with the pySimpleLPR3 module.
The main engine class that serves as the entry point for all SimpleLPR functionality.
SimpleLPR(parms: EngineSetupParms)
SimpleLPR(parms: EngineSetupParms, nativeFolderPath: str)
Parameters:
parms: Engine setup parametersnativeFolderPath: Optional path to native library folderversionNumber: VersionNumber (read-only)Returns the version number of the SimpleLPR library.
numSupportedCountries: int (read-only)Returns the number of supported countries for license plate recognition.
set_productKey(productKeyPath: str) -> Noneset_productKey(productKey: bytes) -> NoneSets the product key from a file path or byte array.
Parameters:
productKeyPath: Path to the license fileproductKey: License data as bytesget_countryCode(id: int) -> strReturns the string identifier for a country by its index.
Parameters:
id: Country index (0 to numSupportedCountries-1)Returns: Country string identifier (e.g., "Spain", "Germany")
get_countryWeight(id: int) -> floatget_countryWeight(id: str) -> floatGets the relative weight of a country used for breaking ties when a candidate matches multiple countries.
Parameters:
id: Country index or string identifierReturns: Country weight (0.0 to disable, higher values for preference)
set_countryWeight(id: int, weight: float) -> Noneset_countryWeight(id: str, weight: float) -> NoneSets the relative weight of a country.
Parameters:
id: Country index or string identifierweight: Country weight (≥ 0.0, use 0.0 to disable)realizeCountryWeights() -> NoneBuilds internal country verification lookup tables. Call after configuring country weights.
Note: This method can be time-consuming depending on countries selected.
openVideoSource(uri: str, format: FrameFormat, maxWidthCap: int = -1, maxHeightCap: int = -1) -> VideoSourceOpens a video source from URI with optional frame rescaling.
Parameters:
uri: Video source location (file path, RTSP URL, etc.)format: Desired color format for framesmaxWidthCap: Maximum frame width (-1 for no limit)maxHeightCap: Maximum frame height (-1 for no limit)Returns: VideoSource object for frame access
createProcessor() -> ProcessorCreates a new processor for license plate recognition.
Returns: Processor instance
Note: Each thread should use its own processor instance.
createProcessorPool(cProcessors: int = 0) -> ProcessorPoolCreates a processor pool for concurrent processing.
Parameters:
cProcessors: Number of processors (0 = auto-detect based on CPU cores)Returns: ProcessorPool instance
createPlateCandidateTracker(parms: PlateCandidateTrackerSetupParms) -> PlateCandidateTrackerCreates a plate candidate tracker for video processing.
Parameters:
parms: Tracker configuration parametersReturns: PlateCandidateTracker instance
Provides license plate recognition functionality for single-threaded processing.
numSupportedCountries: int (read-only)Number of supported countries.
contrastSensitivityFactor: float (read/write)Contrast sensitivity factor (0.0-1.0). Lower values help with shadows, higher values for normal conditions.
plateRegionDetectionEnabled: bool (read/write)Enables/disables plate region detection and extraction.
cropToPlateRegionEnabled: bool (read/write)Enables/disables cropping results to detected plate region.
analyze(imgPath: str) -> List[Candidate]Analyzes an image file for license plates.
Parameters:
imgPath: Path to image file (.jpg, .png, .tif)Returns: List of detected license plate candidates
analyze(imgBuf: buffer) -> List[Candidate]Analyzes an image from memory buffer.
Parameters:
imgBuf: Image data supporting Python buffer protocol (numpy array, bytes, etc.)Returns: List of detected license plate candidates
Same as SimpleLPR engine:
get_countryCode(id: int) -> strget_countryWeight(id: int) -> floatset_countryWeight(id: int, weight: float) -> NonerealizeCountryWeights() -> NoneProvides multi-threaded license plate recognition using a pool of processors.
numSupportedCountries: int (read-only)Number of supported countries.
contrastSensitivityFactor: float (read/write)Contrast sensitivity factor for all processors in the pool.
plateRegionDetectionEnabled: bool (read/write)Enables/disables plate region detection for all processors.
cropToPlateRegionEnabled: bool (read/write)Enables/disables crop to plate region for all processors.
launchAnalyze(streamId: int, requestId: int, timestampInSec: float, timeoutInMs: int, imgPath: str) -> boolLaunches asynchronous analysis of an image file.
Parameters:
streamId: Stream identifier for grouping related requestsrequestId: Unique request identifiertimestampInSec: Image timestamp in secondstimeoutInMs: Timeout for getting an available processorimgPath: Path to image fileReturns: True if analysis launched successfully
launchAnalyze(streamId: int, requestId: int, timeoutInMs: int, frame: VideoFrame) -> boollaunchAnalyze(streamId: int, requestId: int, timeoutInMs: int, frame: VideoFrame, roi: Rectangle) -> boolLaunches asynchronous analysis of a video frame.
Parameters:
streamId: Stream identifierrequestId: Unique request identifiertimeoutInMs: Timeout for getting processorframe: VideoFrame to analyzeroi: Optional region of interestReturns: True if analysis launched successfully
launchAnalyze(streamId: int, requestId: int, timestampInSec: float, timeoutInMs: int, imgBuf: buffer) -> boolLaunches asynchronous analysis of image from buffer.
Parameters:
streamId: Stream identifierrequestId: Unique request identifiertimestampInSec: Image timestamptimeoutInMs: Timeout for getting processorimgBuf: Image bufferReturns: True if analysis launched successfully
pollNextResult(streamId: int, timeoutInMs: int) -> ProcessorPoolResult | NoneRetrieves the next available analysis result.
Parameters:
streamId: Stream ID to get results for (STREAM_ID_ANY for any stream)timeoutInMs: Timeout for waiting for resultReturns: ProcessorPoolResult or None if timeout
ongoingRequestCount_get(streamId: int) -> intGets the number of ongoing analysis requests.
Parameters:
streamId: Stream ID to count (STREAM_ID_ANY for all streams)Returns: Number of ongoing requests
Same as SimpleLPR engine and Processor.
Provides access to video frames from various sources (files, streams, cameras).
isLiveSource: bool (read-only)Indicates if the source is a live stream (True) or file (False).
state: VideoSourceState (read-only)Current state of the video source.
nextFrame() -> VideoFrame | NoneRetrieves the next video frame.
Returns: VideoFrame object or None if no frame available
reconnect() -> NoneAttempts to reconnect live sources in error states. No effect on file sources.
Represents a single video frame with metadata and pixel data.
sequenceNumber: int (read-only)Unique sequential number of the frame within the video stream.
timestamp: float (read-only)Frame timestamp in seconds since video start.
format: FrameFormat (read-only)Color format of the video frame.
width: int (read-only)Frame width in pixels.
height: int (read-only)Frame height in pixels.
widthStep: int (read-only)Number of bytes between consecutive row starts.
data: capsule (read-only)Pointer to raw pixel data.
saveAsJPEG(imgPath: str, quality: int = -1) -> NoneSaves the frame as a JPEG file.
Parameters:
imgPath: Output file pathquality: JPEG quality (-1 for default, 0-100)VideoFrame supports Python's buffer protocol, allowing direct access to pixel data:
import numpy as np
frame_array = np.array(video_frame, copy=False)
Tracks license plate candidates across multiple video frames, providing temporal correlation resistant to OCR errors.
processFrameCandidates(frameId: int, timestampInSec: float, processorPoolResult: ProcessorPoolResult) -> PlateCandidateTrackerResultProcesses candidates from a frame without image data.
Parameters:
frameId: Unique frame identifiertimestampInSec: Frame timestampprocessorPoolResult: Result from ProcessorPool.pollNextResult()Returns: Tracking results with new and closed tracks
processFrameCandidates(processorPoolResult: ProcessorPoolResult, frame: VideoFrame) -> PlateCandidateTrackerResultProcesses candidates with video frame for thumbnail extraction.
Parameters:
processorPoolResult: Result from ProcessorPool.pollNextResult()frame: Video frame for thumbnail extractionReturns: Tracking results with new and closed tracks
processFrameCandidates(frameId: int, timestampInSec: float, processorPoolResult: ProcessorPoolResult, format: FrameFormat, imgBuf: buffer) -> PlateCandidateTrackerResultProcesses candidates with raw image data for thumbnail extraction.
Parameters:
frameId: Unique frame identifiertimestampInSec: Frame timestampprocessorPoolResult: Result from ProcessorPool.pollNextResult()format: Image format specificationimgBuf: Raw image data bufferReturns: Tracking results with new and closed tracks
flush() -> PlateCandidateTrackerResultForces tracker to close all active tracks.
Returns: Results containing all closed tracks
Represents a license plate tracked across multiple video frames.
firstDetectionFrameId: intFrame ID of the first detection.
firstDetectionTimestamp: floatTimestamp of the first detection in seconds.
newestDetectionFrameId: intFrame ID of the most recent detection.
newestDetectionTimestamp: floatTimestamp of the most recent detection in seconds.
representativeFrameId: intFrame ID of the representative detection.
representativeTimestamp: floatTimestamp of the representative frame in seconds.
representativeCandidate: CandidateBest license plate candidate from this track.
representativeThumbnail: VideoFrame | NoneThumbnail image of the plate from representative frame.
Contains the results of plate tracking operations.
newTracks: List[TrackedPlateCandidate]Collection of new tracks that met trigger criteria.
closedTracks: List[TrackedPlateCandidate]Collection of tracks closed due to inactivity or other criteria.
Represents a detected license plate candidate.
darkOnLight: boolTrue if plate has dark text on light background.
plateDetectionConfidence: floatConfidence that candidate is a license plate vs. scene text (-1 if detection disabled).
boundingBox: RectangleBounding box of the text in pixel coordinates.
plateRegionVertices: List[Point]Four vertices of detected plate region (or -1 coordinates if not detected).
matches: List[Match]List of possible country matches. Last entry is raw text before country validation.
Represents a possible country match for a license plate candidate.
country: strCountry code string.
countryISO: strCountry ISO Alpha-2 code.
text: strUnicode representation of the license plate string.
confidence: floatOverall recognition confidence (product of element confidences).
boundingBox: RectangleBounding box of the text in pixel coordinates.
elements: List[Element]Information about individual characters in reading order.
Represents a candidate character in a license plate.
glyph: strUnicode representation of the character.
confidence: floatRecognition confidence (0-1 range, not a probability).
boundingBox: RectangleBounding box of the character in pixel coordinates.
Configuration parameters for SimpleLPR engine initialization.
cudaDeviceId: intCUDA device identifier (-1 for CPU mode).
Note: CUDA support is only available in the SDK version, not the PyPI package.
enableImageProcessingWithGPU: boolEnable GPU for image processing tasks.
Note: GPU features are only available in the SDK version, not the PyPI package.
enableClassificationWithGPU: boolEnable GPU for candidate classification.
Note: GPU features are only available in the SDK version, not the PyPI package.
maxConcurrentImageProcessingOps: intMaximum concurrent image processing operations (0 for automatic).
Recommended values:
Configuration parameters for plate candidate tracking.
PlateCandidateTrackerSetupParms(
triggerWindowInSec: float = 3.0,
maxIdleTimeInSec: float = 3.5,
minTriggerFrameCount: int = 3,
thumbnailWidth: int = 256,
thumbnailHeight: int = 128
)
triggerWindowInSec: floatTime window for track triggering (default: 3.0 seconds).
maxIdleTimeInSec: floatMaximum idle time before track closure (default: 3.5 seconds).
minTriggerFrameCount: intMinimum detections needed to trigger track (default: 3).
thumbnailWidth: intTarget thumbnail width in pixels (default: 256, -1 for uncapped).
thumbnailHeight: intTarget thumbnail height in pixels (default: 128, -1 for uncapped).
Represents a 2D point with integer coordinates.
x: int - X coordinatey: int - Y coordinateRepresents a rectangle with integer coordinates.
left: int - Left edge X coordinatetop: int - Top edge Y coordinatewidth: int - Rectangle widthheight: int - Rectangle heightRepresents a version number with four components.
A: int - Generation numberB: int - Major versionC: int - Minor versionD: int - Patch versionContains error information when operations fail.
errorCode: int (read-only)HRESULT-style error code.
description: str (read-only)Textual error description.
Contains the result of an asynchronous processor pool operation.
streamId: int (read-only)Stream identifier for the request.
requestId: int (read-only)Unique request identifier.
timestamp: float (read-only)Timestamp of the analyzed image/frame.
errorInfo: ErrorInfo | None (read-only)Error information if analysis failed.
candidates: List[Candidate] (read-only)Detected license plate candidates if analysis succeeded.
Specifies video frame color formats.
FRAME_FORMAT_GRAY8 - 8-bit grayscaleFRAME_FORMAT_BGR24 - 24-bit Blue-Green-RedRepresents video source states.
VIDEO_SOURCE_STATE_INIT - Initial stateVIDEO_SOURCE_STATE_OPEN - Successfully openedVIDEO_SOURCE_STATE_EOF - End of file/stream reachedVIDEO_SOURCE_STATE_IO_ERROR - Input/output errorVIDEO_SOURCE_STATE_ERROR - General errorTIMEOUT_INFINITE = -1 - Wait indefinitelyTIMEOUT_IMMEDIATE = 0 - Return immediately (non-blocking)STREAM_ID_ANY = -1 - Match any stream IDSimpleLPR uses exceptions for error handling. Common scenarios:
try:
engine = pySimpleLPR3.SimpleLPR(setup_params)
engine.set_productKey("license.xml")
processor = engine.createProcessor()
candidates = processor.analyze("image.jpg")
except Exception as e:
print(f"SimpleLPR error: {e}")
For ProcessorPool operations, check the errorInfo property of results:
result = pool.pollNextResult(0, pySimpleLPR3.TIMEOUT_INFINITE)
if result.errorInfo:
print(f"Analysis failed: {result.errorInfo.description}")
else:
print(f"Found {len(result.candidates)} plates")
All objects use automatic memory management through reference counting. No manual cleanup required in Python.
set_countryWeight(country, 0.0) to improve performanceThis completes the SimpleLPR Python API Reference Guide. The next step would be creating a Quick Start Guide with tutorials and practical examples.