Python實現任意區域文字識別(OCR)後放入剪切板,系統提示音提醒

本文的OCR當然不是自己從頭開發的,是基於百度智能雲提供的API(我感覺是百度在中國的人工智能領域值得稱讚的一大貢獻),其提供的API完全可以滿足個人使用,相對來說簡潔準確率高。

代碼實現

下面讓我們來看一下代碼實現。

主要使用的模塊有

import os # 操作系統相關
import sys # 系統相關
import time # 時間獲取
import signal # 系統信號
import winsound # 提示音
from aip import AipOcr  # 百度OCR API
from PIL import ImageGrab # 捕獲剪切板中的圖片
import win32clipboard as wc # WINDOWS 剪切板操作
import win32con # 這裏用於獲取 WINDOWS 剪貼板數據的標準格式

第一步 這裏的APP_ID,API_KEY,SECRET_KEY是通過登陸百度智能雲後自己在OCR板塊申請的, 實現基本的OCR程序,可以通過圖片獲取文字。

""" 你的 APPID AK SK """
APP_ID = 'xxx'
API_KEY = 'xxx'
SECRET_KEY = 'xxx'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 讀取圖片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

""" 從API的返回字典中獲取文字 """
def getOcrText(txt_dict):
	txt = ""
	if type(txt_dict) == dict:
		for i in txt_dict['words_result']:
			txt = txt + i["words"]
			if len(i["words"]) < 25: # 這裏使用字符串長度決定了文本是否換行,讀者可以根據自己的喜好控制回車符的輸出,實現可控的文本顯示形式
				txt = txt + "\n\n"
	return txt

""" 調用通用/高精度文字識別, 圖片參數爲本地圖片 """
def BaiduOcr(imageName,Accurate=True):
	image = get_file_content(imageName)
	if Accurate:
		return getOcrText(client.basicGeneral(image))
	else:
		return getOcrText(client.basicAccurate(image))
	
""" 帶參數調用通用文字識別, 圖片參數爲遠程url圖片 """
def BaiduOcrUrl(url): 
	return getOcrText(client.basicGeneralUrl(url))

第二步,實現快捷鍵獲取文字,將識別文字放入剪切板中,提示音提醒以及快捷鍵退出程序

""" 截圖後,調用通用/高精度文字識別"""
def BaiduOcrScreenshots(Accurate=True,path="./temp/"):
	if not os.path.exists(path):
		os.makedirs(path)
	image = ImageGrab.grabclipboard()
	if image != None:
		print("\rThe image has been obtained. Please wait a moment!",end=" ")
		filename = str(time.time_ns())
		image.save(path+filename+".png")
		if Accurate:
			txt = getOcrText(client.basicAccurate(get_file_content(path+filename+".png")))
		else:	
			txt = getOcrText(client.basicGeneral(get_file_content(path+filename+".png")))
		os.remove(path+filename+".png")
		set_clipboard(txt)
		winsound.PlaySound('SystemAsterisk',winsound.SND_ASYNC)
		return txt
	else :
			print("\rPlease get the screenshots by Shift+Win+S !       ",end="")
			
def sig_handler(signum, frame):
    sys.exit(0)

def AutoOcrScreenshots():
	signal.signal(signal.SIGINT, sig_handler)
	signal.signal(signal.SIGTERM, sig_handler)
	print("Please get the screenshots by Shift+Win+S !",end="")
	print("Waiting For Ctrl+C to exit!")
	while(1):
		try:
			BaiduOcrScreenshots(ifauto=True)
			time.sleep(0.1)
		except SystemExit:
			break
		else :
			pass
		finally:
			pass

使用方法

使用Windows 10系統時, 可以使用Shift+Win+S快捷鍵實現任意區域截取,截取後圖片將暫時存放在剪切板中,程序自動使用Windows API獲取圖片內容,之後使用百度的OCR API獲取文字,並將文字放置在剪切版內存中後發出提示音。使用者則可以在開啓程序後,使用快捷鍵截圖後靜待提示音後使用Ctrl+V將文字內容放置在自己所需的位置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章