### Install Dynamsoft Capture Vision Bundle Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/README.md Use pip to install the required package for the Python SDK. ```bash pip install dynamsoft-capture-vision-bundle ``` ```bash pip3 install dynamsoft-capture-vision-bundle ``` -------------------------------- ### Initialize and Process Images Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/quick-start.md A minimal example showing license initialization, router creation, and basic image processing. ```python from dynamsoft_capture_vision_bundle import ( LicenseManager, CaptureVisionRouter, EnumErrorCode ) # Step 1: Initialize license error_code, error_msg = LicenseManager.init_license( "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" ) if error_code != EnumErrorCode.EC_OK and error_code != EnumErrorCode.EC_LICENSE_WARNING: print(f"License error: {error_msg}") exit(1) # Step 2: Create router cvr = CaptureVisionRouter() # Step 3: Process image result_array = cvr.capture_multi_pages( "document.jpg", "PT_DETECT_AND_NORMALIZE_DOCUMENT" ) # Step 4: Extract results results = result_array.get_results() if results: for result in results: if result.get_error_code() == EnumErrorCode.EC_OK: print("Processing successful") else: print(f"Error: {result.get_error_string()}") ``` -------------------------------- ### Public Trial License Key Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Example of a public trial license key string. ```text DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9 ``` -------------------------------- ### Initialize Settings from File Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Load custom template definitions from a JSON configuration file. ```python init_settings_from_file(file_path: str) -> tuple[int, str] ``` ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() template_path = "CustomTemplates/ReadGS1AIBarcode.json" error_code, error_msg = cvr.init_settings_from_file(template_path) if error_code != EnumErrorCode.EC_OK: raise Exception(f"Init template failed: {error_msg}") # Now use the custom template in capture operations result_array = cvr.capture_multi_pages("image.png", "ReadGS1AIBarcode") ``` -------------------------------- ### Get All ParsedResultItem Field Names Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Retrieves a list of all available field names for the parsed item. ```python get_all_field_names() -> list[str] ``` ```python field_names = item.get_all_field_names() print(f"Available fields: {', '.join(field_names)}") # Extract all fields data = {} for field_name in field_names: value = item.get_field_value(field_name) if value is not None: data[field_name] = value ``` -------------------------------- ### Initialize License with Basic Handling Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/license-management.md Demonstrates standard license initialization and checking for success or warning status. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode # Initialize with a public trial license error_code, error_message = LicenseManager.init_license( "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" ) if error_code == EnumErrorCode.EC_OK: print("License initialized successfully") elif error_code == EnumErrorCode.EC_LICENSE_WARNING: print(f"License initialized with warning: {error_message}") else: print(f"License initialization failed: {error_message}") ``` -------------------------------- ### Manage resource initialization and cleanup in Python Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Use try-finally blocks to ensure license initialization is verified before proceeding with router operations. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, LicenseManager, EnumErrorCode ) try: # Initialize error_code, msg = LicenseManager.init_license("LICENSE_KEY") if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: raise Exception(f"License init failed: {msg}") cvr = CaptureVisionRouter() # Use the router results = cvr.capture_multi_pages("image.jpg", "ReadPassportAndId").get_results() finally: # Cleanup happens automatically when objects are garbage collected pass ``` -------------------------------- ### Get ParsedResultItem Code Type Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Returns the document or entity type parsed, such as AAMVA_DL_ID or MRTD_TD3_PASSPORT. ```python get_code_type() -> str ``` ```python for item in parsed_result.get_items(): doc_type = item.get_code_type() if doc_type == "AAMVA_DL_ID": # Process driver's license license_num = item.get_field_value("licenseNumber") elif doc_type == "MRTD_TD3_PASSPORT": # Process passport passport_num = item.get_field_value("passportNumber") ``` -------------------------------- ### Get ParsedResult Original Image Tag Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Retrieves the image tag associated with the parsed result. ```python get_original_image_tag() -> FileImageTag | None ``` -------------------------------- ### Initialize License with Error Handling Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/license-management.md Shows how to terminate the application if license initialization fails. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode import sys error_code, error_message = LicenseManager.init_license("YOUR_LICENSE_KEY") if error_code != EnumErrorCode.EC_OK and error_code != EnumErrorCode.EC_LICENSE_WARNING: print(f"License initialization failed: ErrorCode: {error_code}, ErrorString: {error_message}") sys.exit(1) else: print("SDK is ready to use") ``` -------------------------------- ### Get ParsedResult Error String Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Returns the error message associated with the parsed data extraction. ```python get_error_string() -> str ``` -------------------------------- ### Initialize Configuration from File Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Load settings from a JSON file before initiating image processing. Ensure the error code is checked to confirm successful initialization. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() # Load configuration error_code, msg = cvr.init_settings_from_file("template.json") if error_code != EnumErrorCode.EC_OK: print(f"Configuration error: {msg}") sys.exit(1) # Now process images result_array = cvr.capture_multi_pages("image.jpg", "TemplateName") ``` -------------------------------- ### Get ParsedResult Error Code Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Returns the error status for the parsed data extraction process. ```python get_error_code() -> int ``` -------------------------------- ### Initialize SDK License Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/README.md Initializes the SDK using a license key and checks for success or warnings. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, msg = LicenseManager.init_license("LICENSE_KEY") if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: print(f"License error: {msg}") exit(1) ``` -------------------------------- ### Get Original Image Hash ID Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Use get_original_image_hash_id to correlate results with intermediate data. ```python get_original_image_hash_id() -> str ``` ```python hash_id = result.get_original_image_hash_id() # Use hash_id to retrieve intermediate results from IntermediateResultReceiver portrait = intermediate_receiver.get_portrait_zone(hash_id) ``` -------------------------------- ### init_settings_from_file(file_path) Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Initializes capture settings from a JSON configuration file. ```APIDOC ## init_settings_from_file(file_path: str) ### Description Initializes capture settings from a JSON configuration file. Allows loading custom template definitions. ### Parameters - **file_path** (str) - Required - Full path to a JSON settings file containing template definitions and processing parameters. ### Return Type tuple[int, str] - Index 0 (int): Error code (0 for success), Index 1 (str): Error message. ``` -------------------------------- ### Initialize License with LicenseManager Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/INDEX.md Use this to initialize the SDK with a valid license key before performing any capture operations. ```python error_code, msg = LicenseManager.init_license("LICENSE_KEY") ``` -------------------------------- ### Get ParsedResultItem Field Validation Status Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Checks the validation status of a specific field using EnumValidationStatus. ```python get_field_validation_status(field_name: str) -> int ``` ```python from dynamsoft_capture_vision_bundle import EnumValidationStatus license_number = item.get_field_value("licenseNumber") status = item.get_field_validation_status("licenseNumber") if license_number is not None and status != EnumValidationStatus.VS_FAILED: print(f"Valid license: {license_number}") else: print("License validation failed") ``` -------------------------------- ### Get ParsedResult Items Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Retrieves all parsed result items. Use this to iterate through entities extracted from an image. ```python get_items() -> list[ParsedResultItem] ``` ```python parsed_result = result.get_parsed_result() if parsed_result.get_error_code() != 0: print(f"Parse error: {parsed_result.get_error_string()}") else: items = parsed_result.get_items() print(f"Parsed {len(items)} items") for item in items: code_type = item.get_code_type() print(f"Item type: {code_type}") ``` -------------------------------- ### Initialize License Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Initialize the license key once at application startup before performing any other operations. ```python from dynamsoft_capture_vision_bundle import LicenseManager # Do this before any other operations LicenseManager.init_license("YOUR_LICENSE_KEY") ``` -------------------------------- ### Get ParsedResultItem Field Value Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Retrieves the value for a specific field name. Returns None if the field is not found. ```python get_field_value(field_name: str) -> Any ``` ```python license_number = item.get_field_value("licenseNumber") if license_number is not None: print(f"License: {license_number}") full_name = item.get_field_value("fullName") if full_name is not None: print(f"Name: {full_name}") ``` -------------------------------- ### Implement License Initialization Pattern Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Standard pattern for initializing the license early in the application startup sequence before creating the CaptureVisionRouter. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode import sys # Initialize license early in application startup error_code, error_message = LicenseManager.init_license( "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" ) if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: print(f"License initialization failed: {error_message}") sys.exit(1) print("License initialized successfully") # Now create router and process images from dynamsoft_capture_vision_bundle import CaptureVisionRouter cvr = CaptureVisionRouter() result_array = cvr.capture_multi_pages("image.jpg", "ReadPassportAndId") ``` -------------------------------- ### Initialize CaptureVisionRouter Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Instantiate the router to begin vision capture operations. ```python CaptureVisionRouter() ``` ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter # Create router instance cvr = CaptureVisionRouter() ``` -------------------------------- ### LicenseManager.init_license() Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/license-management.md Initializes the Dynamsoft Capture Vision SDK with a provided license key. This method must be called before creating any other SDK instances. ```APIDOC ## LicenseManager.init_license(license_key: str) ### Description Initializes the Dynamsoft Capture Vision SDK with a license key. This must be called before any other SDK instances are created. ### Parameters - **license_key** (str) - Required - The license key string (public trial or commercial). ### Return Type - **tuple[int, str]** - A tuple containing an error code (int) and an error message (str). ### Errors - **EnumErrorCode.EC_OK**: Success. - **EnumErrorCode.EC_LICENSE_WARNING**: Initialized with warning; SDK is still usable. - **Other**: Initialization failed. ### Example ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, error_message = LicenseManager.init_license("YOUR_LICENSE_KEY") if error_code == EnumErrorCode.EC_OK: print("License initialized successfully") ``` ``` -------------------------------- ### Initialize License Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Verify license initialization status to prevent operation failures. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, msg = LicenseManager.init_license("LICENSE_KEY") if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: raise Exception(f"Cannot proceed without valid license: {msg}") ``` -------------------------------- ### LicenseManager.init_license Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/README.md Initializes the license for the SDK. ```APIDOC ## LicenseManager.init_license() ### Description Initializes the license required to use the SDK features. ### Returns - **(int, str)** - Returns a tuple containing an error code and an error message string. ``` -------------------------------- ### Initialize License Key Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Initializes the license key using the LicenseManager. Check the error code to ensure the license is ready for use. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, error_message = LicenseManager.init_license("LICENSE_KEY_STRING") if error_code == EnumErrorCode.EC_OK: print("License ready") elif error_code == EnumErrorCode.EC_LICENSE_WARNING: print("License warning (but usable):", error_message) else: print("License error:", error_message) sys.exit(1) ``` -------------------------------- ### Load Configuration File in Python Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Initializes the CaptureVisionRouter with a JSON template file. Check the error code to ensure the file was loaded successfully. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() error_code, error_msg = cvr.init_settings_from_file("path/to/template.json") if error_code != EnumErrorCode.EC_OK: raise Exception(f"Failed to load template: {error_msg}") ``` -------------------------------- ### Handle License Initialization Errors Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Check the return value of LicenseManager.init_license to distinguish between successful initialization, warnings, and critical failures. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, error_message = LicenseManager.init_license("LICENSE_KEY") if error_code == EnumErrorCode.EC_OK: print("License initialized successfully") elif error_code == EnumErrorCode.EC_LICENSE_WARNING: print(f"License warning (but usable): {error_message}") else: print(f"License initialization failed: {error_message}") sys.exit(1) ``` -------------------------------- ### Load Custom Templates Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Load all custom configuration templates during application startup to ensure they are available for the lifecycle of the application. ```python cvr = CaptureVisionRouter() # Load all custom templates at startup for template_file in ["template1.json", "template2.json"]: error_code, msg = cvr.init_settings_from_file(template_file) if error_code != 0: print(f"Failed to load {template_file}: {msg}") # Then use templates throughout application lifecycle ``` -------------------------------- ### Standard SDK Usage Pattern Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/INDEX.md Template for importing classes and executing methods within the SDK. ```python # Format: actual working code from dynamsoft_capture_vision_bundle import ClassName obj = ClassName() result = obj.method() ``` -------------------------------- ### Switch Templates Sequentially Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Reuse the same router instance to process images with different templates by calling the capture method multiple times. ```python # Process with first template result_array_1 = cvr.capture_multi_pages("image.jpg", "Template1") # Process same or different image with different template result_array_2 = cvr.capture_multi_pages("image.jpg", "Template2") ``` -------------------------------- ### Extract and Crop Image using Quadrilateral Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md Demonstrates obtaining a quadrilateral from portrait detection and using it to crop and deskew an image. ```python from dynamsoft_capture_vision_bundle import IdentityProcessor, ImageProcessor # Get quadrilateral from portrait detection identity_processor = IdentityProcessor() error_code, portrait_quad = identity_processor.find_portrait_zone( scaled_image, localized_text, recognized_text, quads, deskewed ) if error_code == 0 and portrait_quad is not None: # Use quadrilateral to crop image image_processor = ImageProcessor() crop_error, cropped = image_processor.crop_and_deskew_image( original_image, portrait_quad ) ``` -------------------------------- ### Implement complete error handling template Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/quick-start.md A comprehensive template covering license initialization, file validation, processing checks, and field-level data validation. ```python from dynamsoft_capture_vision_bundle import ( LicenseManager, CaptureVisionRouter, EnumErrorCode, EnumValidationStatus ) import os import sys try: # Initialize license error_code, error_msg = LicenseManager.init_license("LICENSE_KEY") if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: print(f"License error: {error_msg}") sys.exit(1) # Create router cvr = CaptureVisionRouter() # Check file image_path = "image.jpg" if not os.path.exists(image_path): print(f"File not found: {image_path}") sys.exit(1) # Process result_array = cvr.capture_multi_pages(image_path, "ReadPassportAndId") results = result_array.get_results() if results is None or len(results) == 0: print("No results") sys.exit(1) # Extract for result in results: if result.get_error_code() != EnumErrorCode.EC_OK: print(f"Processing error: {result.get_error_string()}") continue parsed = result.get_parsed_result() if parsed is None or len(parsed.get_items()) == 0: print("No parsed data") continue for item in parsed.get_items(): field_value = item.get_field_value("passportNumber") validation = item.get_field_validation_status("passportNumber") if field_value is None: print("Field not found") elif validation == EnumValidationStatus.VS_FAILED: print(f"Field validation failed: {field_value}") else: print(f"Valid data: {field_value}") except Exception as e: print(f"Exception: {e}") sys.exit(1) ``` -------------------------------- ### Quadrilateral Usage Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md Demonstrates how to obtain a Quadrilateral object from the IdentityProcessor and use it with the ImageProcessor to crop and deskew an image. ```APIDOC ## SDK Method: dynamsoft_capture_vision_bundle.Quadrilateral ### Description Represents a four-sided polygon with corners. It is primarily used to define regions for image processing tasks like cropping and deskewing. ### Usage - Obtained via: `IdentityProcessor.find_portrait_zone()` - Used with: `ImageProcessor.crop_and_deskew_image()` ### Example ```python from dynamsoft_capture_vision_bundle import IdentityProcessor, ImageProcessor # Get quadrilateral from portrait detection identity_processor = IdentityProcessor() error_code, portrait_quad = identity_processor.find_portrait_zone( scaled_image, localized_text, recognized_text, quads, deskewed ) if error_code == 0 and portrait_quad is not None: # Use quadrilateral to crop image image_processor = ImageProcessor() crop_error, cropped = image_processor.crop_and_deskew_image( original_image, portrait_quad ) ``` ``` -------------------------------- ### Load Templates with Error Handling Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/sample-patterns.md Initializes settings from a JSON file and validates the operation using EnumErrorCode. Provides a mechanism for fallback or exception handling if loading fails. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() # Try to load custom template template_path = "CustomTemplates/ReadGS1AIBarcode.json" error_code, error_msg = cvr.init_settings_from_file(template_path) if error_code != EnumErrorCode.EC_OK: print(f"Failed to load template: {error_msg}") # Try fallback or exit raise Exception("Init template failed: " + error_msg) # Now use the template result_array = cvr.capture_multi_pages(image_path, "ReadGS1AIBarcode") ``` -------------------------------- ### Interactive File Input Loop in Python Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/sample-patterns.md Prompts the user for a file path, providing a default sample image if the input is empty and allowing for graceful exit. ```python from pathlib import Path import os import sys BASE_DIR = Path(__file__).resolve().parent while True: image_path = input( ">> Input your image full path:\n" ">> 'Enter' for sample image or 'Q'/'q' to quit\n" ).strip(' \'"') if image_path.lower() == "q": sys.exit(0) if image_path == "": # Use default sample image image_path = str(BASE_DIR.parent / "Images" / "document-sample.jpg") if not os.path.exists(image_path): print("The image path does not exist.") continue # Process image here break ``` -------------------------------- ### Use EnumPresetTemplate in CaptureVisionRouter Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/types.md Demonstrates applying a preset template when calling the capture_multi_pages method. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumPresetTemplate cvr = CaptureVisionRouter() # Use preset template result_array = cvr.capture_multi_pages( "document.jpg", EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) ``` -------------------------------- ### CaptureVisionRouter() Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Constructor to create a new instance of the Capture Vision Router. ```APIDOC ## CaptureVisionRouter() ### Description Creates a new instance of the Capture Vision Router. ### Parameters None ``` -------------------------------- ### Define Image Scale Settings Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Configure image scaling parameters within the JSON configuration file. ```json { "ImageScaleSetting": { "ScaleType": "ST_SCALE_DOWN", "ReferenceEdge": "RE_SHORTER_EDGE", "EdgeLengthThreshold": 99999 } } ``` -------------------------------- ### Handle Template Errors Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Manage template loading by using string names, preset templates, or custom JSON configuration files. ```python from dynamsoft_capture_vision_bundle import EnumErrorCode # Try string name result_array = cvr.capture_multi_pages(image_path, "ReadPassportAndId") # Or use preset template from dynamsoft_capture_vision_bundle import EnumPresetTemplate result_array = cvr.capture_multi_pages( image_path, EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) # Or load custom template error_code, msg = cvr.init_settings_from_file("custom_template.json") if error_code == EnumErrorCode.EC_OK: result_array = cvr.capture_multi_pages(image_path, "CustomTemplate") ``` -------------------------------- ### ImageProcessor.crop_and_deskew_image() Signature Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md The method signature for cropping and deskewing an image. ```python crop_and_deskew_image( image: ImageData, quad: Quadrilateral ) -> tuple[int, ImageData] ``` -------------------------------- ### Handle Template Loading Errors Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Validate template loading by checking the error code returned by init_settings_from_file and raising an exception on failure. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() error_code, error_msg = cvr.init_settings_from_file("template.json") if error_code != EnumErrorCode.EC_OK: raise Exception(f"Failed to load template: {error_msg}") ``` -------------------------------- ### Define Image Parameters Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Sets image preprocessing modes such as binarization for specific stages. ```json { "ImageParameterOptions": [ { "Name": "ip_binarize", "ApplicableStages": [ { "Stage": "SST_BINARIZE_IMAGE", "BinarizationModes": [ {"Mode": "BM_LOCAL_BLOCK"} ] } ] } ] } ``` -------------------------------- ### Retrieve and Save ImageData from Capture Results Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md Demonstrates extracting original and enhanced images from capture results and saving them to disk using ImageIO. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, OriginalImageResultItem, ImageIO ) cvr = CaptureVisionRouter() result_array = cvr.capture_multi_pages("image.jpg", "ReadPassportAndId") results = result_array.get_results() if results: for result in results: # Get original image for item in result.get_items(): if isinstance(item, OriginalImageResultItem): original_image = item.get_image_data() if original_image: # Save original image_io = ImageIO() error_code, msg = image_io.save_to_file(original_image, "original.png") # Or process enhanced document images proc_result = result.get_processed_document_result() if proc_result: enhanced_items = proc_result.get_enhanced_image_result_items() for idx, enhanced_item in enumerate(enhanced_items): enhanced_image = enhanced_item.get_image_data() if enhanced_image: error_code, msg = image_io.save_to_file( enhanced_image, f"enhanced_{idx}.png" ) ``` -------------------------------- ### Implement on_scaled_colour_image_unit_received callback Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/intermediate-results.md Override this method to handle scaled color image units. ```python def on_scaled_colour_image_unit_received(self, result: ScaledColourImageUnit, info: IntermediateResultExtraInfo): print("Scaled color image available") hash_id = result.get_original_image_hash_id() ``` -------------------------------- ### Check Error Codes Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Validate error codes after initialization to ensure the SDK is ready for use. ```python from dynamsoft_capture_vision_bundle import LicenseManager, EnumErrorCode error_code, msg = LicenseManager.init_license("KEY") if error_code not in [EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_WARNING]: raise Exception(f"Cannot proceed: {msg}") ``` -------------------------------- ### Capture Multi-Page Documents Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Process images using specific templates. Ensure the file path is valid before calling. ```python capture_multi_pages(file_path: str, template_name: str | EnumPresetTemplate) -> CapturedResultArray ``` ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter import os cvr = CaptureVisionRouter() image_path = "path/to/document.jpg" if os.path.exists(image_path): # Use string template name result_array = cvr.capture_multi_pages(image_path, "ReadDriversLicense") results = result_array.get_results() if results and len(results) > 0: for i, result in enumerate(results): print(f"Page {i+1}: Processing complete") else: print("No results found") ``` ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumPresetTemplate cvr = CaptureVisionRouter() image_path = "path/to/document.jpg" # Use preset template enum result_array = cvr.capture_multi_pages( image_path, EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) results = result_array.get_results() if results: for result in results: # Check for errors if result.get_error_code() != 0: print(f"Error: {result.get_error_string()}") ``` -------------------------------- ### Implement on_detected_quads_received callback Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/intermediate-results.md Override this method to handle detected document quadrilaterals. ```python def on_detected_quads_received(self, result: DetectedQuadsUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: print("Document quads detected") ``` -------------------------------- ### Use Custom Template for Capture Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Loads a custom JSON template and applies it to a capture operation by name. ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumErrorCode cvr = CaptureVisionRouter() # Load custom template error_code, msg = cvr.init_settings_from_file("CustomTemplates/ReadGS1AIBarcode.json") if error_code != EnumErrorCode.EC_OK: raise Exception(f"Failed to load custom template: {msg}") # Use the custom template by name result_array = cvr.capture_multi_pages("image.png", "ReadGS1AIBarcode") ``` -------------------------------- ### Capture Multi-Page Images with CaptureVisionRouter Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/INDEX.md Process images using a specified template and retrieve the resulting data. ```python cvr = CaptureVisionRouter() results = cvr.capture_multi_pages("image.jpg", "Template").get_results() ``` -------------------------------- ### capture_multi_pages(file_path, template_name) Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/capture-vision-router.md Processes an image file (single or multi-page) using a specified capture template and returns all results. ```APIDOC ## capture_multi_pages(file_path: str, template_name: str | EnumPresetTemplate) ### Description Processes an image file (single or multi-page) using a specified capture template and returns all results. ### Parameters - **file_path** (str) - Required - Full path to the image or document file to process. - **template_name** (str | EnumPresetTemplate) - Required - Name of the capture template to apply. ### Return Type CapturedResultArray - Array-like object containing CapturedResult items. ``` -------------------------------- ### ImageProcessor.crop_and_deskew_image() Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md Crops an image to a specified quadrilateral region and deskews it to horizontal orientation. ```APIDOC ## ImageProcessor.crop_and_deskew_image(image, quad) ### Description Crops an image to a specified quadrilateral region and deskews it to horizontal orientation. ### Parameters - **image** (ImageData) - Required - Source image to crop and deskew - **quad** (Quadrilateral) - Required - Quadrilateral defining the region (typically from detected document corners) ### Return Value - **tuple[int, ImageData]** - A tuple where index 0 is the error code (0 for success) and index 1 is the resulting cropped and deskewed image. ``` -------------------------------- ### Define Barcode Reader Task Settings Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Configures barcode detection parameters including expected count, format IDs, and processing stages. ```json { "BarcodeReaderTaskSettingOptions": [ { "Name": "task_barcode", "ExpectedBarcodesCount": 1, "BarcodeFormatIds": ["BF_GS1_DATABAR", "BF_CODE_128"], "BarcodeFormatSpecificationNameArray": ["bfs_format"], "SectionArray": [ { "Section": "ST_REGION_PREDETECTION", "ImageParameterName": "ip_predetect", "StageArray": [{"Stage": "SST_PREDETECT_REGIONS"}] } ] } ] } ``` -------------------------------- ### Reuse CaptureVisionRouter Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Instantiate the CaptureVisionRouter once and reuse it for multiple capture operations to maintain efficiency. ```python # Good - create once cvr = CaptureVisionRouter() result_1 = cvr.capture_multi_pages("image1.jpg", "Template") result_2 = cvr.capture_multi_pages("image2.jpg", "Template") # Avoid - creating new router for each call is inefficient cvr1 = CaptureVisionRouter() result_1 = cvr1.capture_multi_pages("image1.jpg", "Template") cvr2 = CaptureVisionRouter() result_2 = cvr2.capture_multi_pages("image2.jpg", "Template") ``` -------------------------------- ### Collect Intermediate Results Implementation Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/intermediate-results.md A complete implementation of a custom IntermediateResultReceiver to aggregate various result units by their original image hash ID. ```python from dynamsoft_capture_vision_bundle import ( CaptureVisionRouter, IntermediateResultReceiver, IntermediateResultExtraInfo, DeskewedImageUnit, LocalizedTextLinesUnit, RecognizedTextLinesUnit, ScaledColourImageUnit, DetectedQuadsUnit ) from typing import Dict class IntermediateResultUnit: def __init__(self): self.deskewed_image_unit = None self.localized_text_lines_unit = None self.scaled_colour_img_unit = None self.detected_quads_unit = None self.recognized_text_lines_unit = None class MyIntermediateResultReceiver(IntermediateResultReceiver): def __init__(self): super().__init__() self.unit_groups: Dict[str, IntermediateResultUnit] = {} def on_deskewed_image_received(self, result: DeskewedImageUnit, info: IntermediateResultExtraInfo) -> None: if info.is_section_level_result: id = result.get_original_image_hash_id() if self.unit_groups.get(id) is None: self.unit_groups[id] = IntermediateResultUnit() self.unit_groups[id].deskewed_image_unit = result def on_localized_text_lines_received(self, result: LocalizedTextLinesUnit, info: IntermediateResultExtraInfo) -> None: if info.is_section_level_result: id = result.get_original_image_hash_id() if self.unit_groups.get(id) is None: self.unit_groups[id] = IntermediateResultUnit() self.unit_groups[id].localized_text_lines_unit = result def on_scaled_colour_image_unit_received(self, result: ScaledColourImageUnit, info: IntermediateResultExtraInfo) -> None: id = result.get_original_image_hash_id() if self.unit_groups.get(id) is None: self.unit_groups[id] = IntermediateResultUnit() self.unit_groups[id].scaled_colour_img_unit = result def on_recognized_text_lines_received(self, result: RecognizedTextLinesUnit, info: IntermediateResultExtraInfo) -> None: if info.is_section_level_result: id = result.get_original_image_hash_id() if self.unit_groups.get(id) is None: self.unit_groups[id] = IntermediateResultUnit() self.unit_groups[id].recognized_text_lines_unit = result def on_detected_quads_received(self, result: DetectedQuadsUnit, info: IntermediateResultExtraInfo) -> None: if info.is_section_level_result: id = result.get_original_image_hash_id() if self.unit_groups.get(id) is None: self.unit_groups[id] = IntermediateResultUnit() self.unit_groups[id].detected_quads_unit = result # Usage cvr = CaptureVisionRouter() irm = cvr.get_intermediate_result_manager() my_receiver = MyIntermediateResultReceiver() irm.add_result_receiver(my_receiver) # Process image result_array = cvr.capture_multi_pages("image.jpg", "ReadPassportAndId") results = result_array.get_results() # Access collected intermediate results if results: for result in results: hash_id = result.get_original_image_hash_id() units = my_receiver.unit_groups.get(hash_id) if units: print(f"Deskewed image: {units.deskewed_image_unit}") print(f"Detected quads: {units.detected_quads_unit}") # Cleanup irm.remove_result_receiver(my_receiver) ``` -------------------------------- ### Accessing FileImageTag Metadata Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/types.md Demonstrates how to retrieve and use metadata from a FileImageTag object, including file path and page number. ```python from dynamsoft_capture_vision_bundle import FileImageTag tag = result.get_original_image_tag() if isinstance(tag, FileImageTag): file_path = tag.get_file_path() page_number = tag.get_page_number() # 0-indexed print(f"File: {file_path}, Page: {page_number + 1}") ``` -------------------------------- ### Access Original Image Metadata Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Use get_original_image_tag to retrieve file path and page information for the source image. ```python get_original_image_tag() -> FileImageTag | None ``` ```python from dynamsoft_capture_vision_bundle import FileImageTag tag = result.get_original_image_tag() if isinstance(tag, FileImageTag): file_path = tag.get_file_path() page_number = tag.get_page_number() print(f"Processing page {page_number + 1} from {file_path}") ``` -------------------------------- ### Extract and save portrait region in Python Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/sample-patterns.md Uses IdentityProcessor to find the portrait zone and ImageProcessor to crop and deskew the image before saving via ImageIO. ```python from dynamsoft_capture_vision_bundle import ( IdentityProcessor, ImageProcessor, ImageIO, EnumErrorCode, OriginalImageResultItem ) def save_portrait(irr, hash_id: str, original_image, page_number: int, image_path: str): """Extract and save portrait from identity document.""" # Get portrait zone from intermediate results identity_processor = IdentityProcessor() units = irr.unit_groups.get(hash_id) if units is None: print("get_precise_portrait_zone failed, hash_id not found:", hash_id) return ret, portrait_zone = identity_processor.find_portrait_zone( units.scaled_colour_img_unit, units.localized_text_lines_unit, units.recognized_text_lines_unit, units.detected_quads_unit, units.deskewed_image_unit ) if ret != EnumErrorCode.EC_OK: print("get_precise_portrait_zone failed, error code:", ret) return if portrait_zone is None: print("No portrait zone found") return # Crop and deskew the portrait region image_processor = ImageProcessor() crop_ret, out_image = image_processor.crop_and_deskew_image( original_image, portrait_zone ) if crop_ret != EnumErrorCode.EC_OK: print("crop image failed, error code:", crop_ret) return # Save the portrait output_path = f"{image_path.stem}_{page_number}_portrait.png" image_io = ImageIO() error_code, error_msg = image_io.save_to_file(out_image, output_path) if error_code == 0: print("Portrait file: " + output_path) else: print("Save portrait failed, error:", error_code, error_msg) # Usage def get_original_image(result): """Extract original image from result items.""" for item in result.get_items(): if isinstance(item, OriginalImageResultItem): return item.get_image_data() return None # In main processing hash_id = result.get_original_image_hash_id() original_image = get_original_image(result) if original_image: save_portrait(irr, hash_id, original_image, page_number, image_path) ``` -------------------------------- ### Save Image Data with ImageIO Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/INDEX.md Use the ImageIO utility to save processed image data to a file. ```python image_io = ImageIO() error_code, msg = image_io.save_to_file(image_data, "output.png") ``` -------------------------------- ### Save image with error handling Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/image-processing.md Basic implementation of saving an image with a check for the returned error code. ```python from dynamsoft_capture_vision_bundle import ImageIO image_io = ImageIO() error_code, error_msg = image_io.save_to_file(image_data, "output.png") if error_code != 0: print(f"Error saving image: {error_msg}") else: print("Image saved successfully") ``` -------------------------------- ### Define EnumPresetTemplate Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/types.md Represents the available built-in capture templates for document processing. ```python class EnumPresetTemplate: PT_DETECT_AND_NORMALIZE_DOCUMENT: Detects and normalizes document boundaries ``` -------------------------------- ### Implement on_deskewed_image_received callback Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/intermediate-results.md Override this method to handle deskewed image units. Access the original image hash ID via the result object. ```python class MyReceiver(IntermediateResultReceiver): def on_deskewed_image_received(self, result: DeskewedImageUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: print("Deskewed image available") hash_id = result.get_original_image_hash_id() ``` -------------------------------- ### Implement DCPResultProcessor for Data Extraction Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/sample-patterns.md Use this class to parse individual items from a recognition result. It requires the dynamsoft_capture_vision_bundle package and handles field validation status checks. ```python from dynamsoft_capture_vision_bundle import EnumValidationStatus class DCPResultProcessor: """Helper class to parse and structure parsed results.""" def __init__(self, item): self.doc_type = item.get_code_type() self.raw_text = [] self.doc_id = None self.surname = None self.given_name = None self.nationality = None self.issuer = None self.gender = None self.date_of_birth = None self.date_of_expiry = None self.is_passport = False # Extract document type if self.doc_type == "MRTD_TD3_PASSPORT": # Passport-specific logic passport_num = item.get_field_value("passportNumber") if passport_num is not None and \ item.get_field_validation_status("passportNumber") != EnumValidationStatus.VS_FAILED: self.doc_id = passport_num self.is_passport = True # Extract common fields if item.get_field_value("primaryIdentifier") is not None and \ item.get_field_validation_status("primaryIdentifier") != EnumValidationStatus.VS_FAILED: self.surname = item.get_field_value("primaryIdentifier") if item.get_field_value("secondaryIdentifier") is not None and \ item.get_field_validation_status("secondaryIdentifier") != EnumValidationStatus.VS_FAILED: self.given_name = item.get_field_value("secondaryIdentifier") def get_string_result(self): """Format extracted data as readable string.""" msg = (f"Raw Text:\n") for index, line in enumerate(self.raw_text): msg += (f"\tLine {index + 1}: {line}\n") msg += (f"Parsed Information:\n" f"\tDocumentType: {self.doc_type or ''}\n" f"\tDocumentID: {self.doc_id or ''}\n" f"\tSurname: {self.surname or ''}\n" f"\tGivenName: {self.given_name or ''}\n" f"\tNationality: {self.nationality or ''}\n") return msg # Usage for item in parsed_result.get_items(): result_processor = DCPResultProcessor(item) print(result_processor.get_string_result()) ``` -------------------------------- ### Handle multi-page processing results in Python Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/error-handling.md Iterate through result arrays and check individual error codes for each page to track success and failure counts. ```python results = result_array.get_results() if results is None or len(results) == 0: print("No results from processing") else: success_count = 0 error_count = 0 for i, result in enumerate(results): if result.get_error_code() == EnumErrorCode.EC_OK: success_count += 1 # Process result else: error_count += 1 print(f"Page {i+1} error: {result.get_error_string()}") print(f"Processing complete: {success_count} successful, {error_count} failed") ``` -------------------------------- ### Retrieve All Result Items Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/result-objects.md Use get_items to iterate through all result items associated with the capture. ```python get_items() -> list[ResultItem] ``` ```python for item in result.get_items(): if isinstance(item, OriginalImageResultItem): print("Found original image result item") ``` -------------------------------- ### Parse GS1 Barcode Data Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/quick-start.md Initializes a license and parses GS1 Application Identifiers from a barcode image using a custom JSON template. ```python from dynamsoft_capture_vision_bundle import ( LicenseManager, CaptureVisionRouter, EnumErrorCode ) LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() # Load custom template for GS1 error_code, msg = cvr.init_settings_from_file("CustomTemplates/ReadGS1AIBarcode.json") if error_code != EnumErrorCode.EC_OK: print(f"Template error: {msg}") exit(1) result_array = cvr.capture_multi_pages("barcode.png", "ReadGS1AIBarcode") results = result_array.get_results() if results: for result in results: if result.get_error_code() == EnumErrorCode.EC_OK: parsed = result.get_parsed_result() if parsed: for item in parsed.get_items(): # Get all field names and extract values all_fields = item.get_all_field_names() for field_name in all_fields: value = item.get_field_value(field_name) if value is not None: print(f"{field_name}: {value}") ``` -------------------------------- ### Implement on_localized_text_lines_received callback Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/intermediate-results.md Override this method to handle localized text line results. ```python def on_localized_text_lines_received(self, result: LocalizedTextLinesUnit, info: IntermediateResultExtraInfo): if info.is_section_level_result: print("Text lines localized") ``` -------------------------------- ### Implement IntermediateResultReceiver Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/INDEX.md Define a custom receiver class to handle intermediate processing results such as deskewed images. ```python class MyReceiver(IntermediateResultReceiver): def on_deskewed_image_received(self, result, info): # Access intermediate deskewed image ``` -------------------------------- ### EnumPresetTemplate Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/types.md Enumeration of built-in capture templates for common document types used in capture operations. ```APIDOC ## EnumPresetTemplate ### Description Enumeration of built-in capture templates for common document types. ### Values - **PT_DETECT_AND_NORMALIZE_DOCUMENT**: Detects and normalizes document boundaries. ### Usage Example ```python from dynamsoft_capture_vision_bundle import CaptureVisionRouter, EnumPresetTemplate cvr = CaptureVisionRouter() # Use preset template result_array = cvr.capture_multi_pages( "document.jpg", EnumPresetTemplate.PT_DETECT_AND_NORMALIZE_DOCUMENT ) ``` ``` -------------------------------- ### Save Enhanced Document Images Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/sample-patterns.md Saves normalized document images to disk using the ImageIO utility. Requires a valid processed document result object and a target file path. ```python from dynamsoft_capture_vision_bundle import ImageIO from pathlib import Path def save_processed_document_result(result, page_number: int, image_path: str): """Save enhanced document images.""" processed_document_result = result.get_processed_document_result() if processed_document_result is None or \ len(processed_document_result.get_enhanced_image_result_items()) == 0: print("Page-"+str(page_number), "No processed document result found.") return items = processed_document_result.get_enhanced_image_result_items() if len(items) > 0: # Get stem of input file for output naming stem = Path(image_path).stem for idx, item in enumerate(items): out_path = f"{stem}_{page_number}_document_{idx}.png" image_io = ImageIO() image = item.get_image_data() if image is not None: errorCode, errorMsg = image_io.save_to_file(image, out_path) if errorCode == 0: print("Document file: " + out_path) else: print("Save processed document failed, error:", errorCode, errorMsg) ``` -------------------------------- ### Define Code Parser Task Settings Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Configures structured data extraction using specific code specifications. ```json { "CodeParserTaskSettingOptions": [ { "Name": "dcp_gs1_ai", "CodeSpecifications": ["GS1_AI"] } ] } ``` -------------------------------- ### Define Capture Vision Templates Source: https://github.com/dynamsoft/capture-vision-python-samples/blob/main/_autodocs/configuration.md Maps a template name to specific ROI and semantic processing pipelines. ```json { "CaptureVisionTemplates": [ { "Name": "MyTemplate", "ImageROIProcessingNameArray": ["roi_process"], "SemanticProcessingNameArray": ["sp_semantic"] } ] } ```