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"])
相关推荐
破茧蝴蝶2 小时前
Python分布式爬虫完整教程
开发语言·python
benchmark_cc3 小时前
量化系统架构设计:为什么应该将数据获取与策略逻辑解耦?
python·数据分析·pandas·量化交易·股票数据·quantdash
狗凯之家源码网3 小时前
全新 PHP 轻量客服聊天室源码深度评测
开发语言·php·聊天室系统
凤山老林3 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
小白快快跑哦3 小时前
python-字符串全解(六):正则表达式-逻辑运算或
python·正则表达式·字符串·逻辑运算
远离UE43 小时前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
keyipatience3 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
Thinker QAQ3 小时前
并发编程(九):BlockingQueue 与 Channel——语言层的原子性、可见性与有序性
java·python·go·并发编程·channel·blockingqueue·message passing
道满科技4 小时前
Function Calling 参数总出错?只修参数就行
linux·windows·python
栈帧之外4 小时前
【C++】STL之set
开发语言·c++