You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Google Vision OCR更改标注特性并指定语言提示?

解决方法

text_detection是Google Cloud Vision SDK提供的便捷封装方法,默认使用DOCUMENT_TEXT_DETECTION特性,且不支持自定义参数。要指定TEXT_DETECTION特性并添加语言提示,需要使用更灵活的annotate_image方法,手动构建检测请求的参数。

修改后的完整函数如下:

def detect_text(path):
    """Detects text in the file using TEXT_DETECTION with language hints."""
    from google.cloud import vision
    import io
    client = vision.ImageAnnotatorClient()

    with io.open(path, 'rb') as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    # 指定要使用的TEXT_DETECTION特性
    feature = vision.Feature(
        type_=vision.Feature.Type.TEXT_DETECTION
    )

    # 设置语言提示,比如中文、英文,可添加多个
    image_context = vision.ImageContext(
        language_hints=['zh-CN', 'en']
    )

    # 构建检测请求并调用API
    response = client.annotate_image(
        request={
            'image': image,
            'features': [feature],
            'image_context': image_context
        }
    )

    texts = response.text_annotations
    # 处理API返回错误
    if response.error.message:
        raise Exception(
            '{}\n'.format(response.error.message)
        )
    return texts

关键参数说明

  • Feature.type_: 设置为vision.Feature.Type.TEXT_DETECTION,明确指定使用短文本检测特性,适合自然场景中的零散文本(如路牌、海报文字);若需处理排版规范的文档,可切换回DOCUMENT_TEXT_DETECTION。
  • ImageContext.language_hints: 传入语言代码列表(如zh-CN代表简体中文,en代表英文),提示API优先识别指定语言,能有效提升特定语言文本的识别准确率。

内容的提问来源于stack exchange,提问作者Tom Tolland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:05:21