2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 百度AI开放平台和高德开放平台的使用

百度AI开放平台和高德开放平台的使用

时间:2023-06-26 06:25:47

相关推荐

百度AI开放平台和高德开放平台的使用

目录

1.百度AI开放平台

1.1语音合成

1.2语音识别

1.3人脸识别

1.4文字识别

1.4.1手写文字识别

1.4.2 身份证识别

1.5人体检测

2.高德开放平台

2.1天气查询

2.2地理编码/逆地理编码

2.3路径规划

1.百度AI开放平台

百度AI开放平台的使用主要分为5步。先登录账号,再创建应用、获取密钥、生成签名,最后开发调用。

应用是调用API服务的基本操作单元,需要先创建应用才可正式调用AI能力,基于应用创建成功后获取的API Key及Secret Key,进行接口调用操作,及相关配置。使用创建应用所分配到的AppID、API Key及Secret Key,进行Access_Token(用户身份验证和授权的凭证)的生成。

1)登录百度AI开放平台:百度智能云-登录

点击左上角蓝色按钮,选择对应的产品服务

2)创建一个应用,应用名称和应用描述随便填写即可,勾选需要的服务接口(一个应用可以实现多种功能),创建完成后就能得到AppID,API Key,Secret Key;

3)在“概览”中领取免费资源;

4)获取access_token(注意每次获取的access_token 30天就会过期,必须重新获取一次)

import requestsAPI_KEY = '复制创建的应用的API_KEY'SECRET_KEY = '复制创建的应用的SECRET_KEY' host = '/oauth/2.0/token?grant_type=client_credentials' + \'&client_id=' + API_KEY + \'&client_secret=' + SECRET_KEYresponse = requests.get(host)if response:token = response.json()['access_token']print(token)

百度AI开放平台提供了很多产品功能,这里挑出几个做示范。

1.1语音合成

from aip import AipSpeechAPP_ID = '你的APP_ID'API_KEY = '你的API_KEY'SECRET_KEY = '你的SECRET_KEY'client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)word = '你好'result = client.synthesis(word, 'zh', 1,{'vol': 5})if not isinstance(result, dict):with open('test.mp3', 'wb') as f:f.write(result)

上面的代码生成了一个test.mp3的音频文件,内容为“你好”。更多参数请参考:/ai-doc/SPEECH/Qk38y8lrl

1.2语音识别

# encoding:utf-import base64import pyaudio,wavefrom aip import AipSpeechAPP_ID = '你的APP_ID'API_KEY = '你的API_KEY'SECRET_KEY = '你的SECRET_KEY'client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)def record(): # 录音chunk = 1024 sample_format = pyaudio.paInt16channels = 1fs = 16000 seconds = 3 # 录音时长为3秒p = pyaudio.PyAudio()print('开始录音')stream = p.open(format=sample_format,channels=channels,rate=fs,frames_per_buffer=chunk,input=True)frames = []for i in range(0, int(fs / chunk * seconds)):data = stream.read(chunk)frames.append(data)stream.stop_stream()stream.close()p.terminate()print('录音结束')wf = wave.open("audio.pcm", 'wb')wf.setnchannels(channels)wf.setsampwidth(p.get_sample_size(sample_format))wf.setframerate(fs)wf.writeframes(b''.join(frames))wf.close()def get_file_content(filePath): # 读取文件with open(filePath, 'rb') as fp:return fp.read()if __name__ == '__main__':record()result = client.asr(get_file_content('audio.pcm'), 'pcm', 16000, {'dev_pid': 1537,})answer=result['result'][0].strip('。')print(answer)

1.3人脸识别

在应用的可视化人脸库中新建用户组,加入用户照片

import base64from aip import AipFaceAPP_ID = '你的APP_ID'API_KEY = '你的API_KEY'SECRET_KEY = '你的SECRET_KEY'client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)def fileopen(filepath): #打开图片with open(filepath, 'rb') as f:data = base64.b64encode(f.read())image = str(data,'utf-8')return imagedef face_search(filepath,groupIdList): #人脸库搜索groupIdList="你的用户组名称"image = fileopen(filepath)imageType="BASE64"data=client.search(image,imageType,groupIdList)result = data.get('result')if result:if result['user_list'][0]['score'] >70 :return result['user_list'][0]['user_id'] #打印识别出来的姓名else :return Noneif __name__ == '__main__':print(face_search('test.jpg','test')) # 替换图片名称和人脸库用户组名称

1.4文字识别

1.4.1手写文字识别

import requestsimport base64request_url = " /rest/2.0/ocr/v1/handwriting"f = open('test.jpg', 'rb') # 替换成自己的图片文件img = base64.b64encode(f.read())params = {"image":img}access_token = '【获取的access_token】'request_url = request_url + "?access_token=" + access_tokenheaders = {'content-type': 'application/x-www-form-urlencoded'}response = requests.post(request_url, data=params, headers=headers)if response:answer=response.json()['words_result'][0]['words']print(answer)

1.4.2 身份证识别

import base64import requestsrequest_url = "/rest/2.0/ocr/v1/idcard"f = open('test.jpg', 'rb') # 替换成自己的图片文件img = base64.b64encode(f.read())params = {"id_card_side":"front","image":img}access_token = '【获取的access_token】'request_url = request_url + "?access_token=" + access_tokenheaders = {'content-type': 'application/x-www-form-urlencoded'}response = requests.post(request_url, data=params, headers=headers)if response:print (response.json()['words_result']['姓名']['words'])

1.5人体检测

