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"])
相关推荐
geovindu1 小时前
go:Backtracking Algorithm
开发语言·后端·算法·golang·回溯算法
FriendshipT1 小时前
Ultralytics:解读Proto模块
人工智能·pytorch·python·深度学习·目标检测
zhiSiBuYu05172 小时前
Python3 循环语句新手实战指南
python
ShirleyWang0122 小时前
Day02 K3s NGF(Nginx Gateway Fabric)单 Worker 环境网关更新与故障处置 SOP
linux·服务器·python·k8s·k3s
ZDQNFU2 小时前
ORM之SQLAlchemy教程
后端·python
lzhdim2 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
Irene19912 小时前
Oracle PL/SQL Developer 版本差异(11g、14)实战总结
java·开发语言
jeffzhengye2 小时前
Claude-Real-Video:让 Claude 真正看懂视频,0 Token 成本
python·微信
qq_448011162 小时前
C语言中的getchar()
c语言·开发语言