Python 实现简单OCR文本识别

Ubuntu系统:22.04

python版本:3.9

安装依赖库:

bash 复制代码
# 安装Tesseract引擎和开发库
sudo apt update && sudo apt install tesseract-ocr libtesseract-dev

# 安装英语+中文语言包
sudo apt install tesseract-ocr-eng tesseract-ocr-chi-sim

# 安装Python依赖
pip install pytesseract pillow -i https://mirrors.aliyun.com/pypi/simple

代码实现:

python 复制代码
# 安装必要依赖(Ubuntu/Debian)
# 先执行以下终端命令:
# sudo apt update && sudo apt install tesseract-ocr libtesseract-dev
# sudo apt install tesseract-ocr-chi-sim  # 中文支持(可选)
# pip3 install pytesseract pillow

from PIL import Image
import pytesseract
import sys
import os

def ocr_core(image_path):
    """
    核心OCR函数
    :param image_path: 图片路径
    :return: 识别后的文本
    """
    try:
        if not os.path.exists(image_path):
            raise FileNotFoundError(f"文件 {image_path} 不存在")

        img = Image.open(image_path)
        
        # 多语言识别示例(英语+中文)
        text = pytesseract.image_to_string(img, lang='eng+chi_sim')
        
        return text.strip() if text else "未识别到文字"
    
    except Exception as e:
        return f"错误: {str(e)}"

if __name__ == "__main__":
    if len(sys.argv) > 1:
        image_path = sys.argv[1]
    else:
        image_path = input("请输入图片路径:").strip()
    
    print("\n识别中...")
    result = ocr_core(image_path)
    
    print("\n识别结果:")
    print("-" * 30)
    print(result)
    print("-" * 30)

下载测试图片:

bash 复制代码
# 下载测试图片(可选)
wget https://tesseract.projectnaptha.com/img/eng_bw.png -O test.png

# 执行识别
python ocr_demo.py test.png
相关推荐
Python图像识别1 小时前
71_基于深度学习的布料瑕疵检测识别系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
QX_hao2 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白2 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
千码君20162 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
淮北4943 小时前
windows安装minicoda
windows·python·conda
Evand J3 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
爱喝白开水a4 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
Neverfadeaway4 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
武子康4 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
杰克尼4 小时前
JavaWeb_p165部门管理
java·开发语言·前端