Google 的VisionAPI提供了Label Detection、Face Detection和Logo Detection等等功能,本帖使用其中的Face Detection检测情绪(愤怒、高兴、伤心、惊喜)。(免费1000次请求/每月)
认证密钥的设置,参考文档: https://cloud.google.com/vision/docs/face-tutorial
fromgoogleapiclientimportdiscovery fromoauth2client.client importGoogleCredentials importbase64 defdetect_emotion(image_file_path): credentials = GoogleCredentials.get_application_default() service = discovery.build('vision', 'v1', credentials=credentials) withopen(image_file_path, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={ 'requests': [{ 'image': { 'content': image_content.decode('UTF-8') }, 'features': [{ 'type': 'FACE_DETECTION', 'maxResults': 10 }] }] }) response = service_request.execute() try: # 返回的json有一堆信息,提取要用的信息 anger = response['responses'][0]['faceAnnotations'][0]['angerLikelihood'] surprise = json_response['responses'][0]['faceAnnotations'][0]['surpriseLikelihood'] sorrow = json_response['responses'][0]['faceAnnotations'][0]['sorrowLikelihood'] joy = json_response['responses'][0]['faceAnnotations'][0]['joyLikelihood'] blurred = json_response['responses'][0]['faceAnnotations'][0]['blurredLikelihood'] print((<spanclass="pl-c1">str</span>(anger))) print((<spanclass="pl-c1">str</span>(surprise))) print((<spanclass="pl-c1">str</span>(sorrow))) print((<spanclass="pl-c1">str</span>(joy))) if(happy_string != "VERY_UNLIKELY"): print("高兴") elif(anger_string != "VERY_UNLIKELY"): print("愤怒") elif(surprise_string != "VERY_UNLIKELY"): print("惊喜") else: print("伤心") exceptExceptionas e: print(e)Share the post "使用Google的人脸检测API检测情绪-python"
Google+ Weibo Email