您现在的位置是:网站首页 > 博客日记 >

利用百度接口识别图片文字

作者:YXN-python 阅读量:130 发布日期:2023-05-17

前提:需要在百度智能云申请权限,此处不提供申请教程了,直接上代码:

import hashlib
import random
import requests
from aip import AipNlp, AipOcr


class Recognition:
    def __init__(self, app: dict):
        self.app_id = app['app_id']
        self.api_key = app['api_key']
        self.secret_key = app['secret_key']
        self.client = AipNlp(self.app_id, self.api_key, self.secret_key)
        self.client_ocr = AipOcr(self.app_id, self.api_key, self.secret_key)  # 初始化百度OCR API客户端

    # 图片翻译
    def translate_image(self, image_path):
        with open(image_path, 'rb') as f:
            image = f.read()

        result = self.client_ocr.basicGeneral(image)
        if 'error_code' in result:
            print('图片翻译失败,错误码:', result['error_code'], '错误信息:', result['error_msg'])
        else:
            text = ''.join([word['words'] for word in result['words_result']])
            print(text)
            # translate_text(text, 'auto', 'en')  # 将识别出的文字进行翻译,这里示例将识别语言为自动检测,目标语言为英语
        return result


if __name__ == '__main__':
    def main_start():
        request_args = {
            "app_id": 'xxxxxx',
            "api_key": 'xxxxxx',
            "secret_key": 'xxxxxx'
        }
        translate_api = Recognition(request_args)

        # # 测试图片翻译
        text = translate_api.translate_image('./1.jpg')
        print(text)


    main_start()

YXN-python

2023-05-17