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) -> None
set_productKey(productKey: bytes) -> None
Sets the product key from a file path or byte array.
Parameters:
productKeyPath
: Path to the license fileproductKey
: License data as bytesget_countryCode(id: int) -> str
Returns 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) -> float
get_countryWeight(id: str) -> float
Gets 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) -> None
set_countryWeight(id: str, weight: float) -> None
Sets the relative weight of a country.
Parameters:
id
: Country index or string identifierweight
: Country weight (≥ 0.0, use 0.0 to disable)realizeCountryWeights() -> None
Builds 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) -> VideoSource
Opens 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() -> Processor
Creates a new processor for license plate recognition.
Returns: Processor instance
Note: Each thread should use its own processor instance.
createProcessorPool(cProcessors: int = 0) -> ProcessorPool
Creates a processor pool for concurrent processing.
Parameters:
cProcessors
: Number of processors (0 = auto-detect based on CPU cores)Returns: ProcessorPool instance
createPlateCandidateTracker(parms: PlateCandidateTrackerSetupParms) -> PlateCandidateTracker
Creates 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) -> str
get_countryWeight(id: int) -> float
set_countryWeight(id: int, weight: float) -> None
realizeCountryWeights() -> None
Provides 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) -> bool
Launches 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) -> bool
launchAnalyze(streamId: int, requestId: int, timeoutInMs: int, frame: VideoFrame, roi: Rectangle) -> bool
Launches 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) -> bool
Launches 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 | None
Retrieves 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) -> int
Gets 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 | None
Retrieves the next video frame.
Returns: VideoFrame object or None if no frame available
reconnect() -> None
Attempts 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) -> None
Saves 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) -> PlateCandidateTrackerResult
Processes 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) -> PlateCandidateTrackerResult
Processes 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) -> PlateCandidateTrackerResult
Processes 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() -> PlateCandidateTrackerResult
Forces tracker to close all active tracks.
Returns: Results containing all closed tracks
Represents a license plate tracked across multiple video frames.
firstDetectionFrameId: int
Frame ID of the first detection.
firstDetectionTimestamp: float
Timestamp of the first detection in seconds.
newestDetectionFrameId: int
Frame ID of the most recent detection.
newestDetectionTimestamp: float
Timestamp of the most recent detection in seconds.
representativeFrameId: int
Frame ID of the representative detection.
representativeTimestamp: float
Timestamp of the representative frame in seconds.
representativeCandidate: Candidate
Best license plate candidate from this track.
representativeThumbnail: VideoFrame | None
Thumbnail 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: bool
True if plate has dark text on light background.
plateDetectionConfidence: float
Confidence that candidate is a license plate vs. scene text (-1 if detection disabled).
boundingBox: Rectangle
Bounding 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: str
Country code string.
countryISO: str
Country ISO Alpha-2 code.
text: str
Unicode representation of the license plate string.
confidence: float
Overall recognition confidence (product of element confidences).
boundingBox: Rectangle
Bounding 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: str
Unicode representation of the character.
confidence: float
Recognition confidence (0-1 range, not a probability).
boundingBox: Rectangle
Bounding box of the character in pixel coordinates.
Configuration parameters for SimpleLPR engine initialization.
cudaDeviceId: int
CUDA device identifier (-1 for CPU mode).
Note: CUDA support is only available in the SDK version, not the PyPI package.
enableImageProcessingWithGPU: bool
Enable GPU for image processing tasks.
Note: GPU features are only available in the SDK version, not the PyPI package.
enableClassificationWithGPU: bool
Enable GPU for candidate classification.
Note: GPU features are only available in the SDK version, not the PyPI package.
maxConcurrentImageProcessingOps: int
Maximum 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: float
Time window for track triggering (default: 3.0 seconds).
maxIdleTimeInSec: float
Maximum idle time before track closure (default: 3.5 seconds).
minTriggerFrameCount: int
Minimum detections needed to trigger track (default: 3).
thumbnailWidth: int
Target thumbnail width in pixels (default: 256, -1 for uncapped).
thumbnailHeight: int
Target 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.