python实现ocr搜索答案---百万英雄辅助工具

时间:2022-06-02 23:20:10
# -*- coding: UTF-8 -*-

from aip import AipOcr
import json

from selenium import webdriver
import os
import subprocess
from PIL import Image

# 定义常量
APP_ID = '10707718'
API_KEY = 'EeujpVN1ds0g4XjMBGkXfjk4'
SECRET_KEY = 'svIw8fn3n4XV0AuAH3sjNwpzc9XUbu8k'

# 初始化AipFace对象
aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)

# 读取图片
filePath = "autojump.png"


def scopImg(filePath):
img = Image.open(filePath)
wh = img.size

left = 0
top = wh[1] * 0.1
right = wh[0]
bottom = wh[1] * 0.3

print(str(left) + "\t" + str(top) + "\t" + str(right) + "\t" + str(bottom))

region = (left, top, right, bottom)
cropImg = img.crop(region)
cropImg.save('crop.png', 'png')


def get_file_content(filePath):
scopImg(filePath)
file_stream = open('crop.png', "rb")
return file_stream.read()

# 定义参数变量


options = {
'detect_direction': 'true',
'language_type': 'CHN_ENG',
}


def main():
while True:
input_str = input('开始截图!!!\n')
if input_str == 'y':
pull_screenshot()
str_result = ''
# 调用通用文字识别接口
result = aipOcr.basicAccurate(get_file_content(filePath), options)
jsonresult = json.dumps(result).encode('utf-8').decode('unicode_escape')
for json_item in json.loads(jsonresult)['words_result']:
str_result += json_item['words']
print(str_result)

driver = webdriver.Chrome()
# 访问百度
driver.get('http://baidu.com/')

# 输入框输入内容
driver.find_element_by_id('kw').send_keys(str_result)


screenshot_way = 2


def pull_screenshot():
'''
新的方法请根据效率及适用性由高到低排序
'''
global screenshot_way
if screenshot_way == 2 or screenshot_way == 1:
process = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)
screenshot = process.stdout.read()
if screenshot_way == 2:
binary_screenshot = screenshot.replace(b'\r\n', b'\n')
else:
binary_screenshot = screenshot.replace(b'\r\r\n', b'\n')
f = open('autojump.png', 'wb')
f.write(binary_screenshot)
f.close()
elif screenshot_way == 0:
os.system('adb shell screencap -p /sdcard/autojump.png')
os.system('adb pull /sdcard/autojump.png .')


if __name__ == '__main__':
main()