Skip to main content

Text extraction (Qwen-OCR)

Qwen-OCR is a visual understanding model that extracts text and structured data from images — scanned documents, tables, receipts, and more. It handles multiple languages and supports advanced OCR tasks: information extraction, table parsing, formula recognition, and document parsing.

Examples

Input imageRecognition result
Recognize multiple languagesimageINTERNATIONALMOTHER LANGUAGEDAYПривет!Hello!Bonjour!Merhaba!Ciao!Hello!Ola!בר מולדSalam!
Recognizing tilted imagesimageIntroductionThis product is made of Korean imported fiber. It does not shrink, deform, mold, breed bacteria, or damage item surfaces. It features true oil non-stick performance, strong water absorption, water immersion resistance, easy cleaning, non-toxicity, no residue, and quick drying.Shop owner experience: Stainless steel, ceramics, bathtubs, and overall bathrooms mostly have white, smooth surfaces. Surface stains are difficult to remove with other cleaning cloths, and cloths that are too sharp can easily leave scratches. With this simulated loofah cloth, dip it in a small amount of neutral detergent, rub out foam, and these surface stains can be easily wiped clean.6941990612023Item No.: 2023
Locating text positionsimg_1
The High-precision recognition task supports the text locating feature.
Visualized locating resultsimg_1_location
For more information, see the FAQ to draw the bounding boxes of each line of text on the original image.

Model selection

Qwen-OCR provides the following models. Select one based on your business requirements:
  • Qwen3.5-OCR: Built on the Qwen3.5 architecture, with comprehensive upgrades in document parsing, text locating, and key information extraction. Supports multi-turn conversations and PDF document parsing. Delivers significantly improved performance in extracting information from business certificates (ID cards, driver's licenses, etc.). For the supported certificate and receipt types, see Supported certificate and receipt types. Includes the qwen3.5-ocr model.
  • Qwen-VL-OCR: Built on the Qwen3-VL architecture, supports built-in tasks such as document parsing, text locating (high-precision recognition), information extraction, table parsing, formula recognition, general text recognition, and multilingual recognition, and supports image rotation correction. Includes the qwen-vl-ocr (stable) and qwen-vl-ocr-2025-11-20 models.
  • Early versions (not recommended): Their features and performance are inferior to the new versions. We recommend migrating to qwen3.5-ocr. Includes the qwen-vl-ocr-2024-10-28 model.
The qwen-vl-ocr model's max_tokens` parameter (Maximum Output) defaults to 4096. To increase this parameter to the 4097~8192 range, contact your business manager to apply and provide: the Alibaba Cloud account ID, image types (document images, e-commerce images, contracts, etc.), model name, expected QPS and total daily requests, and the proportion of requests with output lengths exceeding 4096.

Preparations

  • You have obtained an API Key and configured the API Key in environment variables.
  • If you use the OpenAI SDK or DashScope SDK, install the latest SDK version first. The minimum DashScope Python SDK version is 1.22.2, and the minimum Java SDK version is 2.21.8.
    • DashScope SDK
      • Advantages: Supports all advanced features such as image rotation correction and built-in OCR tasks, with complete functionality and simple calls.
      • Applicable Scenario: Projects that require the full feature set.
    • OpenAI-compatible SDK
      • Advantages: Projects that already use the OpenAI SDK or ecosystem tools can migrate quickly.
      • Limitations: Advanced features (image rotation correction and built-in OCR tasks) do not support direct calls through parameters. You must manually construct a Prompt for impersonation and parse the output results yourself.
      • Applicable Scenario: Projects with existing OpenAI integrations that do not rely on DashScope-specific advanced features.

QuickStart

The following example extracts key information from a train ticket image (URL) and returns it in JSON format. To pass in local files, see How to pass in local files; for image specification requirements, see Image limits.
  • OpenAI-compatible-Chat
  • OpenAI-compatible-Response
  • DashScope
Python
from openai import OpenAI
import os

PROMPT_TICKET_EXTRACTION = """
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"},
"""

try:
    client = OpenAI(
        # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
        # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  # 请将 {WorkspaceId} 替换为业务空间ID
    )
    completion = client.chat.completions.create(
        model="qwen-vl-ocr-2025-11-20",
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
                        # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                        "min_pixels": 32 * 32 * 3,
                        # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                        "max_pixels": 32 * 32 * 8192
                    },
                    # 模型支持在text字段中传入Prompt,若未传入,则会使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                    {"type": "text",
                     "text": PROMPT_TICKET_EXTRACTION}
                ]
            }
        ])
    print(completion.choices[0].message.content)