对于输入的一张图片(可正常解码,且长宽比适宜),检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持17种属性,包括:性别、年龄阶段、上下身服饰(含类别/颜色)、是否戴帽子、是否戴口罩、是否背包、是否吸烟、是否使用手机、人体朝向等。具体接口返回参数信息参考/ai-doc/BODY/Ak3cpyx6v。

import requestsimport base64request_url = "/rest/2.0/image-classify/v1/body_attr"f = open('test.jpg', 'rb') # 替换成自己的图片文件img = base64.b64encode(f.read())params = {"image":img}access_token = '【获取的access_token】'request_url = request_url + "?access_token=" + access_tokenheaders = {'content-type': 'application/x-www-form-urlencoded'}response = requests.post(request_url, data=params, headers=headers)if response:print (response.json())# 举例:判断是否佩戴口罩if int(response.json()['person_num'])>0:ismask = response.json()['person_info'][0]['attributes']['face_mask']['name']if ismask == "无口罩" or "不确定":print("请佩戴口罩!")

上面的识别很可能用到拍照,把代码放在下面,需要的话可以调用。

import cv2def takephoto(photo): #拍照,照片存为photo.jpgcap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # 打开摄像头while (1):ret, frame = cap.read()frame = cv2.flip(frame, 1) # 摄像头是和人对立的,将图像左右调换回来正常显示cv2.imshow("capture", frame) # 生成摄像头窗口if cv2.waitKey(1) & 0xFF == ord('q'): # 如果按下q 就截图保存并退出cv2.imwrite(photo+'.jpg', frame) # 保存路径breakcap.release()cv2.destroyAllWindows()takephoto('test') # 拍照并存储为'test.jpg'

2.高德开放平台

高德开放平台的使用分为3步:

第一步,申请Web服务API类型Key;

第二步,参考接口参数文档发起HTTP/HTTPS请求,第一步申请的 Key 需作为必填参数一同发送;

第三步,接收请求返回的数据(JSON或XML格式),参考返回参数文档解析数据。

2.1天气查询

import requestsimport xlrddef sfe(ans,flag=0):book=xlrd.open_workbook('citycode.xls')sh=book.sheet_by_index(0)nrow=sh.nrowsadcode='110000'for i in range(1,nrow):data=sh.row(i)cellcheck=sh.cell_value(i,flag)if ans in cellcheck:adcode=sh.cell_value(i,1)breakreturn adcodedef Weather(adcode):request_url = "/v3/weather/weatherInfo?city="+adcode+"&key=【你的key】"response = requests.get(request_url)str_weather = "未知"if response:str_weather=response.json()['lives'][0]['weather']return str_weathercity=input("请输入要查询的城市:")adcode = sfe(city)weather = Weather(adcode)print(city+"的天气为"+weather)

更多返回结果参数请参考天气查询-API文档-开发指南-Web服务 API | 高德地图API

2.2地理编码/逆地理编码

import requestsdef getLocation(address): # 地理编码request_url="/v3/geocode/geo?address="+address+"&key=【你的key】"response=requests.get(request_url)str_location="未知"if response:str_location=response.json()['geocodes'][0]['location']return str_locationdef getAddress(location): # 逆地理编码request_url="/v3/geocode/regeo?location="+location+"&key=【你的key】"response=requests.get(request_url)str_location="未知"if response:str_location=response.json()['regeocode']['formatted_address']return str_location

更多返回结果参数请参考地理/逆地理编码-API文档-开发指南-Web服务 API | 高德地图API

2.3路径规划

更多详细信息请参考路径规划-API文档-开发指南-Web服务 API | 高德地图API

路径规划可分为步行、驾车、公交、骑行等方面,下面以步行和公交路径规划为例,不同的规划只需要改变url和parameters,输出response.json(),解析JSON格式的数据,选择需要的信息。

import requestsdef walkplan(): # 步行路线规划url = '/v3/direction/walking?parameters'parameters = {'key': '【你的key】','origin': str(from_location), # 起始地点的经纬度'destination': str(to_location) # 目的地的经纬度}response = requests.get(url, parameters)if response:# print(response.json())count = response.json()['count']distance = response.json()['route']['paths'][0]['distance']duration = int(int(response.json()['route']['paths'][0]['duration'])/60) # 精确到分钟print("全程"+distance+"米,步行时间预计"+str(duration)+"分钟")print("共查询到"+count+"种方案")for i in range(0,int(count)):length = len(response.json()['route']['paths'][i]['steps'])instruction=[]for j in range(0,length):instruction.append(response.json()['route']['paths'][i]['steps'][j]['instruction'])print("第"+str(i+1)+"种方案的步行导航为:")print(instruction)instruction.clear()def busplan(): # 公交路线规划url = '/v3/direction/transit/integrated?parameters'parameters = {'key': '【你的key】','origin': str(from_location), # 起始地点的经纬度'destination': str(to_location) # 目的地的经纬度'city':'' # 城市/跨城规划时的起点城市}response = requests.get(url, parameters)if response:# print(response.json())json=response.json()count = json['count']transits = json['route']['transits']print("共查询到"+count+"种方案")for i in range(0,int(count)):print("方案"+str(i+1)+":")cost = transits[i]['cost']walkdistance = transits[i]['walking_distance']name = transits[i]['segments'][0]['bus']['buslines'][0]['name']station = transits[i]['segments'][0]['bus']['buslines'][0]['via_num']print("票价为"+str(cost)+"元")print("需要步行的距离为"+walkdistance+"米")print("公交名称为:"+name)print("需要经过"+station+"个站点")sta=[]for j in range(0,int(station)):sta.append(transits[i]['segments'][0]['bus']['buslines'][0]['via_stops'][j]['name'])print(sta)sta.clear()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。