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"])
相关推荐
从零开始学习人工智能6 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
WWJA王文举7 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境7 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13147 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教7 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教8 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境8 小时前
FastAPI 的Admin面板生态
后端·python
qq_448011168 小时前
C语言中的动态内存分配
c语言·开发语言·php
ctlover9 小时前
Streamlit 框架
python
ι:9 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机