Python 识别图片中文字

OCR文字识别

调用百度免费的api接口实现,网络图片中文字的提取。

一.api接口文档

https://ai.baidu.com/tech/ocr_others/webimage

相关介绍不做赘述。

二.代码实现

import requests
import os
import json
import base64
import time

# 获取access_token
def getAccessToken():

    URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
    Api_key = 'api_key'
    Secret_key = 'Secret_key'
    requests_url = URL + '&client_id=' + Api_key + '&client_secret=' +Secret_key
    response = requests.get(requests_url).json()
    access_token = response['access_token']
    print(access_token)
    return access_token

    # print(response.json())
def Ocrimage(img):

    '''
    网络图片文字识别
    '''
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"
    # 二进制方式打开图片文件
    # f = open('./image/1.jpg', 'rb')
    # img = base64.b64encode(f.read())

    params = {"image":img}
    access_token = 'access_token'
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    # if response:
    #     print (response.json())
    return response.json() 

def sumRes(Res):

    word = ''
    word_list = Res['words_result']
    for p in word_list:
        word_data = p['words']
        word = word + word_data
    print(word)

def start():
    fn_list = os.listdir('./image')
    for fn in fn_list:
        time.sleep(1.5)
        file_Path = './image/' + fn
        f = open(file_Path, 'rb')
        img = base64.b64encode(f.read())
        Res = Ocrimage(img)
        sumRes(Res)

if __name__ == "__main__":
	# 第一次运行该方法获取access_token,复制赋值给Ocrimage方法中的access_token。
    # getAccessToken()
	# 第一次运行注释掉 start()方法
    start()


三.代码效果

遍历当前运行目录下,image文件夹中的所有图片,提取图片文字并在控制台输出。

你可能感兴趣的:(脚本办公,python,ocr,图像识别)