溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何利用PaddleOCR制作個搜題小工具

發(fā)布時間:2022-06-09 10:04:29 來源:億速云 閱讀:281 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Python如何利用PaddleOCR制作個搜題小工具”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Python如何利用PaddleOCR制作個搜題小工具”文章能幫助大家解決問題。

    安裝

    雖然PaddleOCR支持服務(wù)端部署并提供識別API,但根據(jù)我們的需求,搭建一個本地離線的OCR識別環(huán)境,所以此次我們只介紹如何在本地安裝并使用的做法。

    安裝PaddlePaddle飛槳框架

    一、環(huán)境準備

    1.1 目前飛槳支持的環(huán)境

    Windows 7/8/10 專業(yè)版/企業(yè)版 (64bit)

    GPU版本支持CUDA 10.1/10.2/11.0/11.2,且僅支持單卡

    Python 版本 3.6+/3.7+/3.8+/3.9+ (64 bit)

    pip 版本 20.2.2或更高版本 (64 bit)

    二、安裝命令

    pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple

    (注意此版本為CPU版本,如需GPU版本請查看PaddlePaddle文檔)

    安裝完成后您可以使用 python 進入python解釋器,輸入import paddle ,再輸入 paddle.utils.run_check()

    如果出現(xiàn)PaddlePaddle is installed successfully!,說明您已成功安裝。

    安裝PaddleOCR

    pip install "paddleocr>=2.0.1" # 推薦使用2.0.1+版本

    代碼使用

    安裝完成后你可以使用以下代碼來進行簡單的功能測試

    from paddleocr import PaddleOCR, draw_ocr
    
    # Paddleocr目前支持中英文、英文、法語、德語、韓語、日語,可以通過修改lang參數(shù)進行切換
    # 參數(shù)依次為`ch`, `en`, `french`, `german`, `korean`, `japan`。
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")  # need to run only once to download and load model into memory
    # 選擇你要識別的圖片路徑
    img_path = '11.jpg'
    result = ocr.ocr(img_path, cls=True)
    for line in result:
        print(line)
    
    # 顯示結(jié)果
    from PIL import Image
    
    image = Image.open(img_path).convert('RGB')
    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]
    im_show = draw_ocr(image, boxes, txts, scores, font_path='/path/to/PaddleOCR/doc/fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result.jpg')

    結(jié)果是一個list,每個item包含了文本框,文字和識別置信度

    [[[24.0, 36.0], [304.0, 34.0], [304.0, 72.0], [24.0, 74.0]], ['純臻營養(yǎng)護發(fā)素', 0.964739]]
    [[[24.0, 80.0], [172.0, 80.0], [172.0, 104.0], [24.0, 104.0]], ['產(chǎn)品信息/參數(shù)', 0.98069626]]
    [[[24.0, 109.0], [333.0, 109.0], [333.0, 136.0], [24.0, 136.0]], ['(45元/每公斤,100公斤起訂)', 0.9676722]]
    ......

    可視化效果

    Python如何利用PaddleOCR制作個搜題小工具

    至此我們就掌握了 PaddleOCR 的基本使用,基于這個我們就能開發(fā)出一個OCR的搜題小工具了。

    搜題小工具

    現(xiàn)在有很多那種答題競賽的小游戲,在限定時間內(nèi)看誰答題正確率更高?;蛘攥F(xiàn)在一些單位會搞一些大練兵什么的競賽,需要在網(wǎng)上答題,這個時候手動輸入題目去搜索就很慢,效率也不會太高,所以我們就可以來寫一個腳本,幫助我們完成搜題的過程。

    基本思路就是通過ADB截取當(dāng)前屏幕,然后剪切出題目所在位置,然后通過PaddleOCR來獲取題目文字,之后打開搜索引擎搜索或者打開題庫搜索。

    安裝ADB

    你可以到這里下載安裝ADB之后配置環(huán)境變量。

    配置完環(huán)境變量后在終端輸入adb,如果出現(xiàn)以下字符則證明adb安裝完成。

    Android Debug Bridge version 1.0.41
    Version 31.0.3-7562133

    截圖并保存題目區(qū)域圖片

    import os
    from PIL import Image
    
    # 截圖
    def pull_screenshot():
        os.system('adb shell screencap -p /sdcard/screenshot.png')
        os.system('adb pull /sdcard/screenshot.png .')
    
    img = Image.open("./screenshot.png")
    # 切割問題區(qū)域
    # (起始點的橫坐標,起始點的縱坐標,寬度,高度)
    question  = img.crop((10, 400, 1060, 1000))
    # 保存問題區(qū)域
    question.save("./question.png")

    OCR識別,獲取題目

    ocr = PaddleOCR(use_angle_cls=False, 
                            lang="ch", 
                            show_log=False
                            )  # need to run only once to download and load model into memory
    img_path = 'question.png'
    result = ocr.ocr(img_path, cls=False)
    
    # 獲取題目文本
    questionList = [line[1][0] for line in result]
    text = ""
    # 將數(shù)組轉(zhuǎn)換為字符串
    for str in questionList :
        text += str
    print(text)

    打開瀏覽器搜索

    import webbrowser
    webbrowser.open('https://baidu.com/s?wd=' + urllib.parse.quote(question))

    之后你就可以查看搜索結(jié)果了

    如果有題庫,你還可以使用pyautogui來模擬鼠標鍵盤操作,去操作Word等軟件在題庫中進行搜索。

    完整代碼

    # -*- coding: utf-8 -*-
    
    # @Author  : Pu Zhiwei
    # @Time    : 2021-09-02 20:29
    
    from PIL import Image
    import os
    import matplotlib.pyplot as plt
    from paddleocr import PaddleOCR, draw_ocr
    import pyperclip
    import pyautogui
    import time
    import webbrowser
    import urllib.parse
    
    
    # 鼠標位置
    currentMouseX, currentMouseY = 60, 282
    
    # 截圖獲取當(dāng)前題目
    def pull_screenshot():
        os.system('adb shell screencap -p /sdcard/screenshot.png')
        os.system('adb pull /sdcard/screenshot.png .')
    
    # 移動鼠標到搜索框搜索
    def MoveMouseToSearch():
        # duration 參數(shù),移動時間,即用時0.1秒移動到對應(yīng)位置
        pyautogui.moveTo(currentMouseX, currentMouseY, duration=0.1)
        # 左鍵點擊
        pyautogui.click()
        pyautogui.click()
        # 模擬組合鍵,粘貼
        pyautogui.hotkey('ctrl', 'v')
    
    # 擴充問題
    def AddText(list, length, text):
        if length > 3:
            return text + list[3]
        else:
            return text
    # 打開瀏覽器
    def open_webbrowser(question):
        webbrowser.open('https://baidu.com/s?wd=' + urllib.parse.quote(question))
    
    
    # 顯示所識別的題目
    def ShowAllQuestionText(list):
        text = ""
        for str in list:
            text += str
        print(text)
    
    
    
    if __name__ == "__main__":
        while True:
            print("\n\n請將鼠標放在Word的搜索框上,三秒后腳本將自動獲取Word搜索框位置!\n\n")
            # 延時三秒輸出鼠標位置
            time.sleep(3)
            # 獲取當(dāng)前鼠標位置
            currentMouseX, currentMouseY = pyautogui.position()
            print('當(dāng)前鼠標位置為: {0} , {1}'.format(currentMouseX, currentMouseY))
            start = input("按y鍵程序開始運行,按其他鍵重新獲取搜索框位置:")
            if start == 'y':
                break
    
        while True:
            t = time.perf_counter()
            pull_screenshot()
            img = Image.open("./screenshot.png")
            # 切割問題區(qū)域
            # (起始點的橫坐標,起始點的縱坐標,寬度,高度)
            question  = img.crop((10, 400, 1060, 1000))
            # 保存問題區(qū)域
            question.save("./question.png")
    
    
            # 加載 PaddleOCR
            # Paddleocr目前支持中英文、英文、法語、德語、韓語、日語,可以通過修改lang參數(shù)進行切換
            # 參數(shù)依次為`ch`, `en`, `french`, `german`, `korean`, `japan`。
    
            # 自定義模型地址
            # det_model_dir='./inference/ch_ppocr_server_v2.0_det_train', 
            #                rec_model_dir='./inference/ch_ppocr_server_v2.0_rec_pre',
            #                cls_model_dir='./inference/ch_ppocr_mobile_v2.0_cls_train',
            ocr = PaddleOCR(use_angle_cls=False, 
                            lang="ch", 
                            show_log=False
                            )  # need to run only once to download and load model into memory
            img_path = 'question.png'
            result = ocr.ocr(img_path, cls=False)
    
            questionList = [line[1][0] for line in result]
            length = len(questionList)
            text = ""
            if length < 1:
                text = questionList[0]
            elif length == 2:
                text = questionList[1]
            else:
                text = questionList[1] + questionList[2]
    
            print('\n\n')
            ShowAllQuestionText(questionList)
            # 將結(jié)果寫入剪切板
            pyperclip.copy(text)
            # 點擊搜索
            MoveMouseToSearch()
            
            # 計算時間
            print('\n\n')
            end_time3 = time.perf_counter()
            print('用時: {0}'.format(end_time3 - t))
            
            go = input('輸入回車繼續(xù)運行,輸入 e 打開瀏覽器搜索,輸入 a 增加題目長度,輸入 n 結(jié)束程序運行: ')
            if go == 'n':
                break
      
            if go == 'a':
                text = AddText(questionList, length, text)
                pyperclip.copy(text)
                # 點擊搜索
                MoveMouseToSearch()
                stop = input("輸入回車繼續(xù)")
            elif go == 'e':
                # 打開瀏覽器
                open_webbrowser(text)
                stop = input("輸入回車繼續(xù)")
    
            print('\n------------------------\n\n')

    關(guān)于“Python如何利用PaddleOCR制作個搜題小工具”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI