Python-OCR-Study

Python OCR相关环境的安装以及搭建。
主要用到的是pytesseract。

pytesseract

理论上python3.8及以上就可以了。

  • 安装
  • 脚本相关运行

安装

Index of /tesseract (uni-mannheim.de)
选择最新的进行下载,相对各个库都会下载到最新的版本。

! 安装过程中需要把中文的训练模型进行下载,最好就是把中文简体相关等下载下来。
! 需要配置环境变量

  • Path中添加..\Tesseract-OCR
    • 用户变量
    • 系统变量
  • 新建变量名TESSDATA_PREFIX
    • 系统变量

打开命令行界面,运行tesseract -v,如果能正常显示安装的tesseract的版本信息,即说明安装成功。

不知道为啥,有时候把环境搭建好了稍微处理一下就又无法运行了,目前没什么合适的解决方式,直接卸载重新装tesseract,然后再把对应的训练模型进行下载。

英文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import cv2  
import pytesseract
import os

# 配置pytesseract
pytesseract.pytesseract.tesseract_cmd = 'D:\\Tesseract-OCR\\tesseract.exe' # 修改为你的tesseract安装路径

# 读取图片文件夹
image_folder = 'test'

# 获取文件列表
image_files = [f for f in os.listdir(image_folder) if os.path.isfile(os.path.join(image_folder, f))]

# 处理图片并保存结果
with open('ocr_results_en.txt', 'w') as f:
for file_name in image_files:
file_path = os.path.join(image_folder, file_name)

# 读取图片
image = cv2.imread(file_path)

# 使用Tesseract进行OCR识别
text = pytesseract.image_to_string(image, lang='eng')

# 写入结果到文件
f.write(f"File: {file_name}\n")
f.write(f"Text: {text}\n")
f.write("\n")

中文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import cv2  
import pytesseract
import os

# 配置pytesseract
pytesseract.pytesseract.tesseract_cmd = 'D:\\Tesseract-OCR\\tesseract.exe' # 修改为你的tesseract安装路径

# 读取图片文件夹
image_folder = 'test'

# 获取文件列表
image_files = [f for f in os.listdir(image_folder) if os.path.isfile(os.path.join(image_folder, f))]

# 处理图片并保存结果
with open('ocr_results_zh.txt', 'w', encoding='utf-8') as f:
for file_name in image_files:
file_path = os.path.join(image_folder, file_name)

# 读取图片
image = cv2.imread(file_path)

# 使用Tesseract进行OCR识别
text = pytesseract.image_to_string(image, lang='chi_sim')

# 写入结果到文件
f.write(f"File: {file_name}\n")
f.write(f"Text: {text}\n")
f.write("\n")
# 默认保存编码为gbk的,如果需要转换常用编码utf8的,直接在写入到新文件中以utf-8的编码保存即可。

Paddle

安装

1
2
pip install paddleocr -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
pip install paddle -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

理论上直接按照这种进行pip安装即可。

但是安装paddle会出现 error: subprocess-exited-with-error报错,意思说是subprocess模块啥的安装失败。

emmm

坑:shapely 的版本必须必须必须是 1.7.1 ,不能比这高!!!requirements.txt 也没有这个提示。如果比这个版本高,不会正常运行,而且还不会报错,而是返回 ‘退出代码为 -1073741819 (0xC0000005) 的字样’。 泪奔了,找了2天终于解决了…

原文链接:https://blog.csdn.net/Fan_shine/article/details/123089196

Win10 CPU环境,OSError: [WinError 126] 找不到指定的模块 · Issue #212 · PaddlePaddle/PaddleOCR · GitHub

shapely,下载地址:

Links for shapely (tsinghua.edu.cn)

-------------THE END-------------