OCR文字識別在UI自動化上的運用

用了Airtest的圖像識別後發現在一些文字的識別上有些不準確,猜測可能是特徵值比較低吧,容易匹配錯。

在論壇上也看到過有人用OCR的方式,記不得是哪個帖子了,用的是騰訊雲的接口吧。

按這個思路嘗試了一下,騰訊雲的接口有次數限制,我找了訊飛的接口,完全免費,也能用

原理很簡單,給這個接口上傳一張圖片,後臺處理生成識別出來的文字以及位置座標。

有幾個雲平臺提供了OCR的接口,騰訊雲超過一定次數就收費,我找到了科大訊飛的接口是完全免費的。

給這個接口上傳一張圖片,後臺處理生成識別出來的文字以及位置座標。

所以,只要把設備的屏幕截圖保存,讀進來,轉成base64編碼,傳給訊飛雲接口

等着結果返回json串,解析裏面包含你要找的文字,拿到位置座標,算出中心點

點擊

搞定

貼代碼,訊飛雲上的demo代碼照搬有問題,改了一下

import urllib
def OCR_getPos(target):

    filePath = snapshot()
    f = open(filePath, 'rb')
    file_content = f.read()
    base64_image = base64.b64encode(file_content)
    body = urllib.parse.urlencode({'image': base64_image}).encode(encoding='utf-8')

    url = 'http://webapi.xfyun.cn/v1/service/v1/ocr/general'
    api_key = '1e90ca2d09d7213bf6770f34e6d2e70b'#用你自己的api_key替換
    param = {"language": "cn|en", "location": "true"}

    x_appid = "c23538b5" #用你自己的appid替換,我這個是亂敲的哈
    x_param = base64.b64encode(json.dumps(param).replace(' ', '').encode(encoding="utf-8"))
    x_param_b64_str = x_param.decode('utf-8')
    x_time = str(int(int(round(time.time() * 1000)) / 1000))
    string = api_key+x_time+x_param_b64_str
    string = string.encode('utf-8')
    # string = api_key + str(x_time) + x_param
    # m = hashlib.new('md5')
    # m.update(string.encode(encoding='UTF-8'))
    # x_checksum = m.hexdigest()
    # hash = hashlib.new('md5')
    # hash.update(.encode(encoding='utf-8'))
    # x_checksum = hash.hexdigest()
    x_checksum = hashlib.md5(string).hexdigest()
    x_header = {'X-Appid': x_appid,
                'X-CurTime': x_time,
                'X-Param': x_param_b64_str,
                'X-CheckSum': x_checksum}
    req = urllib.request.Request(url, body, x_header)
    result = urllib.request.urlopen(req)
    result = result.read().decode()
    jsonObject = json.loads(result)
    location=None
    try:
        data = jsonObject.get('data').get('block')
        for block in data:
            if block.get('type') == 'text':
                data = block
    except:
        print('no words')
        return
    lines = data.get('line')
    for line in lines:
        words = line.get('word')
        for word in words:
            content = word.get('content')
            if content is not None and target in content:
                location = word.get('location')
                print(location)
    if location :
        x1 = int(location.get('top_left').get('x'))
        y1 = int(location.get('top_left').get('y'))
        x2 = int(location.get('right_bottom').get('x'))
        y2 = int(location.get('right_bottom').get('y'))
        width = x2 -x1
        height = y2 - y1
        center_x = x1 + width/2
        center_y = y1 + height/2
        pos = [center_x, center_y]
        touch(pos)
    print(result+'\n')
    print(data)

if __name__ == '__main__':
    OCR_getPos('姓名')

 

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