天天看點

python批量識别圖檔中文字_利用Python批量進行圖檔文字識别

實作邏輯

1. 批量擷取圖檔的路徑

2. 通過調用百度OCR接口批量識别圖檔

3. 将傳回值寫入txt

實作過程

1. 安裝百度的Python SDK

pip install baidu-aip

2. 具體代碼

from aip import AipOcr

import time

import os

#擷取開始時間

start = time.time()

""" 你的 APPID AK SK """

APP_ID = '您的appid'

API_KEY = '您的AK'

SECRET_KEY = '您的SK'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 讀取圖檔 """

def get_file_content(filePath):

print(filePath)

with open(filePath, 'rb') as fp:

return fp.read()

""" 寫入文本 """

def write_on_txt(content,filePath,linefeed = "1"):

"""

content:要寫入的内容

filePath:要寫入檔案的路徑

linefeed :判斷是否換行

- 1 為不換行

- 其他 為換行

"""

#隻需要将之前的”w"改為“a"即可,代表追加内容

with open(filePath,"a") as file:

try:

file.write(content)

except:

print("寫入錯誤")

else:

if linefeed != "1":

file.write("\n")

#圖檔路徑

img_path = r"D:\圖檔" # 也可采用 r" D:\Test_path" 或者是"D:/Test_path"

#文本路徑

txt_path = r"C:\Users\User29\Desktop\OCR\圖檔.txt"

options = {}

#周遊所有檔案(使用 os.walk 方法)

for root,dirs,files in os.walk(img_path):

for file in files:

# 使用join函數将檔案名稱和檔案所在根目錄連接配接起來

file_dir = os.path.join(root, file)

print(file_dir)

write_on_txt("=============================",txt_path,"0")

write_on_txt("檔案名:"+ file_dir,txt_path,"0")

#判斷是否是圖檔

if file_dir[-4:]==".png"or file_dir[-4:]==".jpg":

#傳入圖檔

image = get_file_content(file_dir)

""" 調用通用文字識别, 圖檔參數為本地圖檔 """

a = client.basicGeneral(image, options)

# 檢視傳回的結果

# print(a['words_result'])

print()

for dic in a['words_result']:

print(dic['words'])

write_on_txt(dic['words'],txt_path,"0")

end = time.time()

print('Running time: %1.2f Seconds'%(end-start))