Mac下Python用Tesseract读图片报Unsupported image object错误求助
TypeError: Unsupported image object 报错解决指南 核心报错原因
这个报错本质是pytesseract不认你传入的图像对象,常见触发场景就两类:
- 图像读取失败,实际传进去的是空值
None - 版本兼容问题:部分pytesseract版本无法直接识别OpenCV读取返回的numpy数组格式的图像对象
分步排查与解决方法
- 第一步:先验证图像读取是不是成功了
在调用image_to_string前加一行打印语句print(type(img)),如果输出是<class 'NoneType'>,说明压根没读到图:把图像路径换成绝对路径,同时去掉路径里的中文、空格、特殊字符,确认对应的jpeg/png文件确实存在于写的路径位置。 - 第二步:解决格式适配问题
pytesseract原生最稳的输入格式是PIL.Image对象,直接传OpenCV的结果很容易触发兼容报错,常用的改写方案有两种:- 保留OpenCV读取逻辑,手动完成格式转换
import cv2 import pytesseract from PIL import Image # Mac下Homebrew安装的Tesseract默认在这个路径,手动指定避免pytesseract找不到程序触发的校验报错 pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract' img = cv2.imread('image.png') # OpenCV默认读出来是BGR通道,转成RGB再转成PIL支持的对象格式 img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(img_rgb) text = pytesseract.image_to_string(pil_img) print(text) - 直接用PIL读图像,跳过OpenCV的适配环节
import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract' img = Image.open('image.png') text = pytesseract.image_to_string(img) print(text)
- 保留OpenCV读取逻辑,手动完成格式转换
内容的提问来源于stack exchange,提问作者Yogi
相关产品推荐
相关产品推荐