except Exception as e:
    print(f"错误信息: {e}")
{
  "choices": [{
    "message": {
      "content": "```json\n{\n    \"发票号码\": \"24329116804000\",\n    \"车次\": \"G1948\",\n    \"起始站\": \"南京南站\",\n    \"终点站\": \"郑州东站\",\n    \"发车日期和时间点\": \"2024年11月14日11:46开\",\n    \"座位号\": \"04车12A号\",\n    \"席别类型\": \"二等座\",\n    \"票价\": \"¥337.50\",\n    \"身份证号码\": \"4107281991****5515\",\n    \"购票人姓名\": \"读小光\"\n}\n```",
      "role": "assistant"
    },
    "finish_reason": "stop",
    "index": 0,
    "logprobs": null
  }],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 606,
    "completion_tokens": 159,
    "total_tokens": 765
  },
  "created": 1742528311,
  "system_fingerprint": null,
  "model": "qwen3.5-ocr",
  "id": "chatcmpl-20e5d9ed-e8a3-947d-bebb-c47ef1378598"
}

Calling built-in tasks

To simplify calls in specific scenarios, the models (except qwen-vl-ocr-2024-10-28) have a variety of tasks built in. Call Method:
  • DashScope SDK: Set the ocr_options parameter to call built-in tasks. Since qwen3.5-ocr, customized tasks are used in combination with user-defined Prompts (no longer forcibly overridden), and customized task results are returned through the ocr_result field. Earlier versions use a fixed Prompt internally.
  • OpenAI-compatible SDK: You must manually pass in the Prompt specified for the task.
The following table lists the task values, the specified Prompt, output format, and examples for each built-in task:
  • High-precision recognition
  • Information extraction
  • Table parsing
  • Document parsing
  • Formula recognition
  • General text recognition
  • Multilingual recognition
For the high-precision recognition task, we recommend using qwen-vl-ocr-2025-11-20 or later versions, or the latest model, which supports:
  • Text content recognition (extracting text)
  • Text position detection (locating text lines and outputting coordinates)
