IT俱乐部 Python 使用Python实现pdf转图片再进行OCR识别

使用Python实现pdf转图片再进行OCR识别

1.先pdf转图片

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
from pdf2image import convert_from_path
 
# PDF文件路径
pdf_path = '/Users/xxx/2022.pdf'
# 输出图片的文件夹
output_folder = './output_images2022'
# 输出图片的命名格式
output_name = 'page'
 
# 如果输出文件夹不存在,创建它
if not os.path.exists(output_folder):
    os.makedirs(output_folder)
 
# 将PDF转换为图像列表,设置分辨率为300 DPI
images = convert_from_path(pdf_path, dpi=300)
 
# 保存每一页为PNG图片
for i, image in enumerate(images):
    image.save(f'{output_folder}/{output_name}_{i+1}.png', 'PNG')

2.OCR识别

示例代码

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from PIL import ImageEnhance
import pytesseract
from PIL import Image
from openpyxl import Workbook
 
# 配置 Tesseract 的路径(如果需要)
# pytesseract.pytesseract.tesseract_cmd = r'/usr/local/bin/tesseract'  # Mac 的路径
# pytesseract.pytesseract.tesseract_cmd = r'C:Program FilesTesseract-OCRtesseract.exe'  # Windows 的路径
 
# 打开图片
# image_path = "/Users/xxx/page_3.png"  # 替换为你的图片路径
 
 
def enhance_image(img):
    img = img.convert('L'# 转灰度
    img = ImageEnhance.Contrast(img).enhance(2.0)
    return img
 
 
def allimngs(image_path):
 
    image = Image.open(image_path)
 
    image = enhance_image(image)
 
    # 使用 pytesseract 进行 OCR
    text = pytesseract.image_to_string(image, lang="chi_sim"# 中文
 
    # # 打印提取的文本
    # print("提取的文本:")
    # print(text.replace(' ', ''))
 
    return text.replace(' ', '')
 
 
# 统计子字符串出现次数
 
class TrieNode:
    def __init__(self):
        self.children = {}
        self.keywords = []
 
 
class Trie:
    def __init__(self):
        self.root = TrieNode()
 
    def insert(self, keyword):
        node = self.root
        for char in keyword:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.keywords.append(keyword)
 
 
def count_keywords(text, keywords):
    # 去重关键词以确保唯一性
    keywords = list(set(keywords))
 
    # 构建Trie树
    trie = Trie()
    for kw in keywords:
        trie.insert(kw)
 
    # 初始化计数器
    counters = {kw: 0 for kw in keywords}
    i = 0
    n = len(text)
 
    while 0:
            # 更新所有匹配的关键词计数器
            for kw in current_node.keywords:
                counters[kw] += 1
            i = end_pos  # 跳跃到已匹配部分的末尾
        else:
            i += 1  # 无匹配,移动到下一个字符
 
    return counters
 
 
if __name__ == "__main__":
    keywords = ['矮小',
                '安于现状',
                '暗藏',
                '暗淡',
                '暗黑']
    all_text = ''
    workbook = Workbook()
    sheet = workbook.active
 
    for i in range(108):
        i = i+1
        image_path = f"/Users/xxx/output_images2022/page_{i}.png"
        all_text = all_text + allimngs(image_path)
 
    all_text = all_text.replace(' ', '').replace('n', '')
 
    result = count_keywords(all_text, keywords)
 
    num = 1
 
    for k, v in result.items():
        sheet[f'A{num}'] = k
        sheet[f'B{num}'] = v
        print(k, v, num)
        num = num + 1
 
    workbook.save(filename='2022.xlsx')

3.知识补充

Python中图片与pdf识别文本的OCR方法

1、PaddleOCR:

基于百度飞桨框架开发,模型丰富,支持多语言识别,包括中文、英文等。性能强大,适合复杂场景的文字识别

安装 PaddleOCR 库:

1
pip install paddleocr

示例代码

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
30
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
  
# 初始化 PaddleOCR
# 参数解释:
# `lang`:指定语言模型,如 'en'(英文)、'ch'(中文)等。
# `use_angle_cls`:是否启用文字方向分类器。
ocr = PaddleOCR(use_angle_cls=True, lang='en'# 也可以设置为 'ch' 用于中文[^28^]
  
# 指定图片路径
img_path = 'example.jpg'  # 替换为你的图片路径
  
# 执行 OCR 识别
result = ocr.ocr(img_path, cls=True# `cls=True` 表示启用方向分类器
  
# 打印识别结果
for line in result:
    print(line)
  
# 可选:绘制识别结果并保存
if result:
    image = Image.open(img_path).convert('RGB')
    boxes = [line[0] for line in result]  # 提取文字框
    txts = [line[1][0] for line in result]  # 提取文字内容
    scores = [line[1][1] for line in result]  # 提取置信度
  
    # 绘制结果
    im_show = draw_ocr(image, boxes, txts, scores, font_path='path/to/PaddleOCR/doc/fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result.jpg'# 保存绘制后的图片[^28^]

2、RapidOCR

首先,确保安装了 RapidOCR 的 ONNXRuntime 版本,这是一个轻量级且高效的推理引擎:

1
pip install rapidocr_onnxruntime

示例代码:识别数字和字母

以下代码展示了如何使用 RapidOCR 识别图片中的数字和字母,并仅打印识别结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from rapidocr_onnxruntime import RapidOCR
  
# 初始化 OCR 引擎
ocr = RapidOCR()
  
# 指定图片路径
img_path = 'example.jpg'  # 替换为你的图片路径
  
# 执行识别
result, _ = ocr(img_path)
  
# 提取并打印识别结果(仅数字和字母)
if result:
    for line in result:
        text = line[1# 提取文字内容
        # 筛选只包含数字和字母的文本
        if text.isalnum():
            print(text)
else:
    print("未识别到文字")

注意事项

  • 图片路径:确保 img_path 指向的图片包含数字或字母。
  • 语言设置:默认情况下,RapidOCR 支持中英文混合识别。如果需要识别其他语言,可以参考文档进行配置。
  • 环境要求:确保 Python 版本为 3.6 或更高。

3、EasyOCR

特点:易于使用,支持多种语言(包括中文、英文等),基于深度学习技术,适合初学者和快速集成。

安装方法:

1
pip install easyocr

使用示例:

1
2
3
4
5
6
7
import easyocr
  
reader = easyocr.Reader(['en', 'ch_sim'])  # 支持多语言
img_path = 'example.jpg'
result = reader.readtext(img_path)
for line in result:
    print(line[1])  # 打印识别结果

4、Pytesseract

特点:Tesseract 的 Python 封装,支持多种语言,使用简单,适合传统 OCR 任务。

安装方法:

1
pip install pytesseract

需要先安装 Tesseract OCR,可以从 Tesseract 官网 下载。

使用示例:

1
2
3
4
5
6
from PIL import Image
import pytesseract
  
img_path = 'example.jpg'
text = pytesseract.image_to_string(Image.open(img_path), lang='eng')
print(text)  # 打印识别结果

5、DocTR

特点:专注于文档分析和表格识别,能够提取文档中的结构化信息,适合处理复杂布局的文档。

安装方法:

1
pip install python-doctr

使用示例:

1
2
3
4
5
6
7
8
9
10
11
from doctr.models import ocr_predictor
from doctr.io import DocumentFile
  
img_path = 'example.jpg'
doc = DocumentFile.from_images(img_path)
model = ocr_predictor(pretrained=True)
result = model(doc)
for block in result.pages[0].blocks:
    for line in block.lines:
        for word in line.words:
            print(word.value)  # 打印识别结果

6、PyOCR

特点:封装了多个 OCR 引擎(如 Tesseract、Cuneiform 等),提供了统一的接口。

安装方法:

1
pip install pyocr

使用示例:

1
2
3
4
5
6
7
8
import pyocr
from PIL import Image
  
tools = pyocr.get_available_tools()
ocr_tool = tools[0]
img_path = 'example.jpg'
text = ocr_tool.image_to_string(Image.open(img_path), lang='eng')
print(text)  # 打印识别结果

选择建议:

速度优先:推荐使用 RapidOCR 或 EasyOCR。

准确性优先:推荐使用 PaddleOCR。

易用性优先:推荐使用 EasyOCR。

文档分析优先:推荐使用 docTR。

注意:根据你的具体需求(如语言支持、应用场景、性能要求等),可以选择最适合的 OCR 库。

到此这篇关于使用Python实现pdf转图片再进行OCR识别的文章就介绍到这了,更多相关Python pdf转图片内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/python/15251.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部