### Install Dynamsoft Capture Vision Bundle Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/README.md Use pip or pip3 to install the Dynamsoft Capture Vision bundle for Python. ```bash pip install dynamsoft-capture-vision-bundle ``` ```bash pip3 install dynamsoft-capture-vision-bundle ``` -------------------------------- ### Initialize License with Public Trial Key Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Initialize the SDK license using a public trial key. This is a required step before any processing can occur. Ensure network access for the trial key. Handle potential errors during initialization. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode # Public trial key – requires internet access. # Replace with your own key for production or offline use. error_code, error_message = LicenseManager.init_license( "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" ) if error_code not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING): raise RuntimeError( f"License initialization failed – code: {error_code}, msg: {error_message}" ) # EC_LICENSE_WARNING is non-fatal (e.g. trial about to expire); log and continue. if error_code == EnumErrorCode.EC_LICENSE_WARNING: print(f"License warning: {error_message}") ``` -------------------------------- ### CaptureVisionRouter.init_settings_from_file Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Loads a custom JSON template to configure the router. This allows for custom barcode formats, image-processing stages, and more. Must be called before `capture_multi_pages` if using a custom template name. ```APIDOC ## CaptureVisionRouter.init_settings_from_file – Load a custom JSON template Replaces the router's built-in settings with a JSON template file that defines custom barcode formats, image-processing stages, semantic parsing tasks, and ROI definitions. Must be called before `capture_multi_pages` when a custom template name is used. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode from pathlib import Path cvr = CaptureVisionRouter() template_path = Path("CustomTemplates/ReadGS1AIBarcode.json") error_code, error_msg = cvr.init_settings_from_file(str(template_path)) if error_code != EnumErrorCode.EC_OK: raise RuntimeError(f"Failed to load template: {error_msg}") # The router now recognises the "ReadGS1AIBarcode" template name. ``` ``` -------------------------------- ### Initialize License for Dynamsoft Capture Vision Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/README.md Initialize the Dynamsoft Capture Vision SDK with a license key. A free public trial license requires network connection, while a requested trial license works offline. ```python from dcv_sdk.core.license_manager import LicenseManager # Use a free public trial license (requires network connection) LicenseManager.init_license("DLS20220101") # Or use a 30-day free trial license (works offline) # LicenseManager.init_license("YOUR_30_DAY_TRIAL_LICENSE") ``` -------------------------------- ### LicenseManager.init_license Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Initializes the DCV runtime license. This must be called before creating a CaptureVisionRouter. A free trial key is provided, but a production key is recommended for long-term use. ```APIDOC ## LicenseManager.init_license – Activate the SDK with a license key Initializes the DCV runtime license before any processing can occur. The call must succeed (or return only a warning) before a `CaptureVisionRouter` is created. A free public trial key that requires network access is bundled with every sample; offline 30-day keys are available from the Dynamsoft portal. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode # Public trial key – requires internet access. # Replace with your own key for production or offline use. error_code, error_message = LicenseManager.init_license( "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" ) if error_code not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING): raise RuntimeError( f"License initialization failed – code: {error_code}, msg: {error_message}" ) # EC_LICENSE_WARNING is non-fatal (e.g. trial about to expire); log and continue. if error_code == EnumErrorCode.EC_LICENSE_WARNING: print(f"License warning: {error_message}") ``` ``` -------------------------------- ### Create CaptureVisionRouter Instance Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Instantiate the `CaptureVisionRouter`, which serves as the central engine for all image analysis tasks. No further configuration is needed for built-in templates. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter cvr = CaptureVisionRouter() # The router is now ready – no further configuration is required for built-in templates. ``` -------------------------------- ### Load Custom Template from JSON File Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Load custom settings from a JSON template file into the `CaptureVisionRouter`. This allows for custom barcode formats, image processing stages, and more. Must be called before using a custom template name in `capture_multi_pages`. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode from pathlib import Path cvr = CaptureVisionRouter() template_path = Path("CustomTemplates/ReadGS1AIBarcode.json") error_code, error_msg = cvr.init_settings_from_file(str(template_path)) if error_code != EnumErrorCode.EC_OK: raise RuntimeError(f"Failed to load template: {error_msg}") # The router now recognises the "ReadGS1AIBarcode" template name. ``` -------------------------------- ### Detect and Normalize Document Image Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Uses the PT_DETECT_AND_NORMALIZE_DOCUMENT preset to find, deskew, and save a normalized document image. Ensure the license is initialized before use. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, EnumPresetTemplate, FileImageTag, ImageIO ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() result_array = cvr.capture_multi_pages( "Images/document-sample.jpg", EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) image_io = ImageIO() for i, result in enumerate(result_array.get_results()): tag = result.get_original_image_tag() page_number = tag.get_page_number() + 1 if isinstance(tag, FileImageTag) else i + 1 if result.get_error_code() not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_UNSUPPORTED_JSON_KEY_WARNING): print(f"Page {page_number} error:", result.get_error_string()) continue processed = result.get_processed_document_result() if processed is None or not processed.get_enhanced_image_result_items(): print(f"Page {page_number}: no document found") continue for idx, item in enumerate(processed.get_enhanced_image_result_items()): out_path = f"Page_{page_number}_enhanced_{idx}.png" image_data = item.get_image_data() if image_data: err, msg = image_io.save_to_file(image_data, out_path) if err == 0: print(f"Saved: {out_path}") else: print(f"Save failed: {err} – {msg}") # Expected output: # Saved: Page_1_enhanced_0.png ``` -------------------------------- ### Process Image File with CaptureVisionRouter Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Process an image or PDF file using the `CaptureVisionRouter`. This function runs the entire DCV pipeline and returns a `CapturedResultArray` containing per-page results. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, EnumPresetTemplate, FileImageTag ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() ``` -------------------------------- ### Save ImageData to File using ImageIO Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Persists an ImageData object to a file. The output format is determined by the file extension (e.g., PNG, JPEG, BMP). Ensure the output path is correctly specified. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, EnumPresetTemplate, ImageIO ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() image_io = ImageIO() result_array = cvr.capture_multi_pages( "Images/document-sample.jpg", EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) for i, result in enumerate(result_array.get_results()): processed = result.get_processed_document_result() if processed is None: continue for j, item in enumerate(processed.get_enhanced_image_result_items()): image_data = item.get_image_data() if image_data is None: continue out_path = f"enhanced_doc_p{i+1}_{j}.png" # PNG, JPEG, BMP all supported error_code, error_msg = image_io.save_to_file(image_data, out_path) if error_code == 0: print(f"Saved {out_path}") else: print(f"Save failed ({error_code}): {error_msg}") ``` -------------------------------- ### CaptureVisionRouter.capture_multi_pages Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Processes an image or PDF file through the full DCV pipeline. It returns a `CapturedResultArray` containing results for each page. ```APIDOC ## CaptureVisionRouter.capture_multi_pages – Process an image file Runs the full DCV pipeline (region pre-detection → localization → decoding/recognition → semantic parsing) on every page of the supplied image or PDF. Returns a `CapturedResultArray`; iterate its `.get_results()` list to inspect per-page output. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, EnumPresetTemplate, FileImageTag ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() ``` -------------------------------- ### Read GS1 AI Barcodes from Image Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Reads GS1 AI barcodes from an image file and prints the parsed AI, code, and value. Ensure the 'ReadGS1AIBarcode' template is configured. ```python result_array = cvr.capture_multi_pages( "Images/gs1-ai-sample.png", "ReadGS1AIBarcode" ) for i, result in enumerate(result_array.get_results()): if result.get_error_code() not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_UNSUPPORTED_JSON_KEY_WARNING): print("Error:", result.get_error_string()) continue parsed = result.get_raw_passed_result().get_parsed_result() if not parsed or not parsed.get_items(): print(f"Page {i+1}: no GS1 AIs found") continue for item in parsed.get_items(): for key, ai_code, value in parse_gs1_result(item): print(f"AI: {key} ({ai_code}), Value: {value}") ``` -------------------------------- ### CaptureVisionRouter Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt The central processing engine for all image-analysis tasks. A single instance can be reused across multiple images and template names. ```APIDOC ## CaptureVisionRouter – Central processing engine `CaptureVisionRouter` is the single entry point for all image-analysis tasks. After construction it is ready to use with any built-in template. One router instance can be reused across multiple images and multiple template names. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter cvr = CaptureVisionRouter() # The router is now ready – no further configuration is required for built-in templates. ``` ``` -------------------------------- ### ImageIO.save_to_file Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Persists an ImageData object to disk. The output format is inferred from the file extension. Supported formats include PNG, JPEG, and BMP. ```APIDOC ## ImageIO.save_to_file ### Description Persists an `ImageData` object to disk. The output format is inferred from the file extension. ### Method `save_to_file(image_data: ImageData, out_path: str) -> Tuple[int, str]` ### Parameters #### Path Parameters - **image_data** (ImageData) - Required - The image data object to save. - **out_path** (str) - Required - The file path to save the image to. The extension determines the format (e.g., .png, .jpg, .bmp). ### Return Value A tuple containing: - **error_code** (int) - 0 if successful, non-zero otherwise. - **error_msg** (str) - A message describing the error if an error occurred. ``` -------------------------------- ### Read Passport and ID Information Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Processes passport and ID images to extract information. Ensure the 'ReadPassportAndId' template is available. Handles potential errors during parsing and saves a portrait crop for passports. ```python LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() irr = MyIRReceiver() irm = cvr.get_intermediate_result_manager() irm.add_result_receiver(irr) result_array = cvr.capture_multi_pages( "Images/passport-sample.jpg", "ReadPassportAndId" ) image_io = ImageIO() img_proc = ImageProcessor() for i, result in enumerate(result_array.get_results()): if result.get_error_code() not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_UNSUPPORTED_JSON_KEY_WARNING): print("Error:", result.get_error_string()) continue parsed = result.get_parsed_result() if not parsed or not parsed.get_items(): print("No MRZ found.") continue hash_id = result.get_original_image_hash_id() is_passport = False for item in parsed.get_items(): code_type = item.get_code_type() is_passport = (code_type == "MRTD_TD3_PASSPORT") def field(name): v = item.get_field_value(name) s = item.get_field_validation_status(name) return v if v and s != EnumValidationStatus.VS_FAILED else None print(f"Type: {code_type}") print(f"Surname: {field('primaryIdentifier')}") print(f"Given name: {field('secondaryIdentifier')}") print(f"Nationality: {field('nationality')}") print(f"DOB: {field('dateOfBirth')}") print(f"Expiry: {field('dateOfExpiry')}") print(f"Line 1: {field('line1')}") print(f"Line 2: {field('line2')}") # Save portrait crop for passports if is_passport: original_image = next( (it.get_image_data() for it in result.get_items() if isinstance(it, OriginalImageResultItem)), None ) quad = irr.get_portrait_quad(hash_id) if quad and original_image: ret, portrait = img_proc.crop_and_deskew_image(original_image, quad) if ret == EnumErrorCode.EC_OK: err, msg = image_io.save_to_file(portrait, f"portrait_page{i+1}.png") print(f"Portrait saved: portrait_page{i+1}.png" if err == 0 else f"Save failed: {msg}") ``` -------------------------------- ### Define Custom Capture Pipeline with JSON Template Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Defines a custom capture pipeline named 'ReadGS1AIBarcode' using a JSON template. This template configures various task settings for barcode reading and semantic processing. ```json { "CaptureVisionTemplates": [ { "Name": "ReadGS1AIBarcode", "ImageROIProcessingNameArray": ["roi_gs1_ai_barcode"], "SemanticProcessingNameArray": ["sp_gs1_ai"] } ], "BarcodeReaderTaskSettingOptions": [ { "Name": "task_gs1_ai_barcode", "ExpectedBarcodesCount": 1, "BarcodeFormatIds": ["BF_GS1_DATABAR", "BF_CODE_128", "BF_GS1_COMPOSITE"], "BarcodeFormatSpecificationNameArray": ["bfs_gs1_ai"] } ], "BarcodeFormatSpecificationOptions": [ { "Name": "bfs_gs1_ai", "BarcodeFormatIds": ["BF_GS1_DATABAR", "BF_CODE_128", "BF_GS1_COMPOSITE"], "IncludeTrailingCheckDigit": 0, "IncludeImpliedAI01": 1 } ], "CodeParserTaskSettingOptions": [ { "Name": "dcp_gs1_ai", "CodeSpecifications": ["GS1_AI"] } ], "SemanticProcessingOptions": [ { "Name": "sp_gs1_ai", "ReferenceObjectFilter": { "ReferenceTargetROIDefNameArray": ["roi_gs1_ai_barcode"] }, "TaskSettingNameArray": ["dcp_gs1_ai"] } ], "TargetROIDefOptions": [ { "Name": "roi_gs1_ai_barcode", "TaskSettingNameArray": ["task_gs1_ai_barcode"] } ] } ``` -------------------------------- ### MRZ Scanner with Intermediate Result Receiver Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt This snippet demonstrates how to use the `ReadPassportAndId` preset to scan MRZ zones on travel documents. It also shows the `IntermediateResultReceiver` pattern for capturing and processing intermediate frames, which is crucial for tasks like portrait extraction. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, IntermediateResultReceiver, IntermediateResultExtraInfo, DeskewedImageUnit, LocalizedTextLinesUnit, ScaledColourImageUnit, RecognizedTextLinesUnit, DetectedQuadsUnit, ParsedResultItem, EnumValidationStatus, FileImageTag, IdentityProcessor, ImageProcessor, ImageIO, Quadrilateral, OriginalImageResultItem ) # ── Intermediate result collection ────────────────────────────────────────── class MyIRReceiver(IntermediateResultReceiver): def __init__(self): super().__init__() self._groups = {} # hash_id → dict of units def _group(self, hash_id): if hash_id not in self._groups: self._groups[hash_id] = {} return self._groups[hash_id] def on_deskewed_image_received(self, result: DeskewedImageUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: self._group(result.get_original_image_hash_id())["deskewed"] = result def on_localized_text_lines_received(self, result: LocalizedTextLinesUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: self._group(result.get_original_image_hash_id())["localized_lines"] = result def on_scaled_colour_image_unit_received(self, result: ScaledColourImageUnit, info: IntermediateResultExtraInfo): self._group(result.get_original_image_hash_id())["scaled_colour"] = result def on_recognized_text_lines_received(self, result: RecognizedTextLinesUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: self._group(result.get_original_image_hash_id())["recognized_lines"] = result def on_detected_quads_received(self, result: DetectedQuadsUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: self._group(result.get_original_image_hash_id())["quads"] = result def get_portrait_quad(self, hash_id: str): g = self._groups.get(hash_id, {}) id_proc = IdentityProcessor() ret, quad = id_proc.find_portrait_zone( g.get("scaled_colour"), g.get("localized_lines"), g.get("recognized_lines"), g.get("quads"), g.get("deskewed") ) return quad if ret == EnumErrorCode.EC_OK else None ``` -------------------------------- ### Parse Driver License Barcodes Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Uses the "ReadDriversLicense" preset to decode AAMVA barcodes from driver licenses. It extracts and validates fields using helper functions. Ensure the license is initialized. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, EnumValidationStatus, ParsedResultItem, FileImageTag ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() result_array = cvr.capture_multi_pages( "Images/driver-license-sample.jpg", "ReadDriversLicense" ) def extract_dl_field(item: ParsedResultItem, *field_names): """Return the first validated field value from a list of candidate names.""" for name in field_names: value = item.get_field_value(name) status = item.get_field_validation_status(name) if value is not None and status != EnumValidationStatus.VS_FAILED: return value return None for i, result in enumerate(result_array.get_results()): if result.get_error_code() not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_UNSUPPORTED_JSON_KEY_WARNING): print("Error:", result.get_error_string()) continue parsed = result.get_parsed_result() if parsed is None or not parsed.get_items(): print("No driver license found.") continue for item in parsed.get_items(): license_number = extract_dl_field(item, "licenseNumber") last_name = extract_dl_field(item, "lastName", "surName") given_name = extract_dl_field(item, "givenName") gender = extract_dl_field(item, "sex", "gender") birth_date = extract_dl_field(item, "birthDate") expiration_date = extract_dl_field(item, "expirationDate") vehicle_class = extract_dl_field(item, "vehicleClass") print(f"License #: {license_number}") print(f"Name: {last_name}, {given_name}") print(f"Gender: {gender}") print(f"DOB: {birth_date}") print(f"Expires: {expiration_date}") print(f"Class: {vehicle_class}") # Expected output: # License #: S99900589 # Name: SAMPLE, ALEXANDER ``` -------------------------------- ### Parse GS1 AI Barcode Data Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Parses GS1 Application Identifiers from barcodes using a custom JSON template. Requires 'ReadGS1AIBarcode.json' in 'CustomTemplates/'. Helper functions group fields and identify AI tokens. ```python import re from collections import defaultdict from pathlib import Path from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode, ParsedResultItem, FileImageTag ) def group_by_first_layer(names): grouped = defaultdict(list) for name in names: grouped[name.split('.')[0]].append(name) return grouped def is_ai(token): return re.fullmatch(r"\d+|(\d+n)", token) is not None def parse_gs1_result(item: ParsedResultItem): grouped = group_by_first_layer(item.get_all_field_names()) entries = [] for key, fields in grouped.items(): if not is_ai(key): continue ai = data = None for f in fields: last = f.split('.')[-1] if last == key + 'AI': ai = item.get_field_value(f) elif last == key + 'Data': data = item.get_field_value(f) entries.append((key, ai, data)) return entries # ── Setup ──────────────────────────────────────────────────────────────────── LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() template_path = Path("CustomTemplates/ReadGS1AIBarcode.json") err, msg = cvr.init_settings_from_file(str(template_path)) if err != EnumErrorCode.EC_OK: raise RuntimeError(f"Template load failed: {msg}") ``` -------------------------------- ### Intercept Intermediate Results with Custom Receiver Source: https://context7.com/dynamsoft/capture-vision-python-samples/llms.txt Subclass `IntermediateResultReceiver` to capture and process intermediate image frames and geometry data during the capture pipeline. This is useful for debugging or advanced image analysis. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, IntermediateResultReceiver, IntermediateResultExtraInfo, ScaledColourImageUnit, LicenseManager, EnumErrorCode ) class DebugReceiver(IntermediateResultReceiver): def __init__(self): super().__init__() self.frames = [] def on_scaled_colour_image_unit_received( self, result: ScaledColourImageUnit, info: IntermediateResultExtraInfo ): img = result.get_image_data() self.frames.append(img) print(f"Captured intermediate frame: {img.get_width()}×{img.get_height()} px") LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() receiver = DebugReceiver() irm = cvr.get_intermediate_result_manager() irm.add_result_receiver(receiver) cvr.capture_multi_pages("Images/passport-sample.jpg", "ReadPassportAndId") print(f"Total intermediate frames captured: {len(receiver.frames)}") # Remove receiver when no longer needed irm.remove_result_receiver(receiver) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.