質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

3123閲覧

PythonライブラリStreamlitを用いて、顔検出アプリの作成し、年齢、性別を表示させたい。

HYoshitaka

総合スコア14

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/01/16 04:10

PythonライブラリStreamlitとAzure Face APIを使って顔を検出するところまではできたのですが、
下記のコードだと年齢が表示されません。
原因と解決策をご教示ください。
合わせて、性別の表示方法もご教示いただければ幸いです。

python

1import streamlit as st 2from PIL import Image 3 4import requests 5from PIL import Image 6from PIL import ImageDraw 7from PIL import ImageFont 8import io 9import json 10 11st.title('顔認識アプリ') 12 13with open('secret.json') as f: 14 secret_json = json.load(f) 15 16subscription_key = secret_json["SUBSCRIPTION_KEY"] 17assert subscription_key 18 19face_api_url ='https://yoshifacerec.cognitiveservices.azure.com/face/v1.0/detect' 20 21 22uploaded_file = st.file_uploader("ここにイメージを挿入",type={'jpg','png'}) 23if uploaded_file is not None: 24 img1 = Image.open(uploaded_file) 25 with io.BytesIO() as output: 26 img1.save(output,format="JPEG") 27 binary_img =output.getvalue() 28 headers = { 29 'Content-Type':'application/octet-stream', 30 'Ocp-Apim-Subscription-Key': subscription_key 31} 32 33 params = { 34 'returnFaceId':'true', 35 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise' 36 37} 38 res =requests.post(face_api_url,params=params, 39 headers=headers,data=binary_img) 40 41 results =res.json() 42 for result in results: 43 rect =result['faceRectangle'] 44 age =result['age'] 45 46 47 draw =ImageDraw.Draw(img1) 48 draw.rectangle([(rect['left'],rect['top']),(rect['left']+rect['width'],rect['top']+rect['height'])],fill=None,outline='green',width=5) 49 50 font_size = 24 51 font_name = "C:\Windows\Fonts\meiryo.ttc" 52 src = r"pillow_test_src.png" 53 dest= r"pillow_test_dest.png" 54 draw_x = 140 55 draw_y = 120 56 text = draw.age 57 font = ImageFont.truetype(font_name, font_size) 58 59 res =requests.post(face_api_url,params=params, 60 headers=headers,data=binary_img) 61 62 st.image(img1,caption='アップロードされた写真',use_column_width=True)

エラー内容

KeyError: 'age' Traceback: File "c:\users\yoshi\anaconda3\lib\site-packages\streamlit\script_runner.py", line 332, in _run_script exec(code, module.__dict__) File "C:\Users\Yoshi\FR\FR.py", line 44, in <module> age =result['age']

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

いろいろ調べて改良したら走るようになりました。
参考にしたサイト:https://aokakes.hatenablog.com/entry/2018/11/02/214005

python

1import streamlit as st 2from PIL import Image 3 4import requests 5from PIL import Image 6from PIL import ImageDraw 7from PIL import ImageFont 8import io 9import json 10 11st.title('顔認識アプリ') 12 13with open('secret.json') as f: 14 secret_json = json.load(f) 15 16subscription_key = secret_json["SUBSCRIPTION_KEY"] 17assert subscription_key 18 19face_api_url ='https://yoshifacerec.cognitiveservices.azure.com/face/v1.0/detect' 20 21 22uploaded_file = st.file_uploader("ここにイメージを挿入",type={'jpg','png'}) 23if uploaded_file is not None: 24 img1 = Image.open(uploaded_file) 25 with io.BytesIO() as output: 26 img1.save(output,format="JPEG") 27 binary_img =output.getvalue() 28 headers = { 29 'Content-Type':'application/octet-stream', 30 'Ocp-Apim-Subscription-Key': subscription_key 31} 32 33 params = { 34 'returnFaceId':'true', 35 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise' 36 37} 38 res =requests.post(face_api_url,params=params, 39 headers=headers,data=binary_img) 40 41 draw =ImageDraw.Draw(img1) 42 font_size = 24 43 font_name = "C:\Windows\Fonts\meiryo.ttc" 44 src = r"pillow_test_src.png" 45 dest= r"pillow_test_dest.png" 46 47 results =res.json() 48 for result in results: 49 rect =result['faceRectangle'] 50 draw.rectangle([(rect['left'],rect['top']),(rect['left']+rect['width'],rect['top']+rect['height'])],fill=None,outline='green',width=5) 51 draw_x = rect['left']-30 52 draw_y = rect['top']-30 53 54 text = result['faceAttributes']['gender']+'/'+str(result['faceAttributes']['age']) 55# print(age,gender) 56 font = ImageFont.truetype(font_name, font_size) 57 draw.text((draw_x, draw_y), text,font=font, fill='red') 58 59 st.image(img1,caption="認識した写真",use_column_width=True)

投稿2021/01/17 10:25

HYoshitaka

総合スコア14

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

Azure Face APIのドキュメントより
レスポンスの構造を見ると、
ageは、faceAttributesフィールドの中にあるデータとなっています。

したがって、

for result in results: rect =result['faceRectangle'] age = result['faceAttributes']['age'] #<--修正

としてみてはいかがでしょうか。

合わせて、性別の表示方法もご教示いただければ幸いです。

下記になります。

gender = result['faceAttributes']['gender']

投稿2021/01/16 04:16

編集2021/01/16 04:33
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

HYoshitaka

2021/01/16 09:17

ご回答ありがとうございます。 ご教示の通りにコード修正したら、下記のようなエラーコードが出ました。 ------------------------------------------------------------------------- AttributeError: 'ImageDraw' object has no attribute 'age' Traceback: File "c:\users\yoshi\anaconda3\lib\site-packages\streamlit\script_runner.py", line 332, in _run_script exec(code, module.__dict__) File "C:\Users\Yoshi\FR\FR.py", line 56, in <module> text = draw.age -------------------------------------------------------------- ちなみにjsonのレスポンス内容は下記になります。 --------------------------------------------------------------- [{'faceId': '4d5eb01d-fb47-4925-b610-e9d1171be125', 'faceRectangle': {'top': 67, 'left': 76, 'width': 249, 'height': 249}, 'faceAttributes': {'smile': 0.291, 'headPose': {'pitch': -11.8, 'roll': 0.3, 'yaw': -16.3}, 'gender': 'female', 'age': 23.0, 'facialHair': {'moustache': 0.0, 'beard': 0.0, 'sideburns': 0.0}, 'glasses': 'NoGlasses', 'emotion': {'anger': 0.0, 'contempt': 0.002, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.291, 'neutral': 0.706, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'low', 'value': 0.0}, 'exposure': {'exposureLevel': 'overExposure', 'value': 0.84}, 'noise': {'noiseLevel': 'low', 'value': 0.04}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.46, 'invisible': False, 'hairColor': [{'color': 'brown', 'confidence': 0.98}, {'color': 'blond', 'confidence': 0.9}, {'color': 'red', 'confidence': 0.31}, {'color': 'gray', 'confidence': 0.21}, {'color': 'black', 'confidence': 0.17}, {'color': 'other', 'confidence': 0.09}, {'color': 'white', 'confidence': 0.0}]}}}] ---------------------------------------------------------------------------- 以上よろしくお願いいたします。
退会済みユーザー

退会済みユーザー

2021/01/16 10:38 編集

text=draw.age を text=age とすれば、とりあえず上記のエラーは解消されます。 しかし、それ以降のコードもめちゃくちゃなのでまた別のエラーが出ます。 直そうにも正直、font_size = 24以下の行からは明確な仕様(このようにしたい、という内容)を読み取ることはできません。 「年齢、性別を”表示”させたい」という質問に回答するなら 上記の回答( age = result['faceAttributes']['age'] に修正、 gender = result['faceAttributes']['gender'] の追加、 text=draw.ageを text=age に直す 、を行い、最後に print(age, gender) 以上です。 これ以上はエラーの修正ではなく、単に動く物を作れと言う「丸投げ」に近い状態といえますので、Streamlitの使い方について別質問を立てられることをお勧めします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問