博客 / 詳情

返回

使用Python從圖片中提取文本

在日常辦公或文檔數字化處理中,我們常常會遇到需要從圖片中提取文字的需求,例如掃描件、截圖、票據等。藉助OCR(光學字符識別)技術,我們可以快速將圖像中的文字轉換為可編輯文本。

本文將介紹如何使用 Spire.OCR for Python 從圖片中提取文字,包括:

  • 基本提取方法
  • 獲取文本的位置信息
  • 批量處理文件夾內的多張圖片

工具介紹:Spire.OCR for Python

Spire.OCR for Python 是一款輕量級的OCR組件,支持從圖片中識別文本,並可輸出純文本內容或包含位置信息的文本塊。

安裝方法

pip install spire.ocr

必須下載模型文件

在使用 OCR 前,需要下載預訓練模型。根據操作系統,選擇對應版本並解壓到本地目錄:

  • Windows(64位):win-x64.zip
  • Linux: linux.zip
  • macOS: mac.zip

下載後,請記住解壓後的路徑,後續代碼中將用到。


步驟詳解:從圖片中提取文本

步驟1:初始化OCR並設置模型路徑

from spire.ocr import *

scanner = OcrScanner()

options = ConfigureOptions()
options.ModelPath = r'D:\OCR\win-x64'  # 模型所在文件夾路徑
options.Language = 'English'           # 當前支持英文
scanner.ConfigureDependencies(options)

步驟2:從單張圖片中提取文本並保存

scanner.Scan(r'Sample.png')  # 替換為你的圖片路徑
text = scanner.Text.ToString()

with open('output.txt', 'a', encoding='utf-8') as file:
    file.write(text + '\n')

提取結果會保存在 output.txt 文件中。

移除警告請使用 split("Evaluation")[0] 方法。


步驟3:獲取文本塊及其位置信息

如果你需要獲取每段文字在圖像中的位置(例如用於版面分析),可以使用如下方式:

text = scanner.Text

block_text = ""
for block in text.Blocks:
    rect = block.Box
    info = f'{block.Text} -> x: {rect.X}, y: {rect.Y}, w: {rect.Width}, h: {rect.Height}'
    block_text += info + '\n'

with open('output.txt', 'a', encoding='utf-8') as file:
    file.write(block_text + '\n')

步驟4:批量處理文件夾中的圖片

可以輕鬆對文件夾內的多張圖片執行OCR,並將結果分別輸出為文本文件:

import os
from spire.ocr import *

def extract_text_from_folder(folder_path, model_path):
    scanner = OcrScanner()
    config = ConfigureOptions()
    config.ModelPath = model_path
    config.Language = 'English'
    scanner.ConfigureDependencies(config)

    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            image_path = os.path.join(folder_path, filename)
            scanner.Scan(image_path)
            text = scanner.Text.ToString()

            output_file = os.path.splitext(filename)[0] + '_output.txt'
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(text)

# 示例調用
extract_text_from_folder(r'D:\images', r'D:\OCR\win-x64')

總結

本文介紹了使用 Spire.OCR for Python 從圖片中提取文本的完整方法,支持:

  • 單張圖片的文字識別
  • 獲取每段文字的位置信息
  • 一鍵處理整個圖片文件夾

相關鏈接

  • Spire.OCR 教程
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.