python识别图片中的文本保存到word中

python可以使用第三方库pytesseract实现图像的文本识别,并将识别的结果保存到word中,代码本生不复杂pytesseract环境有点麻烦这里整理总结一下

一、简介

Tesseract是一个 由HP实验室开发 由Google维护的开源的光学字符识别(OCR)引擎,可以在 Apache 2.0 许可下获得。它可以直接使用,或者(对于程序员)使用 API​​ 从图像中提取输入,包括手写的或打印的文本。

二、包安装

复制代码
pip install pytesseract

三、代码

复制代码
import pytesseract
from PIL import Image
from docx import Document


def convert_image_to_editable_docx(image_file, docx_file):
    # 读取图片并进行OCR识别
    image = Image.open(image_file)
    # 使用pytesseract调用image_to_string方法进行识别,传入要识别的图片,lang='chi_sim'是设置为中文识别,
    text = pytesseract.image_to_string(image, lang='chi_sim')

    # 创建Word文档并插入文本
    doc = Document()
    doc.add_paragraph(text)
    doc.save(docx_file)

# 示例用法
input_image = "1.png"   # 输入图片文件路径
output_docx = "output.docx"   # 输出Word文档路径

convert_image_to_editable_docx(input_image, output_docx)

不安装环境运行代码会报错:pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.

四、Tesseract的常用网址

下载地址:https://digi.bib.uni-mannheim.de/tesseract/

官方网站:https://github.com/tesseract-ocr/tesseract

官方文档:https://github.com/tesseract-ocr/tessdoc

语言包地址:https://github.com/tesseract-ocr/tessdata

语言包国内地址:https://gitcode.com/mirrors/tesseract-ocr/tessdata/tree/main?utm_source=csdn_github_accelerator\&isLogin=1

五、安装

我下载的是:tesseract-ocr-w64-setup-v5.1.0.20220510.exe

我的安装地址是:D:\Program Files\Tesseract-OCR

六、设置环境变量

path中添加

新增:TESSDATA_PREFIX

下载语言包:语言包国内地址:https://gitcode.com/mirrors/tesseract-ocr/tessdata/tree/main?utm_source=csdn_github_accelerator\&isLogin=1

下载如下这几个包,放到D:\Program Files\Tesseract-OCR\tessdata

七、验证环境变量

1.查看是否安装成功

打开cmd,输入tesseract -v回车,若显示版本号即为安装成功。

2.查看已经安装的语言

在cmd中输入tesseract --list-langs回车,若显示版本号即为安装成功。

八、效果

1.png图片

识别后的效果

相关推荐
摸鱼仙人~19 分钟前
一文详解 Python 密码哈希库 Passlib
开发语言·python·哈希算法
大飞记Python1 小时前
当GitHub不再纯粹:Python自动化测试的未来是AI还是危机?
python·github
eqwaak01 小时前
Matplotlib 动画显示进阶:交互式控制、3D 动画与未来趋势
python·tcp/ip·3d·语言模型·matplotlib
GilgameshJSS1 小时前
【学习K230-例程23】GT6700-音频FFT柱状图
python·学习·音视频
I'm a winner1 小时前
第七章:AI进阶之------输入与输出函数(一)
开发语言·人工智能·python·深度学习·神经网络·microsoft·机器学习
ERP老兵_冷溪虎山2 小时前
Python/JS/Go/Java同步学习(第十三篇)四语言“字符串转码解码“对照表: 财务“小南“纸式转码术处理凭证乱码崩溃(附源码/截图/参数表/避坑指南)
java·后端·python
独行soc3 小时前
2025年渗透测试面试题总结-67(题目+回答)
网络·python·安全·web安全·网络安全·adb·渗透测试
eybk3 小时前
用python的socket写一个局域网传输文件的程序
服务器·网络·python
程序员的世界你不懂3 小时前
【Flask】实现一个前后端一体的项目-脚手架
后端·python·flask
花酒锄作田4 小时前
[MCP][01]简介与概念
python·llm·mcp