After obtaining the text bounding box coordinates, you can refer to the FAQ to draw the detection boxes onto the original image.
Value of taskSpecified promptOutput format and example
advanced_recognitionLocates all text lines and returns the coordinate results as rotated rectangles ([cx, cy, width, height, angle]).
  • Format: plain text, or a JSON object obtained directly from the ocr_result field
  • Examples:
{
  "output": {
    "choices": [
      {
        "message": {
          "content": [
            {
              "ocr_result": {
                "words_info": [
                  {
                    "rotate_rect": [398,153,134,27,90],
                    "text": "Magsafe"
                  },
                  {
                    "rotate_rect": [680,250,40,167,90],
                    "text": "金盾系列"
                  },
  • text: the text content of each line.
  • rotate_rect:
    • Example value: [center_x, center_y, width, height, angle]
    • Meaning: the rotated rectangle representation of the text box, where center_x and center_y are the coordinates of the text box center point, width is the width, height is the height, and angle is the rotation angle of the text box relative to the horizontal direction, with a value range of [-90, 90].
python
import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
            }]

response = dashscope.MultiModalConversation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为高精识别
    ocr_options={"task": "advanced_recognition"}
)
# 高精识别任务的文本与坐标结果从 ocr_result 字段中获取
print(response["output"]["choices"][0]["message"].content[0]["ocr_result"])
{
  "output":{
    "choices":[
      {
        "finish_reason":"stop",
        "message":{
          "role":"assistant",
          "content":[
            {
              "text":"```json\n[{\"pos_list\": [{\"rotate_rect\": [740, 374, 599, 1459, 90]}]}```",
              "ocr_result":{
                "words_info":[
                  {
                    "rotate_rect":[150,80,49,197,-89],
                    "text":"读者对象"
                  },
                  {
                    "rotate_rect":[724,171,34,1346,-89],
                    "text":"如果你是Linux环境下的系统管理员,那么学会编写shell脚本将让你受益匪浅。本书并未细述安装"
                  },
                  {
                    "rotate_rect":[745,216,34,1390,-89],
                    "text":"Linux系统的每个步骤,但只要系统已安装好Linux并能运行起来,你就可以开始考虑如何让一些日常"
                  },
                  {
                    "rotate_rect":[748,263,34,1394,-89],
                    "text":"的系统管理任务实现自动化。这时shell脚本编程就能发挥作用了,这也正是本书的作用所在。本书将"
                  },
                  {
                    "rotate_rect":[749,308,34,1395,-89],
                    "text":"演示如何使用shell脚本来自动处理系统管理任务,包括从监测系统统计数据和数据文件到为你的老板"
                  },
                  {
                    "rotate_rect":[123,354,33,146,-89],
                    "text":"生成报表。"
                  },
                  {
                    "rotate_rect":[751,432,34,1402,-89],
                    "text":"如果你是家用Linux爱好者,同样能从本书中获益。现今,用户很容易在诸多部件堆积而成的图形环境"
                  },
                  {
                    "rotate_rect":[755,477,31,1404,-89],
                    "text":"中迷失。大多数桌面Linux发行版都尽量向一般用户隐藏系统的内部细节。但有时你确实需要知道内部"
                  },
                  {
                    "rotate_rect":[752,523,34,1401,-89],
                    "text":"发生了什么。本书将告诉你如何启动Linux命令行以及接下来要做什么。通常,如果是执行一些简单任"
                  },
                  {
                    "rotate_rect":[747,569,34,1395,-89],
                    "text":"务(比如文件管理),在命令行下操作要比在华丽的图形界面下方便得多。在命令行下有大量的命令"
                  },
                  {
                    "rotate_rect":[330,614,34,557,-89],
                    "text":"可供使用,本书将会展示如何使用它们。"
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  },
  "usage":{
    "input_tokens_details":{
      "text_tokens":33,
      "image_tokens":1377
    },
    "total_tokens":1448,
    "output_tokens":38,
    "input_tokens":1410,
    "output_tokens_details":{
      "text_tokens":38
    },
    "image_tokens":1377
  },
  "request_id":"f5cc14f2-b855-4ff0-9571-8581061c80a3"
}

PDF document parsing

qwen3.5-ocr supports passing PDF files directly for document parsing through the Response API, so there is no need to manually split the PDF into images, and the output length is not limited by the model's maximum output length, so long documents can be parsed in full. Only Response API calls are supported; Chat API is not supported. PDF file limits: no more than 100 MB; the page limit depends on the task in ocr_options — up to 50 pages when it is set to document_parsing, and up to 10 pages when task is not set or is set to another task. The following examples use the Response API to pass PDF files for document parsing.
Python
import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.5-ocr",
    input=[{
        "role": "user",
        "content": [{
            "type": "input_file",
            "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
        }]
    }],
    extra_body={
        "ocr_options": {"task": "document_parsing"}
    }
)

# 获取定制任务结果
print(response.output[0].content[0].ocr_result)
For earlier models (qwen-vl-ocr-2025-11-20 and before) that do not support the Response API, use an image processing library such as Python's pdf2image to convert each PDF page to an image, and then use the multi-image input method for page-by-page recognition.
For more usages of the OpenAI Responses API (such as retrieving and managing completed model responses), see OpenAI compatible - Responses.

Pass a local file (Base64 encoding or file path)

Upload local files using Base64 encoding or a direct file path. Select the method based on file size and SDK type — see How to select a file upload method. Both methods must meet the file requirements in Image limits.
  • Use Base64 encoding
  • Use file path
Convert the file to a Base64-encoded string, and then pass it to the model. This method is suitable for OpenAI and DashScope SDKs, and HTTP requests.
  1. Encode the file: Convert the local image to a Base64-encoded string.
    #  编码函数: 将本地文件转换为 Base64 编码的字符串
    def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    
    # 将xxxx/eagle.png替换为你本地图像的绝对路径
    base64_image = encode_image("xxx/eagle.png")
    
  2. Construct a Data URL in the following format: data:[MIME_type];base64,{base64_image}.
    1. Replace MIME_type with the actual media type. Make sure that the type matches the MIME Type value in the Image limits table, such as image/jpeg or image/png.
    2. base64_image is the Base64-encoded string generated in the previous step.
  3. Call the model: Pass the Data URL using the image or image_url parameter to call the model.
  • Pass a file path
  • Pass a Base64-encoded string
Passing a file path is supported only for calls made with the DashScope Python and Java SDKs. This method is not supported for DashScope HTTP or OpenAI-compatible methods.
Python
import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

# 将xxxx/test.jpg替换为您本地图像的绝对路径
local_path = "xxx/test.jpg"
image_path = f"file://{local_path}"
messages = [
    {
        "role": "user",
        "content": [
            {
                "image": image_path,
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
            },
            # 模型在未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
            {
                "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"
            },
        ],
    }
]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-vl-ocr-2025-11-20",
    messages=messages,
)
print(response["output"]["choices"][0]["message"].content[0]["text"])

More usages

Limitations

Image limits

  • Dimensions and aspect ratio: The image width and height must both be greater than 10 pixels. The aspect ratio must not exceed 200:1 or 1:200.
  • Total pixels: The model automatically scales images, so there is no strict limit on the total number of pixels. However, an image cannot exceed 15.68 million pixels.
  • Supported image formats
    • For images with a resolution below 4K (3840x2160), the following formats are supported:

      Image format

      Common extensions

      MIME Type

      BMP

      .bmp

      image/bmp

      JPEG

      .jpe, .jpeg, .jpg

      image/jpeg

      PNG

      .png

      image/png

      TIFF

      .tif, .tiff

      image/tiff

      WEBP

      .webp

      image/webp

      HEIC

      .heic

      image/heic

    • For images with a resolution from 4K(3840x2160) to 8K(7680x4320), only the JPEG, JPG, and PNG formats are supported.
  • Image size:
    • Public URLs and local paths: a single image must not exceed 20MB for qwen3.5-ocr, and 10MB for other versions.
    • Base64 encoding: the encoded string must not exceed 10MB.
    See also: How do I compress an image or video to the required size? .

Model limits

  • System Message: Qwen-OCR does not support custom System Message. The model uses a fixed System Message internally, and all instructions must be passed in through the User Message.
  • Multi-turn: Multi-turn conversations are supported starting from qwen3.5-ocr, and you can ask pure text follow-up questions without passing in an image URL. qwen-vl-ocr-2025-11-20 and earlier versions only process the latest message and do not retain context.
  • Hallucination risk: When the text in the image is too small or the resolution is low, the model may produce hallucinations. For questions not related to text extraction, the accuracy of the model is not guaranteed.
  • Cannot process text files:
    • For files that contain image data, follow the recommendations in Going live to transform them into an image sequence before processing.
    • For files with plain text or structured data, use Qwen-Long, a model that can parse long text.

Supported certificate and document types

The information extraction task supports structured data extraction from the following certificates, receipts, and permits.
  • Passports and travel documents: Chinese passport, Macau passport, Mainland Travel Permit for Hong Kong and Macau Residents, Mainland Travel Permit for Taiwan Residents, and Home Return Permit for Hong Kong and Macau Residents.
  • Vehicle documents and sales invoices: driver's license, vehicle nameplate, vehicle certificate of conformity, vehicle registration certificate, motor vehicle sales invoice, and used vehicle sales invoice.
  • Invoices and tax receipts: VAT ordinary invoice (roll), fixed-amount special invoice, general machine-printed invoice, tax payment certificate, and central non-tax revenue receipt.
  • Transportation receipts: 12306 high-speed rail ticket, train ticket, boat ticket, expressway toll receipt, and expressway machine-printed invoice.
  • Financial cards and receipts: credit card, electronic bank acceptance bill, payment receipt, and social security card.
  • Business licenses and permits: business license, food business license, food production license, pharmaceutical business license, and medical device business license.
  • Real estate certificate: real estate ownership certificate.
  • International ID cards: Hong Kong ID, Macau ID, Indonesian ID, Thai ID, Vietnamese ID, Malaysian ID, Philippine ID, Indian ID, Turkish ID, Pakistani ID, Mexican ID, UK ID, and US ID.
  • International passports and driver's licenses: Indian passport, Singapore passport, Thai passport, US passport, Australian passport, UAE passport, Philippine driver's license, Japanese driver's license, and US driver's license.

Billing and rate limiting

  • Billing: Qwen-OCR is a multimodal model. The total cost is calculated as follows: (Number of input tokens × Unit price for input) + (Number of output tokens × Unit price for output). View bills or top up your account in the Expenses and Costs console.
    • Calculating image tokens: Use the following code to estimate image token usage. Actual billing is based on the API response.
      Formula: Image tokens = (h_bar * w_bar) / token_pixels + 2.
      • h_bar * w_bar represents the dimensions of the scaled image. The model pre-processes the image by scaling it to a specific pixel limit. This limit depends on the value of the max_pixels parameter.
      • token_pixels represents the pixel value per Token.
        • For qwen3.5-ocr, qwen-vl-ocr, and qwen-vl-ocr-2025-11-20, this value is fixed at 32*32 (which is 1024).
        • For other models, this value is fixed at 28*28 (which is 784).
      This code demonstrates the approximate image scaling logic the model uses. Use it to estimate token count for an image. Actual billing is based on the API response.
      import math
      from PIL import Image
      
      def smart_resize(image_path, min_pixels, max_pixels):
          """
          对图像进行预处理。
      
          参数:
              image_path:图像的路径
          """
          # 打开指定的PNG图片文件
          image = Image.open(image_path)
      
          # 获取图片的原始尺寸
          height = image.height
          width = image.width
          # 将高度调整为28或32的整数倍
          h_bar = round(height / 32) * 32
          # 将宽度调整为28或32的整数倍
          w_bar = round(width / 32) * 32
      
          # 对图像进行缩放处理,调整像素的总数在范围[min_pixels,max_pixels]内
          if h_bar * w_bar > max_pixels:
              beta = math.sqrt((height * width) / max_pixels)
              h_bar = math.floor(height / beta / 32) * 32
              w_bar = math.floor(width / beta / 32) * 32
          elif h_bar * w_bar < min_pixels:
              beta = math.sqrt(min_pixels / (height * width))
              h_bar = math.ceil(height * beta / 32) * 32
              w_bar = math.ceil(width * beta / 32) * 32
          return h_bar, w_bar
      
      # 将xxx/test.png替换为您本地的图像路径
      h_bar, w_bar = smart_resize("xxx/test.png", min_pixels=32 * 32 * 3, max_pixels=8192 * 32 * 32)
      print(f"缩放后的图像尺寸为:高度为{h_bar},宽度为{w_bar}")
      
      # 计算图像的Token数:总像素除以32 * 32
      token = int((h_bar * w_bar) / (32 * 32))
      
      # <|vision_bos|> 和 <|vision_eos|> 作为视觉标记,每个需计入 1个Token
      print(f"图像的总Token数为{token + 2}")
      
  • Rate limits: For the rate limit rules of Qwen-OCR models, see Rate limits
  • Free quota (Singapore region only): Within 90 days from the date of activating Model Studio or of the model application being approved, Qwen-OCR provides a free quota of 1 million tokens.

Going live

  • Image pre-processing:
    • Ensure that input images are clear, evenly lit, and not overly compressed:
      • Store and transmit images in a lossless format (e.g., PNG) to avoid information loss.
      • To improve image definition, use denoising algorithms, such as mean or median filtering, to smooth noisy images.
      • To correct uneven lighting, use algorithms such as adaptive histogram equalization to adjust brightness and contrast.
    • Skewed images: Set enable_rotate: true in the DashScope SDK to correct rotation before recognition.
    • Very small or very large images: Use min_pixels and max_pixels to control image scaling.
      • min_pixels: ensures that details remain recognizable after small images are enlarged. Keep the default value.
      • max_pixels: prevents oversized images from consuming too many tokens. The default value works for most scenarios. If small text is not recognized clearly, you can increase max_pixels appropriately, but this increases token consumption.
  • Result verification: Model recognition results may contain errors. For critical business scenarios, it is recommended to add a manual review step or introduce format verification rules (such as ID card number or bank card number verification).
  • Batch calls: For large-scale, non-real-time scenarios, you can use the Batch API to process batch tasks asynchronously to reduce call costs.

FAQ

Choose the best upload method based on the SDK type, file size, and network stability.

Type

Specifications

DashScope SDK(Python、Java)

OpenAI compatible / DashScope HTTP

Image

Greater than 7 MB and less than 10 MB

Pass the local path

Only public URLs are supported. We recommend using Alibaba Cloud Object Storage Service

Less than 7 MB

Pass the local path

Base64 encoding

Base64 encoding increases the data size. The original file size must be less than 7 MB.
Using a local path or Base64 encoding helps prevent server-side download timeouts and improves stability.
After obtaining the text localization results output by the model, follow the draw_bbox.py code to draw the detection boxes and labels onto the original image.
When using qwen3.5-ocr, if a custom Prompt contains a complete HTML structure (for example, <html><body>...</body></html>), the model may follow that structure and return the OCR results in HTML format instead of plain text, in which case the returned content may appear to be empty or to contain front-end tags. Including only simple tags (for example, a single <br>) does not trigger this behavior.To resolve this issue, use one of the following methods:
  • Check whether the Prompt contains a complete HTML tag structure. If so, retry with plain text instructions. For example, change <html><body>请提取图片中的所有文字</body></html> to Please extract all text from the image.
  • If you are not sure whether the Prompt affects the output format, you can omit the text field and use the model's default Prompt.
  • Switch to the qwen3.7-plus model, which still returns plain text results when given the same Prompt with an HTML structure.

API reference

For the input and output parameters of Qwen-OCR, see Qwen-OCR API reference.

Error codes

If the model call fails and returns an error message, see Error codes for resolution.