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

在Python中使用Tesseract OCR出现AttributeError: 'dict'无'mode'属性错误求因

问题

计划在Google Colab环境中从本地导入图像,使用Tesseract OCR识别图像字符,编写的代码如下:

!apt install tesseract-ocr libtesseract-dev tesseract-ocr-jpn
!pip install pyocr

from PIL import Image
import pyocr
import cv2
from google.colab.patches import cv2_imshow

from google.colab import files
uploaded=files.upload()

tools=pyocr.get_available_tools()
print(tools)
tool=tools[0]
print(tool.get_name())

txt1 = tool.image_to_string(
uploaded,
lang='jpn+eng',
builder=pyocr.builders.TextBuilder(tesseract_layout=6)
)

运行后出现错误:AttributeError: 'dict' object has no attribute 'mode',完整错误栈如下:

AttributeError                            Traceback (most recent call last)
<ipython-input-38-2ad0a8585335> in <module>
      2     uploaded,
      3     lang='jpn+eng',
----> 4     builder=pyocr.builders.TextBuilder(tesseract_layout=6)
      5     )
      6 help(dict.items)

/usr/local/lib/python3.7/dist-packages/pyocr/tesseract.py in image_to_string(image, lang, builder)
    362         builder = builders.TextBuilder()
    363     with tempfile.TemporaryDirectory() as tmpdir:
--> 364         if image.mode != "RGB":
    365             image = image.convert("RGB")
    366         image.save(os.path.join(tmpdir, "input.bmp"))
AttributeError: 'dict' object has no attribute 'mode'

已搜索类似'dict' object has no attribute '~'错误案例,但未找到涉及'mode'属性的情况,请问该错误产生的原因是什么?


错误原因

tool.image_to_string()方法要求传入PIL Image对象(或兼容的图像实例),但你传入的uploaded是字典类型——files.upload()的返回值是一个字典,键为上传文件的文件名,值为文件的二进制数据,并非可直接处理的图像对象。

报错中的mode是PIL Image对象的属性,用于标识图像色彩模式(如RGB、灰度等),字典自然没有这个属性,因此触发AttributeError。


修复方案

需要从uploaded字典中提取文件二进制数据,通过PIL.Image.open()转换成Image对象后再传入OCR方法。修改后的完整代码如下:

!apt install tesseract-ocr libtesseract-dev tesseract-ocr-jpn
!pip install pyocr

from PIL import Image
import pyocr
import io  # 导入io模块处理二进制流
from google.colab import files

uploaded = files.upload()

# 获取上传的第一个文件(若上传多个可循环处理)
file_name = next(iter(uploaded.keys()))
image = Image.open(io.BytesIO(uploaded[file_name]))

tools = pyocr.get_available_tools()
tool = tools[0]

txt1 = tool.image_to_string(
    image,
    lang='jpn+eng',
    builder=pyocr.builders.TextBuilder(tesseract_layout=6)
)

print(txt1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:45:36