Python3开发快速获取图片的文字

在 Python 3 中,快速获取图片中的文字(OCR) ​ 最成熟、最省事的做法是直接使用 Tesseract OCR 。下面给你一套从零到可用的方案,兼顾速度和准确率。

一、安装依赖

1️、安装 Tesseract OCR

Windows

下载:https://github.com/UB-Mannheim/tesseract/wiki

安装后记住路径,例如:

复制代码
C:\Program Files\Tesseract-OCR\tesseract.exe

Linux

复制代码
sudo apt install tesseract-ocr

macOS

复制代码
brew install tesseract

验证:

复制代码
tesseract --version

2️、安装 Python 库
复制代码
pip install pytesseract pillow

二、最简示例(5 行代码)

复制代码
import pytesseract
from PIL import Image

text = pytesseract.image_to_string(Image.open("test.png"), lang="chi_sim+eng")
print(text)

✅ 支持:

  • 中文:chi_sim

  • 英文:eng

  • 中英混合:chi_sim+eng


三、中文识别必须做的事

安装中文语言包
  • Windows:安装时勾选 Chinese

Linux:

复制代码
sudo apt install tesseract-ocr-chi-sim

✅ 提高准确率的关键技巧(很重要)

1️、灰度 + 二值化

复制代码
from PIL import Image

img = Image.open("test.png").convert("L")
img = img.point(lambda x: 0 if x < 140 else 255)
print(pytesseract.image_to_string(img))

2️、指定页面分割模式(PSM)

复制代码
custom_config = r'--oem 3 --psm 6'
text = pytesseract.image_to_string(img, config=custom_config)

常用 PSM:

  • 3:自动分页(默认)

  • 6:统一文本块

  • 7:单行文本

  • 11:稀疏文本


3️、Windows 指定 Tesseract 路径

复制代码
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

✅ 批量识别图片

复制代码
import os

for f in os.listdir("images"):
    if f.endswith(".png"):
        text = pytesseract.image_to_string(Image.open(f"images/{f}"))
        print(f, text.strip())

✅ 获取文字位置(做标注 / 审核)

复制代码
data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
print(data["text"])
print(data["left"])
print(data["top"])
相关推荐
2601_9622992425 分钟前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
2601_9620715739 分钟前
【Java报错已解决】org.springframework.beans.factory.BeanCreationException
java·开发语言
学术 学术 Fun1 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
淡海水2 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
2601_962100542 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
CS_Zero2 小时前
C语言sizeof是函数吗?
c语言·开发语言
二进制漫游记3 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-3 小时前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_962381584 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261354 小时前
如何使用 Python 从 Word 文档中提取图片
python