### GPU Acceleration Setup Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Enable GPU acceleration by setting `use_gpu=True` and specifying `device_id`. Ensure CUDA and onnxruntime-gpu are installed. ```python ocr = ddddocr.DdddOcr(use_gpu=True, device_id=0) ``` -------------------------------- ### Install DdddOcr Source: https://context7.com/sml2h3/ddddocr/llms.txt Install the core library or with API dependencies. Installation from source is also supported. ```bash # Core library only pip install ddddocr # With REST API dependencies (FastAPI + uvicorn) pip install "ddddocr[api]" # From source git clone https://github.com/sml2h3/ddddocr.git cd ddddocr pip install . ``` -------------------------------- ### Install DdddOcr from PyPI Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Use pip to install the DdddOcr library. This is the recommended installation method. ```bash pip install ddddocr ``` -------------------------------- ### Start DdddOcr API Service (Default) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Use this command to start the API service with default configurations. The service will bind to the default host and port. ```bash python -m ddddocr api ``` -------------------------------- ### Install DdddOcr from Source Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Clone the repository and install DdddOcr using pip. This method is useful for development or when needing the latest changes. ```bash git clone https://github.com/sml2h3/ddddocr.git cd ddddocr pip install . ``` -------------------------------- ### Command-line API Service Startup Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Instructions on how to start the DdddOcr API service using the command line with default or custom configurations. ```APIDOC ## Command-line API Service Startup ### Description Start the DdddOcr API service using the command line. ### Usage ```bash # Use default configuration python -m ddddocr api # Specify host and port python -m ddddocr api --host 0.0.0.0 --port 8000 --workers 4 # Configure OCR functionality python -m ddddocr api --ocr true --beta true # Configure object detection functionality python -m ddddocr api --ocr false --det true ``` **Note**: Running `python -m ddddocr.api` directly defaults to binding on `127.0.0.1`. This can be overridden using the `DDDDOCR_HOST` environment variable. ``` -------------------------------- ### Start DdddOcr API Service with Docker Compose (Custom Configuration) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Start the DdddOcr API service using Docker Compose with custom environment variables to override default settings. This example enables OCR and beta features, and sets the worker count. ```bash DDDDOCR_OCR=true DDDDOCR_BETA=true DDDDOCR_WORKERS=4 docker-compose up -d ``` -------------------------------- ### Python Client Example (File Upload) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Example Python code demonstrating how to use the DdddOcr API by uploading image files. ```APIDOC #### Python Example (File Upload) ```python import requests # Prepare file files = {"file": open("captcha.png", "rb")} # Send OCR request url = "http://localhost:8000/ocr/file" response = requests.post(url, files=files) # Process response result = response.json() print(f"Recognition result: {result['result']}") ``` ``` -------------------------------- ### Starting the REST API Server Source: https://context7.com/sml2h3/ddddocr/llms.txt Launches a FastAPI/uvicorn server that exposes all DdddOcr functionalities over HTTP. Interactive Swagger documentation is accessible at the `/docs` endpoint. ```APIDOC ## Starting the REST API Server Launches a FastAPI/uvicorn server exposing all ddddocr capabilities over HTTP. Interactive Swagger docs are available at `/docs`. ```bash # Minimal — OCR enabled, port 8000, all interfaces python -m ddddocr api # Custom host/port, 4 workers, beta model python -m ddddocr api --host 0.0.0.0 --port 9000 --workers 4 --beta true # Detection mode instead of OCR python -m ddddocr api --ocr false --det true ``` ``` -------------------------------- ### Start DdddOcr API Service with Docker Compose (Default) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Use Docker Compose to start the DdddOcr API service with default configurations. Ensure a docker-compose.yml file is present in the current directory. ```bash docker-compose up -d ``` -------------------------------- ### Start DdddOcr API Service (Custom Configuration) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Start the API service with custom host, port, and worker count. This allows for more control over the service's network binding and performance. ```bash python -m ddddocr api --host 0.0.0.0 --port 8000 --workers 4 ``` -------------------------------- ### Python Client Example (Base64 Encoding) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Example Python code demonstrating how to use the DdddOcr API with Base64 encoded images. ```APIDOC ### API Client Example #### Python Example (Base64 Encoding) ```python import requests import base64 # Read image file and Base64 encode with open("captcha.png", "rb") as f: img_base64 = base64.b64encode(f.read()).decode() # Send OCR request url = "http://localhost:8000/ocr" response = requests.post(url, json={"image": img_base64}) # Process response result = response.json() print(f"Recognition result: {result['result']}") ``` ``` -------------------------------- ### Install API Dependencies for DdddOcr Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Install optional dependencies for API-related functionalities. This is not required for basic OCR tasks. ```bash pip install "'.[api]'" ``` -------------------------------- ### Starting the REST API Server Source: https://context7.com/sml2h3/ddddocr/llms.txt Launches a FastAPI/uvicorn server for DdddOcr functionalities over HTTP. Access interactive Swagger docs at `/docs`. Options include custom host, port, workers, and model beta status. ```bash # Minimal — OCR enabled, port 8000, all interfaces python -m ddddocr api # Custom host/port, 4 workers, beta model python -m ddddocr api --host 0.0.0.0 --port 9000 --workers 4 --beta true # Detection mode instead of OCR python -m ddddocr api --ocr false --det true ``` -------------------------------- ### Configure API Service for OCR Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Enable OCR functionality and use the beta version of the OCR model when starting the API service. ```bash python -m ddddocr api --ocr true --beta true ``` -------------------------------- ### Start ddddocr Docker with Custom Settings Source: https://context7.com/sml2h3/ddddocr/llms.txt Launch the ddddocr Docker container with specific configurations, such as enabling the beta model and setting the number of workers. Includes a command to check the service health. ```bash # Start with beta model and 4 workers DDDDOCR_BETA=true DDDDOCR_WORKERS=4 docker-compose up -d # Check health curl http://localhost:8000/health ``` -------------------------------- ### API Command-line Parameters Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Detailed explanation of the command-line parameters available for starting the DdddOcr API service. ```APIDOC ## API Command-line Parameters | Parameter | Type | Default | Description | |---|---|---|---| | `--host` | string | 0.0.0.0 | API service host address | | `--port` | integer | 8000 | API service port | | `--workers` | integer | 1 | Number of API service worker processes | | `--ocr` | boolean | true | Whether to enable OCR functionality | | `--det` | boolean | false | Whether to enable object detection functionality | | `--old` | boolean | false | Whether to use the old OCR model | | `--beta` | boolean | false | Whether to use the Beta version OCR model | | `--use-gpu` | boolean | false | Whether to use GPU acceleration | | `--device-id` | integer | 0 | GPU device ID | | `--show-ad` | boolean | true | Whether to display advertisements | | `--import-onnx-path` | string | "" | Path to custom model | | `--charsets-path` | string | "" | Path to custom character set | ``` -------------------------------- ### Configure API Service for Target Detection Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Disable OCR functionality and enable target detection when starting the API service. ```bash python -m ddddocr api --ocr false --det true ``` -------------------------------- ### Slide Captcha Matching Example Source: https://github.com/sml2h3/ddddocr/blob/master/README.md An example demonstrating how to use ddddocr for slide captcha recognition. It includes reading target and background images, matching the slide position, and visualizing the result. ```python import ddddocr import cv2 import numpy as np import matplotlib.pyplot as plt # 初始化滑块检测对象 slide = ddddocr.DdddOcr(det=False, ocr=False) # 读取滑块图和背景图 with open('target.png', 'rb') as f: target_bytes = f.read() with open('background.png', 'rb') as f: background_bytes = f.read() # 匹配位置 res = slide.slide_match(target_bytes, background_bytes) print(f"滑块位置: {res}") # 可视化结果 background = cv2.imdecode(np.frombuffer(background_bytes, np.uint8), cv2.IMREAD_COLOR) x1, y1, x2, y2 = res["target"] # 在背景图上绘制匹配位置 cv2.rectangle(background, (x1, y1), (x2, y2), (0, 255, 0), 2) ``` -------------------------------- ### Production Docker Deployment Configuration Source: https://context7.com/sml2h3/ddddocr/llms.txt Example docker-compose.yml for a production deployment of ddddocr. Configure ports, environment variables for OCR, beta model, GPU usage, and workers. ```yaml # docker-compose.yml — production deployment services: ddddocr-api: build: . container_name: ddddocr-api ports: - "${DDDDOCR_PORT:-8000}:8000" environment: - DDDDOCR_HOST=0.0.0.0 - DDDDOCR_PORT=8000 - DDDDOCR_WORKERS=${DDDDOCR_WORKERS:-1} - DDDDOCR_OCR=${DDDDOCR_OCR:-true} - DDDDOCR_BETA=${DDDDOCR_BETA:-false} - DDDDOCR_USE_GPU=${DDDDOCR_USE_GPU:-false} restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/health"] interval: 30s timeout: 10s retries: 3 ``` -------------------------------- ### Complete Captcha Recognition Flow Source: https://github.com/sml2h3/ddddocr/blob/master/README.md A full example demonstrating the process of reading a captcha image, performing basic preprocessing (commented out), and then classifying it. ```python import ddddocr import cv2 import numpy as np from PIL import Image import io # 初始化OCR对象 ocr = ddddocr.DdddOcr() # 读取验证码图片 with open("captcha.jpg", "rb") as f: image_bytes = f.read() # 转换为OpenCV格式进行预处理 # img = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR) # 预处理:灰度化、二值化等 # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV) # 转回字节流 # is_success, buffer = cv2.imencode(".jpg", binary) # processed_bytes = io.BytesIO(buffer).getvalue() # 识别处理后的图片 result = ocr.classification(image_bytes) print(f"验证码识别结果: {result}") ``` -------------------------------- ### Initialize DdddOcr with GPU Acceleration Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr with GPU acceleration enabled. Requires CUDA and the appropriate onnxruntime-gpu version to be installed. Specify the GPU device ID if needed. ```python import ddddocr # Use GPU acceleration ocr = ddddocr.DdddOcr(use_gpu=True) # Use a specific GPU device (e.g., device ID 1) # ocr = ddddocr.DdddOcr(use_gpu=True, device_id=1) ``` -------------------------------- ### Slide Captcha Matching Example Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md This example demonstrates how to use DDDDOCR for slide captcha verification. It initializes a slide matching object and uses it to find the position of a target image within a background image. ```python import ddddocr import cv2 import numpy as np import matplotlib.pyplot as plt # 初始化滑块检测对象 slide = ddddocr.DdddOcr(det=False, ocr=False) # 读取滑块图和背景图 with open('target.png', 'rb') as f: target_bytes = f.read() with open('background.png', 'rb') as f: background_bytes = f.read() # 匹配位置 res = slide.slide_match(target_bytes, background_bytes) print(f"滑块位置: {res}") ``` -------------------------------- ### Run DdddOcr API Docker Container with Custom Configuration Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Run a Docker container with custom environment variables to configure the DdddOcr API service. This example enables OCR and beta features, and sets the worker count. ```bash docker run -d --name ddddocr-api \ -p 8000:8000 \ -e DDDDOCR_OCR=true \ -e DDDDOCR_BETA=true \ -e DDDDOCR_WORKERS=4 \ ddddocr-api ``` -------------------------------- ### Run DdddOcr API Docker Container Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Run a Docker container from the built DdddOcr API image. This command starts the API service and maps port 8000 from the container to the host. ```bash docker run -d --name ddddocr-api -p 8000:8000 ddddocr-api ``` -------------------------------- ### Detect Objects in Image Source: https://context7.com/sml2h3/ddddocr/llms.txt Send a Base64-encoded image to the /detect endpoint to get bounding box coordinates for detected objects. Requires `det=True` during initialization. ```bash IMAGE_B64=$(base64 -w 0 click_captcha.jpg) curl -X POST http://localhost:8000/detect \ -H "Content-Type: application/json" \ -d "{\"image\": \"$IMAGE_B64\"}" ``` -------------------------------- ### Multi-threaded OCR Optimization Source: https://github.com/sml2h3/ddddocr/blob/master/README.md In multi-threaded environments, create a separate OCR instance for each thread to avoid recognition errors. This example demonstrates parallel processing of images using ThreadPoolExecutor. ```python import ddddocr import concurrent.futures import os def process_image(file_path): # 每个线程创建自己的OCR实例 ocr = ddddocr.DdddOcr() with open(file_path, 'rb') as f: image = f.read() result = ocr.classification(image) return os.path.basename(file_path), result def parallel_process(directory, max_workers=4): file_paths = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(('.png', '.jpg', '.jpeg', '.bmp'))] results = {} with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: future_to_file = {executor.submit(process_image, file_path): file_path for file_path in file_paths} for future in concurrent.futures.as_completed(future_to_file): filename, result = future.result() results[filename] = result return results # 使用示例 results = parallel_process("./captchas/", max_workers=8) ``` -------------------------------- ### Initialize DdddOcr with Custom Parameters Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Demonstrates initializing the DdddOcr class with various configuration options. Adjust parameters like `ocr`, `det`, `use_gpu`, and `import_onnx_path` based on your specific needs. ```python ddddocr.DdddOcr( ocr=True, # 是否启用OCR功能 det=False, # 是否启用目标检测功能 old=False, # 是否使用旧版OCR模型 beta=False, # 是否使用Beta版OCR模型(新模型) use_gpu=False, # 是否使用GPU加速 device_id=0, # 使用的GPU设备ID show_ad=True, # 是否显示广告信息 import_onnx_path="", # 自定义模型路径 charsets_path="", # 自定义字符集路径 max_image_bytes=None, # 单图最大字节数(默认 8MB) max_image_side=None # 单图最长边限制(默认 4096px) ) ``` -------------------------------- ### Initialize API Service Source: https://context7.com/sml2h3/ddddocr/llms.txt Load models into the running server for subsequent inference calls. Supports GPU usage and device ID selection. ```bash curl -X POST http://localhost:8000/initialize \ -H "Content-Type: application/json" \ -d '{ "ocr": true, "det": false, "beta": true, "use_gpu": false, "device_id": 0 }' ``` -------------------------------- ### DdddOcr Initialization Source: https://github.com/sml2h3/ddddocr/blob/master/examples/README.md Demonstrates how to initialize the DdddOcr class with various configuration options for different recognition tasks. ```APIDOC ## DdddOcr Initialization ### Description Initializes the DdddOcr class with various parameters to configure its behavior for different recognition tasks like OCR, target detection, or using custom models. ### Method `DdddOcr(...)` ### Parameters #### Initialization Parameters - **ocr** (bool) - Optional - Defaults to `True`. Enables OCR functionality for text recognition. This is automatically disabled if `det` is set to `True`. - **det** (bool) - Optional - Defaults to `False`. Enables target detection functionality for identifying object locations. If set to `True`, it overrides the `ocr` setting. - **old** (bool) - Optional - Defaults to `False`. Compatibility parameter; currently does not affect model selection. - **beta** (bool) - Optional - Defaults to `False`. Enables the Beta version of the OCR model, which may offer improved performance on certain CAPTCHAs. Mutually exclusive with `old=True`. - **use_gpu** (bool) - Optional - Defaults to `False`. Enables GPU acceleration. Requires CUDA and a compatible `onnxruntime-gpu` installation; otherwise, initialization will fail. - **device_id** (int) - Optional - Defaults to `0`. Specifies the ID of the GPU device to use. Only effective when `use_gpu` is `True`. - **show_ad** (bool) - Optional - Defaults to `True`. Controls whether to display advertisement information during initialization. - **import_onnx_path** (str) - Optional - Defaults to `""`. Path to a custom ONNX model file. When specified, `charsets_path` must also be provided, and the `ocr`/`det` settings are ignored. - **charsets_path** (str) - Optional - Defaults to `""`. Path to a custom character set JSON file. Must be used in conjunction with `import_onnx_path`. - **max_image_bytes** (int/str) - Optional - Defaults to `8MB`. Maximum allowed size in bytes for a single image. Accepts integer or string representation of a number. - **max_image_side** (int/str) - Optional - Defaults to `4096`. Maximum allowed side length in pixels for a single image. Accepts integer or string representation of a number. ### Request Example ```python import ddddocr # Basic OCR initialization ocr_detector = ddddocr.DdddOcr() # Initialization with GPU support # ocr_detector = ddddocr.DdddOcr(use_gpu=True, device_id=0) # Initialization with Beta OCR model # ocr_detector = ddddocr.DdddOcr(beta=True) # Initialization with custom model # ocr_detector = ddddocr.DdddOcr(import_onnx_path="path/to/your/model.onnx", charsets_path="path/to/your/charsets.json") ``` ### Response #### Success Response An initialized `DdddOcr` object ready for use. #### Response Example ```python # Successful initialization returns an object, no specific output is printed by default unless show_ad is True. ``` ``` -------------------------------- ### List Available MCP Tools Source: https://context7.com/sml2h3/ddddocr/llms.txt Query the Model Context Protocol (MCP) endpoint to discover the tools and methods available for AI agent integration. ```bash # List available tools curl http://localhost:8000/mcp/capabilities ``` -------------------------------- ### Initialize API Service with Python Source: https://context7.com/sml2h3/ddddocr/llms.txt Initialize or reinitialize the API service using Python requests. All subsequent inference calls use the model loaded here. ```python import requests resp = requests.post("http://localhost:8000/initialize", json={ "ocr": True, "det": False, "beta": True }) print(resp.json()) ``` -------------------------------- ### Get Service Status Source: https://context7.com/sml2h3/ddddocr/llms.txt Retrieve the current status of the ddddocr service, including loaded models, enabled features, version, and uptime. This is useful for monitoring and diagnostics. ```bash curl http://localhost:8000/status # { # "service_status": "running", # "loaded_models": ["ocr", "slide"], # "enabled_features": ["ocr", "slide"], # "version": "1.6.1", # "uptime": 342.7 # } ``` -------------------------------- ### POST /initialize Source: https://context7.com/sml2h3/ddddocr/llms.txt Initializes or reinitializes the API service by loading specified models. Subsequent inference calls will use the loaded models. ```APIDOC ## POST /initialize — Initialize or Reinitialize the API Service Loads the requested model(s) into the running server. All subsequent inference calls use the model loaded here. ### Method POST ### Endpoint http://localhost:8000/initialize ### Request Body - **ocr** (boolean) - Optional - Whether to load the OCR model. - **det** (boolean) - Optional - Whether to load the object detection model. - **beta** (boolean) - Optional - Whether to enable beta features. - **use_gpu** (boolean) - Optional - Whether to use GPU for inference. - **device_id** (integer) - Optional - The ID of the GPU device to use. ### Request Example ```json { "ocr": true, "det": false, "beta": true, "use_gpu": false, "device_id": 0 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the initialization was successful. - **message** (string) - A message indicating the status of the initialization. - **data** (object) - Contains details about the loaded models. - **loaded_models** (array of strings) - A list of models that were loaded. - **message** (string) - A confirmation message. #### Response Example ```json { "success": true, "message": "服务初始化成功", "data": { "loaded_models": ["ocr", "slide"], "message": "服务初始化成功" } } ``` ``` -------------------------------- ### Python OCR Request (File Upload) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Example Python code demonstrating how to send an OCR request to the DdddOcr API using file upload. This method is convenient for sending image files directly as multipart/form-data. ```python import requests # 准备文件 files = {"file": open("captcha.png", "rb")} # 发送OCR请求 url = "http://localhost:8000/ocr/file" response = requests.post(url, files=files) # 处理响应 result = response.json() print(f"识别结果: {result['result']}") ``` -------------------------------- ### Docker API Service Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Instructions for building and running the DdddOcr API service using Docker, including custom configurations. ```APIDOC ## Using Docker to Run API Service ### Build and Run Docker Image ```bash # Build Docker image docker build -t ddddocr-api . # Run Docker container docker run -d --name ddddocr-api -p 8000:8000 ddddocr-api # Run with custom configuration docker run -d --name ddddocr-api \ -p 8000:8000 \ -e DDDDOCR_OCR=true \ -e DDDDOCR_BETA=true \ -e DDDDOCR_WORKERS=4 \ ddddocr-api ``` ### Using Docker Compose ```bash # Start with default configuration docker-compose up -d # Start with custom configuration DDDDOCR_OCR=true DDDDOCR_BETA=true DDDDOCR_WORKERS=4 docker-compose up -d ``` ``` -------------------------------- ### Python OCR Request (Base64) Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Example Python code demonstrating how to send an OCR request to the DdddOcr API using Base64 encoded image data. This method is suitable for sending image data directly within the request payload. ```python import requests import base64 # 读取图片文件并Base64编码 with open("captcha.png", "rb") as f: img_base64 = base64.b64encode(f.read()).decode() # 发送OCR请求 url = "http://localhost:8000/ocr" response = requests.post(url, json={"image": img_base64}) # 处理响应 result = response.json() print(f"识别结果: {result['result']}") ``` -------------------------------- ### Switch to Beta OCR Model Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Utilize an alternative OCR model by setting the `beta` parameter to `True` during initialization. This model may offer better performance on certain complex captchas. ```python # 使用第二套OCR模型 ocr = ddddocr.DdddOcr(beta=True) ``` -------------------------------- ### Initialize DdddOcr with Custom ONNX Model Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr with a custom ONNX model. Requires both the model path and the character set path to be provided. OCR and detection settings are ignored when a custom model is imported. ```python import ddddocr # Specify paths to your custom ONNX model and character set JSON ocr = ddddocr.DdddOcr(import_onnx_path="path/to/your/model.onnx", charsets_path="path/to/your/charsets.json") ``` -------------------------------- ### Initialize DdddOcr with Image Size Limits Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr with limits on maximum image file size and side length. This helps manage memory usage and processing time for large images. ```python import ddddocr # Limit image size to 4MB and max side to 2048px ocr = ddddocr.DdddOcr(max_image_bytes=4*1024*1024, max_image_side=2048) ``` -------------------------------- ### MCP Integration - Capabilities Source: https://context7.com/sml2h3/ddddocr/llms.txt Lists the available tools (methods) that can be called via the Model Context Protocol (MCP). ```APIDOC ## GET /mcp/capabilities ### Description Lists the available methods that can be invoked through the MCP interface. ### Method GET ### Endpoint /mcp/capabilities ### Response #### Success Response (200) - **capabilities** (array of strings) - A list of available MCP method names. ``` -------------------------------- ### POST /detect Source: https://context7.com/sml2h3/ddddocr/llms.txt Performs object detection on an image to identify bounding boxes. Requires the server to be initialized with `det=True`. ```APIDOC ## POST /detect — REST Object Detection Endpoint Detects bounding boxes in the uploaded image. Requires the server to have been initialized with `det=True`. ### Method POST ### Endpoint http://localhost:8000/detect ### Parameters #### Request Body - **image** (string) - Required - The Base64-encoded image string. ### Request Example ```json { "image": "" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the detection was successful. - **message** (string) - A message indicating the status of the detection process. - **data** (object) - Contains the detection results. - **bboxes** (array of arrays) - A list of bounding boxes, where each box is represented by `[x1, y1, x2, y2]`. #### Response Example ```json { "success": true, "message": "目标检测成功", "data": { "bboxes": [ [23, 45, 67, 89], [120, 30, 160, 70] ] } } ``` ``` -------------------------------- ### Image Utility Helpers: get_img_base64 / base64_to_image Source: https://context7.com/sml2h3/ddddocr/llms.txt Convenience functions for converting images between file paths, bytes, and base64 strings. Useful for preparing images for the HTTP API. `base64_to_image` returns a PIL Image object. ```python from ddddocr import get_img_base64, base64_to_image # File → base64 string (for API payloads) b64 = get_img_base64("captcha.png") print(b64[:40]) # "iVBORw0KGgoAAAANSUhEUgAA..." # base64 string → PIL Image from PIL import Image img: Image.Image = base64_to_image(b64) print(img.size) # (200, 60) # Round-trip check import io, base64 as b64lib raw = b64lib.b64decode(b64) img2 = base64_to_image(b64lib.b64encode(raw).decode()) print(img2.size) ``` -------------------------------- ### Initialize DdddOcr Class Source: https://context7.com/sml2h3/ddddocr/llms.txt Instantiate the DdddOcr class once per process. Various modes and configurations are available, including beta models, object detection, slider-only mode, GPU acceleration, custom ONNX models, and image size limits. ```python import ddddocr # --- Standard OCR (default) --- ocr = ddddocr.DdddOcr(show_ad=False) # --- Beta model (better on some complex CAPTCHAs) --- ocr_beta = ddddocr.DdddOcr(beta=True, show_ad=False) # --- Object-detection mode --- det = ddddocr.DdddOcr(ocr=False, det=True, show_ad=False) # --- Slider-only mode (no OCR or detection model loaded) --- slide = ddddocr.DdddOcr(ocr=False, det=False, show_ad=False) # --- GPU acceleration (requires onnxruntime-gpu + CUDA) --- ocr_gpu = ddddocr.DdddOcr(use_gpu=True, device_id=0, show_ad=False) # --- Custom trained model --- ocr_custom = ddddocr.DdddOcr( ocr=False, det=False, import_onnx_path="mymodel.onnx", charsets_path="charsets.json", show_ad=False, ) # --- Image-size limits (defaults: 8 MB / 4096 px longest side) --- ocr_safe = ddddocr.DdddOcr(max_image_bytes=4096*1024, max_image_side=2048, show_ad=False) ``` -------------------------------- ### Run Custom Model via Command Line Source: https://context7.com/sml2h3/ddddocr/llms.txt Use this command to run the DDDDOCR API with a custom ONNX model and charset configuration. ```bash python -m ddddocr api \ --ocr false --det false \ --import-onnx-path /models/mymodel.onnx \ --charsets-path /models/charsets.json ``` -------------------------------- ### Initialize DdddOcr with Default Parameters Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Basic initialization of the DdddOcr class. By default, OCR functionality is enabled. ```python import ddddocr ocr = ddddocr.DdddOcr() ``` -------------------------------- ### Initialize ddddocr with GPU Acceleration Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Enable GPU acceleration for faster processing, especially when handling a large number of images. Specify the GPU device ID if multiple GPUs are available. ```python ocr = ddddocr.DdddOcr(use_gpu=True, device_id=0) ``` ```python # 使用第二张GPU卡 ocr = ddddocr.DdddOcr(use_gpu=True, device_id=1) ``` -------------------------------- ### Initialize DdddOcr with Beta OCR Model Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr using the beta OCR model, which may offer improved recognition for certain CAPTCHAs. This parameter is mutually exclusive with 'old=True'. ```python import ddddocr ocr = ddddocr.DdddOcr(beta=True) ``` -------------------------------- ### Initialize DdddOcr with Target Detection Enabled Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr with target detection enabled. Note that enabling 'det' will disable 'ocr'. ```python import ddddocr ocr = ddddocr.DdddOcr(det=True) ``` -------------------------------- ### Correct DdddOcr Initialization Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Avoid performance issues by initializing DdddOcr only once. Repeated initialization within loops is inefficient as it reloads the model. ```python # 错误的用法 for img in images: ocr = ddddocr.DdddOcr() # 每次都初始化,严重影响性能 result = ocr.classification(img) # 正确的用法 ocr = ddddocr.DdddOcr() # 只初始化一次 for img in images: result = ocr.classification(img) ``` -------------------------------- ### Build DdddOcr API Docker Image Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Build a Docker image for the DdddOcr API service. This image can then be used to run the API in a containerized environment. ```bash docker build -t ddddocr-api . ``` -------------------------------- ### Compare Slider Images for Pixel Difference Source: https://context7.com/sml2h3/ddddocr/llms.txt Use the /slide-comparison endpoint for slider gap detection based on pixel differences between two images. ```bash NOTCH_B64=$(base64 -w 0 bg_with_notch.jpg) FULL_B64=$(base64 -w 0 bg_complete.jpg) curl -X POST http://localhost:8000/slide-comparison \ -H "Content-Type: application/json" \ -d "{\"target_image\": \"$NOTCH_B64\", \"background_image\": \"$FULL_B64\"}" ``` -------------------------------- ### Switch Active Inference Model (Python) Source: https://context7.com/sml2h3/ddddocr/llms.txt Programmatically switch the active inference model using Python's requests library. Ensure the server is running and accessible. ```python import requests r = requests.post("http://localhost:8000/switch-model", json={ "model_type": "ocr_beta", "use_gpu": False }) print(r.json()["message"]) # "模型 ocr_beta 切换成功" ``` -------------------------------- ### Initialize ddddocr via MCP Source: https://context7.com/sml2h3/ddddocr/llms.txt Initialize ddddocr functionalities, such as OCR or beta OCR, through the MCP interface. This call sets up the desired OCR modes. ```bash # Initialize via MCP curl -X POST http://localhost:8000/mcp/call \ -H "Content-Type: application/json" \ -d '{"method": "ddddocr_initialize", "params": {"ocr": true, "beta": true}, "id": 2}' ``` -------------------------------- ### Object Detection with DdddOcr.detection() Source: https://context7.com/sml2h3/ddddocr/llms.txt Detects objects in an image and returns their bounding boxes. Initialize DdddOcr with `det=True`. The output is a list of [x_min, y_min, x_max, y_max]. Supports GPU acceleration. ```python import ddddocr import cv2 import numpy as np det = ddddocr.DdddOcr(ocr=False, det=True, show_ad=False) with open("click_captcha.jpg", "rb") as f: img_bytes = f.read() boxes = det.detection(img_bytes) # boxes == [[23, 45, 67, 89], [120, 30, 160, 70], ...] # Draw boxes on the image for inspection img_array = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR) for x1, y1, x2, y2 in boxes: cv2.rectangle(img_array, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=2) cv2.imwrite("detected.jpg", img_array) print(f"Found {len(boxes)} targets: {boxes}") # GPU variant det_gpu = ddddocr.DdddOcr(ocr=False, det=True, use_gpu=True, device_id=0, show_ad=False) boxes = det_gpu.detection(img_bytes) ``` -------------------------------- ### Detect Objects in Image with Python Source: https://context7.com/sml2h3/ddddocr/llms.txt Encode an image to Base64 and send it to the /detect endpoint using Python requests to retrieve bounding box data. ```python import requests, base64 with open("click_captcha.jpg", "rb") as f: b64 = base64.b64encode(f.read()).decode() r = requests.post("http://localhost:8000/detect", json={"image": b64}) bboxes = r.json()["data"]["bboxes"] for box in bboxes: print(f" [{box[0]},{box[1]}] → [{box[2]},{box[3]}]") ``` -------------------------------- ### Docker Compose Configuration Source: https://context7.com/sml2h3/ddddocr/llms.txt Configure DDDDOCR service using environment variables in Docker Compose for custom worker counts and beta features. ```bash DDDDOCR_BETA=true DDDDOCR_WORKERS=4 docker-compose up -d ``` -------------------------------- ### DdddOcr Class Constructor Source: https://context7.com/sml2h3/ddddocr/llms.txt Instantiate the DdddOcr class once per process for various inference modes including standard OCR, object detection, slider-CAPTCHA matching, and custom model import. Supports GPU acceleration and image size limits. ```APIDOC ## DdddOcr Constructor Instantiate the `DdddOcr` class once per process. Re-initializing on every call is a common performance mistake. ### Parameters | Parameter | Type | Default | Notes | |---|---|---|---| | `ocr` | bool | `True` | Enable text recognition | | `det` | bool | `False` | Enable bounding-box detection; overrides `ocr` | | `old` | bool | `False` | Compat flag (no current effect) | | `beta` | bool | `False` | Use `common.onnx` instead of `common_old.onnx` | | `use_gpu` | bool | `False` | CUDA inference via onnxruntime-gpu | | `device_id` | int | `0` | GPU index when `use_gpu=True` | | `show_ad` | bool | `True` | Print sponsor info on init | | `import_onnx_path` | str | `""` | Path to custom `.onnx` file | | `charsets_path` | str | `""` | Path to custom charset JSON; required with `import_onnx_path` | | `max_image_bytes` | int | 8 MB | Reject images exceeding this byte size | | `max_image_side` | int | `4096` | Reject images whose longest side exceeds this pixel count | ### Examples ```python import ddddocr # Standard OCR (default) ocr = ddddocr.DdddOcr(show_ad=False) # Beta model ocr_beta = ddddocr.DdddOcr(beta=True, show_ad=False) # Object-detection mode det = ddddocr.DdddOcr(ocr=False, det=True, show_ad=False) # Slider-only mode slide = ddddocr.DdddOcr(ocr=False, det=False, show_ad=False) # GPU acceleration ocr_gpu = ddddocr.DdddOcr(use_gpu=True, device_id=0, show_ad=False) # Custom trained model ocr_custom = ddddocr.DdddOcr( ocr=False, det=False, import_onnx_path="mymodel.onnx", charsets_path="charsets.json", show_ad=False, ) # Image-size limits ocr_safe = ddddocr.DdddOcr(max_image_bytes=4096*1024, max_image_side=2048, show_ad=False) ``` ``` -------------------------------- ### Initialize ddddocr to Disable Ad Display Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Turn off advertisement display in the console output, which is recommended for production environments. ```python ocr = ddddocr.DdddOcr(show_ad=False) ``` -------------------------------- ### Perform OCR via File Upload with Python Source: https://context7.com/sml2h3/ddddocr/llms.txt Use Python requests to upload an image file to the /ocr/file endpoint for text recognition. ```python import requests with open("captcha.png", "rb") as f: r = requests.post("http://localhost:8000/ocr/file", files={"file": f}) print(r.json()["data"]["text"]) ``` -------------------------------- ### DdddOcr.slide_comparison() Source: https://context7.com/sml2h3/ddddocr/llms.txt Compares a background image with a notch against its complete version to determine the position of the gap. Both images must be of the same dimensions. ```APIDOC ## `DdddOcr.slide_comparison()` — Slider CAPTCHA Pixel-Diff Comparison Compares a partially-occluded (notch) image against its complete version to locate the gap. Both images must be the same size. ```python import ddddocr slide = ddddocr.DdddOcr(ocr=False, det=False, show_ad=False) with open("bg_with_notch.jpg", "rb") as f: notch_bytes = f.read() with open("bg_complete.jpg", "rb") as f: full_bytes = f.read() result = slide.slide_comparison(notch_bytes, full_bytes) # result == {"target": [x, y]} print(f"Gap position: x={result['target'][0]}, y={result['target'][1]}") ``` ``` -------------------------------- ### get_img_base64() / base64_to_image() Source: https://context7.com/sml2h3/ddddocr/llms.txt Utility functions for converting images between file paths, bytes, and base64 strings. These are particularly useful for preparing image data for API requests. ```APIDOC ## `get_img_base64()` / `base64_to_image()` — Image Utility Helpers Convenience functions exported at package level for converting between file paths, bytes, and base64 strings — useful when preparing images for the HTTP API. ```python from ddddocr import get_img_base64, base64_to_image # File → base64 string (for API payloads) b64 = get_img_base64("captcha.png") print(b64[:40]) # "iVBORw0KGgoAAAANSUhEUgAA..." # base64 string → PIL Image from PIL import Image img: Image.Image = base64_to_image(b64) print(img.size) # (200, 60) # Round-trip check import io, base64 as b64lib raw = b64lib.b64decode(b64) img2 = base64_to_image(b64lib.b64encode(raw).decode()) print(img2.size) ``` ``` -------------------------------- ### Docker Environment Variable Configuration Source: https://github.com/sml2h3/ddddocr/blob/master/README.md Reference for environment variables that can be used to configure the DdddOcr API service when running in Docker. ```APIDOC ### Docker Environment Variable Configuration Reference | Environment Variable | Default Value | Description | |---|---|---| | `DDDDOCR_HOST` | 0.0.0.0 (CLI default) / 127.0.0.1 (Direct run default) | API service host address | | `DDDDOCR_PORT` | 8000 | API service port | | `DDDDOCR_WORKERS` | 1 | Number of API service worker processes | | `DDDDOCR_OCR` | true | Whether to enable OCR functionality | | `DDDDOCR_DET` | false | Whether to enable object detection functionality | | `DDDDOCR_OLD` | false | Whether to use the old OCR model | | `DDDDOCR_BETA` | false | Whether to use the Beta version OCR model | | `DDDDOCR_USE_GPU` | false | Whether to use GPU acceleration | | `DDDDOCR_DEVICE_ID` | 0 | GPU device ID | | `DDDDOCR_SHOW_AD` | true | Whether to display advertisements | | `DDDDOCR_IMPORT_ONNX_PATH` | "" | Path to custom model | | `DDDDOCR_CHARSETS_PATH` | "" | Path to custom character set | ``` -------------------------------- ### Initialize DdddOcr with OCR Disabled Source: https://github.com/sml2h3/ddddocr/blob/master/ddddocr/README.md Initialize DdddOcr without OCR functionality, useful if only target detection or slider verification is needed. ```python import ddddocr ocr = ddddocr.DdddOcr(ocr=False) ```