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

在Google Colab使用pytesseract.image_to_data时遇KeyError: 'PNG'求助

解决pytesseract.image_to_data抛出KeyError: 'PNG'的问题

问题根源

该错误通常是因为pytesseract版本与Pillow(PIL)版本不兼容,旧版pytesseract(如0.3.9)在处理cv2生成的numpy数组图像时,调用PIL的save方法会出现参数不匹配或格式识别异常。

可行修复方案

1. 降级Pillow至兼容版本

pytesseract 0.3.9与Pillow 8.x版本兼容性更佳,执行以下命令降级:

!pip install pillow==8.4.0

完成后重新运行原代码即可。

2. 手动转换图像为PIL格式

直接传入cv2的numpy数组可能触发临时文件保存错误,手动将图像转为PIL Image对象后再传入pytesseract:

import cv2
from pytesseract import Output
from PIL import Image
import pytesseract

image = cv2.imread('/content/sample_data/0003.jpg')
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 转换为PIL Image格式
pil_image = Image.fromarray(rgb)
results = pytesseract.image_to_data(pil_image, output_type=Output.DICT)

3. 升级pytesseract至最新版本

新版本pytesseract修复了大量兼容性问题,执行升级命令后无需修改原代码:

!pip install --upgrade pytesseract

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:31:00