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))
總結
以上是生活随笔為你收集整理的python批量识别图片中文字_利用Python批量进行图片文字识别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python统计单词出现次数_用pyth
- 下一篇: 燃烧温度计算程序_【知识库】燃气燃烧器如