以下是一个基于 Python 的微信 API 接口调用 OCR 识别图片文字的示例代码:

import requests
import json

# 在微信公众平台申请的 appID 和 appSecret
appID = 'your_appID'
appSecret = 'your_appSecret'

# 获取 access_token
def get_access_token(appID, appSecret):
    url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appID + '&secret=' + appSecret
    response = requests.get(url)
    access_token = json.loads(response.text)['access_token']
    return access_token

# OCR 识别图片文字
def ocr_image_text(access_token, image_path):
    url = 'https://api.weixin.qq.com/cv/ocr/comm?access_token=' + access_token
    files = {'img': open(image_path, 'rb')}
    response = requests.post(url, files=files)
    result = json.loads(response.text)
    if result['errcode'] == 0:
        text = ''
        for item in result['items']:
            text += item['text'] + '\n'
        return text
    else:
        return 'OCR 识别失败'

# 调用 OCR 识别函数
access_token = get_access_token(appID, appSecret)
image_path = 'I:\test.png'  # 本地图片路径
text = ocr_image_text(access_token, image_path)
print(text)

需要注意的是,以上代码中的图片路径需要根据实际的本地图片路径进行修改。另外,还需要在微信公众平台申请相应的权限和配置,才能成功调用微信 API 接口。

Python 微信 API 图片文字 OCR 识别代码示例

原文地址: https://www.cveoy.top/t/topic/lKGa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录