Google Colab中用Pdf2Image转PDF遇UnidentifiedImageError求助
解决Google Colab中pdf2image转换PDF时的UnidentifiedImageError
问题描述
在Google Colab使用pdf2image工具转换PDF为图片时触发错误:
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f241957a950>
此前相同代码运行正常,已尝试!sudo apt-get update、安装poppler-utils、改用convert_from_path等操作均无效,仅单独安装pdf2image相关依赖时可正常运行,怀疑与tesseract、PyPDF2等工具的安装存在依赖冲突。
使用代码:
from pdf2image import convert_from_bytes file = "/content/example.pdf" images = convert_from_bytes(open(file, 'rb').read(), size=800, dpi=800)
解决方案
1. 强制重装核心依赖
Colab环境中已安装的其他工具可能篡改了pillow(图片处理核心依赖)或pdf2image的版本,执行以下命令强制重装兼容版本:
!sudo apt-get install -y poppler-utils !pip install --force-reinstall pdf2image pillow==9.5.0
指定pillow固定版本可避免因版本更新导致的兼容性问题。
2. 明确指定poppler路径
部分情况下,poppler的路径未被正确识别,改用convert_from_path并显式指定poppler路径:
from pdf2image import convert_from_path file = "/content/example.pdf" # Colab中poppler默认安装路径为/usr/bin images = convert_from_path(file, size=800, dpi=800, poppler_path='/usr/bin')
3. 排查冲突依赖
逐步安装可疑工具,每次安装后测试转换功能,定位冲突源:
# 先测试基础环境是否正常 !pip uninstall -y pytesseract PyPDF2 # 测试转换代码,确认正常后再逐个安装 !pip install pytesseract PyPDF2 # 每安装一个工具就运行转换代码,找到导致错误的包后锁定兼容版本
4. 重置Colab运行时
如果以上方法无效,直接重置Colab运行时(菜单栏→Runtime→Factory reset runtime),重新安装必要依赖:
!sudo apt-get update !sudo apt-get install -y poppler-utils !pip install pdf2image
再运行转换代码,避免环境被其他无关依赖污染。
内容的提问来源于stack exchange,提问作者Notaginger
相关产品推荐
相关产品推荐

