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
相关推荐
先知后行。1 小时前
QT实现计算器
开发语言·qt
掘根1 小时前
【Qt】常用控件3——显示类控件
开发语言·数据库·qt
万粉变现经纪人3 小时前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip
西阳未落4 小时前
C++基础(21)——内存管理
开发语言·c++·面试
编程武士5 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao5 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
callJJ5 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
hsjkdhs6 小时前
万字详解C++之构造函数析构函数
开发语言·c++
Lin_Aries_04217 小时前
容器化简单的 Java 应用程序
java·linux·运维·开发语言·docker·容器·rpc
傻啦嘿哟7 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite