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

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

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

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

Python

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

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

2回答

988閲覧

Raspberry piでのemoji-unicornhathdでDrawEmotion関連のエラーが出てしまう(FACE API)

maru19

総合スコア5

Raspberry Pi

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

Python

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

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

1クリップ

投稿2019/12/11 08:43

編集2019/12/13 05:57

前提・実現したいこと

Raspberry piをFACE APIを使用してemoji-unicornhathdの動作を試みています。

emoji-unicornhathd
github

上記を参考にしながら動作を試みたのですが、
数年前とFACE APIの内容が変わっておりうまく動作しません。

発生している問題・エラーメッセージ

pi@raspberrypi:~ $ python /home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py unicorn hat hd detected Unicorn HAT HD: Emoji Press Ctrl+C to exit! captured! face rectangle [] . . . . . captured! face rectangle [[224 130 172 172]] [{"faceId":"c5ed71c5-706a-4f25-b408-75189dd0f58a","faceRectangle":{"top":144,"left":223,"width":172,"height":172}}] Traceback (most recent call last): File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 123, in <module> drawEmotion(data) File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 64, in drawEmotion f_rec = face['scores'] KeyError: 'scores'

「/face/v1.0/detect?」を「/face/v1.0/detect?returnFaceAttributes=emotions」に変更した場合

Python

1pi@raspberrypi:~ $ python /home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py 2unicorn hat hd detected 3Unicorn HAT HD: Emoji 4 5Press Ctrl+C to exit! 6. 7. 8. 9. 10captured! 11face rectangle 12[[250 106 225 225]] 13{"error":{"code":"BadArgument","message":"Invalid argument returnFaceAttributes."}} 14Traceback (most recent call last): 15 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 126, in <module> 16 drawEmotion(data) 17 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 77, in drawEmotion 18 f_rec = face['scores'] 19TypeError: string indices must be integers 20 21

リクエストURLを私のエンドポイントにした場合
conn = httplib.HTTPSConnection('私の名前.cognitiveservices.azure.com')

Python

1captured! 2face rectangle 3[[442 327 76 76]] 4[Errno -3] Temporary failure in name resolution 5 6None 7Traceback (most recent call last): 8 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 127, in <module> 9 drawEmotion(data) 10 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 76, in drawEmotion 11 data = json.loads(data) 12 File "/usr/lib/python2.7/json/__init__.py", line 339, in loads 13 return _default_decoder.decode(s) 14 File "/usr/lib/python2.7/json/decoder.py", line 364, in decode 15 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 16TypeError: expected string or buffer 17

リクエストURLをconn = httplib.HTTPSConnection('japaneast.api.cognitive.microsoft.com')にした場合

Python

1captured! 2face rectangle 3[[212 106 220 220] 4 [544 392 46 46]] 5{"error":{"code":"BadArgument","message":"Invalid argument returnFaceAttributes."}} 6Traceback (most recent call last): 7 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 127, in <module> 8 drawEmotion(data) 9 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 78, in drawEmotion 10 f_rec = face['scores'] 11TypeError: string indices must be integers 12

conn.request("POST", "/face/v1.0/detect?returnFaceAttributes=emotions", image, headers)のemotionに書き直した場合

Python

1captured! 2face rectangle 3[[174 170 240 240]] 4[{"faceId":"222cb191-eac7-4f4d-bd12-85804a4f06ae","faceRectangle":{"top":186,"left":182,"width":237,"height":237},"faceAttributes":{"emotion":{"anger":0.0,"contempt":0.0,"disgust":0.0,"fear":0.0,"happiness":0.0,"neutral":0.956,"sadness":0.043,"surprise":0.0}}}] 5Traceback (most recent call last): 6 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 127, in <module> 7 drawEmotion(data) 8 File "/home/pi/emoji-unicornhathd/emoji-unicornhathd-stream.py", line 78, in drawEmotion 9 f_rec = face['scores'] 10KeyError: 'scores' 11

キャプチャした表情の感情はフィードバックされるものの、
最終的に達成したいRaspberry PiのHATに感情に適した絵文字を表示させることができない。

使用しているコード

emoji-unicornhathd/emoji-unicornhathd-stream.py
を使用しています。

Python

1 2# -*- encoding:utf-8 -*- 3 4import io 5import time 6import picamera 7import cv2 8import numpy as np 9import httplib 10import json 11import ssl 12ssl._create_default_https_context = ssl._create_unverified_context 13 14 15try: 16 import unicornhathd 17 print("unicorn hat hd detected") 18except ImportError: 19 from unicorn_hat_sim import unicornhathd 20 21print("""Unicorn HAT HD: Emoji 22 23Press Ctrl+C to exit! 24 25""") 26 27unicornhathd.rotation(0) 28 29# Azure API Key 30# ここを変更してください! 31api_key = 'ここは個人のKey入力しています。' 32 33# CV2 34cascade_path = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml" 35 36# Image Size 37camera_width = 640 38camera_height = 480 39 40##### 41def emoji_show(emoji): 42 R = np.load('/home/pi/emoji-unicornhathd/rgb/' + emoji + '_R.npy') 43 G = np.load('/home/pi/emoji-unicornhathd/rgb/' + emoji + '_G.npy') 44 B = np.load('/home/pi/emoji-unicornhathd/rgb/' + emoji + '_B.npy') 45 for x in range(0, 16): 46 for y in range(0, 16): 47 unicornhathd.set_pixel(x, y, R[x][y], G[x][y], B[x][y]) 48 unicornhathd.show() 49 50def getEmotion(image, headers): 51 try: 52 conn = httplib.HTTPSConnection('japaneast.api.cognitive.microsoft.com') 53 conn.request("POST", "/face/v1.0/detect?", image, headers) 54 response = conn.getresponse() 55 data = response.read() 56 conn.close() 57 return data 58 except Exception as e: 59 print("[Errno {0}] {1}".format(e.errno, e.strerror)) 60 print(e.message) 61 62def drawEmotion(data): 63 data = json.loads(data) 64 for face in data: 65 f_rec = face['scores'] 66 f_rec = sorted(f_rec.items(), key=lambda x:x[1],reverse = True) 67 emo = f_rec[0][0] 68 69 emoji_show(emo) 70 71 72##### 73 74 75try: 76 while True: 77 # Create the in-memory stream 78 stream = io.BytesIO() 79 emoji_show('camera') 80 with picamera.PiCamera() as camera: 81 camera.resolution = (camera_width, camera_height) 82 camera.capture(stream, format='jpeg') 83 print "captured!" 84 emoji_show('camera-with-flash') 85 time.sleep(0.5) 86 emoji_show('camera') 87 88 # Construct a numpy array from the stream 89 data = np.fromstring(stream.getvalue(), dtype=np.uint8) 90 # "Decode" the image from the array, preserving colour 91 image = cv2.imdecode(data, 1) 92 93 # Detect face 94 image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 95 cascade = cv2.CascadeClassifier(cascade_path) 96 facerect = cascade.detectMultiScale(image_gray, scaleFactor=1.1, minNeighbors=1, minSize=(1, 1)) 97 98 emoji_show('hourglass') 99 100 print "face rectangle" 101 print facerect 102 103 if len(facerect) > 0: 104 save_file_name = "face_detect.jpg" 105 106 cv2.imwrite(save_file_name, image) 107 108 headers = { 109 'Content-Type': 'application/octet-stream', 110 'Ocp-Apim-Subscription-Key': api_key, 111 } 112 image_load = open(save_file_name, 'rb') 113 data = getEmotion(image_load, headers) 114 print data 115 116 drawEmotion(data) 117 118 else: 119 emoji_show('no-face') 120 121 time.sleep(1) 122 print "." 123 time.sleep(1) 124 print "." 125 time.sleep(1) 126 print "." 127 time.sleep(1) 128 print "." 129 time.sleep(1) 130 print "." 131 132except KeyboardInterrupt: 133 unicornhathd.off()

試したこと

数年前とFACE API関連が変わっておりそこを修正しました。
また自分の環境に応じてパスを加えております。
しかし、カメラやUnicorn HAT HDは動作するものの表情を認識し、
HATにフィードバックする際にエラーが起きます。
いろいろ試しては見ましたがどうも、
「def drawEmotion(data)」**「f_rec = face['scores']」**辺りでエラーが発生します。
解決法方法などあればご教授お願いします。

補足情報(FW/ツールのバージョンなど)

・Raspberry Pi 3B+
Description: Raspbian GNU/Linux 10 (buster)
Release: 10
Codename: buster

・Raspberry Pi カメラモジュール V2
・Unicorn HAT HD

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

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

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

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

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

vanderlvov

2019/12/11 10:36

Urlをマークダウン形式に修正してください: [title](url)
maru19

2019/12/11 10:42

申し訳ございません。 修正致しました。
guest

回答2

0

ベストアンサー

さらに調べてみて、
https://www.indetail.co.jp/blog/12502/
にはソースがありました。
まず、apiは違うでしょう:

conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/emotion/v1.0/recognize?", image, headers)

しかし、APIは違うけど、レスポンスは似ているでしょう。
http://martink.me/articles/using-the-project-oxford-emotion-api
scoresの代わりに

f_rec = face['scores']

ではなくて

f_rec = face['faceAttributes']['emotions']

で同じのデータを取得できるはずです!

APIを正しく使ってみてください。

投稿2019/12/13 07:47

編集2019/12/13 07:49
vanderlvov

総合スコア685

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

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

maru19

2019/12/13 14:33

ありがとうございます! 遂に動作が可能となりました! Pythonを使い始めて1ヵ月ほどでずっと悩み続けていましたが、 あなたのおかげで動作することが可能となりうれしい限りです。 ここでは感謝しきれないほどです。 ご多忙にもかかわらず、何度も対応していただきありがとうございます。
vanderlvov

2019/12/13 14:47

おめでとうございます!嬉しいです。
guest

0

Face API公式ドキュメント によると、レスポンスオブジェクトは結構変わったようです。

解決方法:

  1. まず、エラーメッセージを見るとemotionsのデーターを取得してないと分かりました。
  2. 取得できるはずけど、取得してない原因は、APIの使い方が適切ではないでしょうね :)。このドキュメント「FACE API Detectについて」を見ると、リクエストはreturnFaceAttributesのパラメタが必要だと分かります。

/face/v1.0/detect?/face/v1.0/detect?returnFaceAttributes=emotionsにしてみてください。
レスポンスが変わるはずですよね。同じのドキュメントの中で、レスポンスオブジェクトの事例があります。
こうなるはずだと思います:

json

1[ 2 { 3 "faceId": "c5c24a82-6845-4031-9d5d-978df9175426", 4 "recognitionModel": "recognition_02", 5 "faceAttributes": { 6 "emotion": { 7 "anger": 0.575, 8 "contempt": 0, 9 "disgust": 0.006, 10 "fear": 0.008, 11 "happiness": 0.394, 12 "neutral": 0.013, 13 "sadness": 0, 14 "surprise": 0.004 15 } 16 } 17 } 18]

このレスポンス

[{"faceId":"222cb191-eac7-4f4d-bd12-85804a4f06ae","faceRectangle":{"top":186,"left":182,"width":237,"height":237},"faceAttributes":{"emotion":{"anger":0.0,"contempt":0.0,"disgust":0.0,"fear":0.0,"happiness":0.0,"neutral":0.956,"sadness":0.043,"surprise":0.0}}}]

には

{"emotion":{"anger":0.0,"contempt":0.0,"disgust":0.0,"fear":0.0,"happiness":0.0,"neutral":0.956,"sadness":0.043,"surprise":0.0}

それを使ってみてください。scoresはレスポンスにないので!

投稿2019/12/11 11:10

編集2019/12/13 07:28
vanderlvov

総合スコア685

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

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

maru19

2019/12/11 15:13

申し訳ございません。 返ってきているレスポンスというのはどのようなものでしょうか…? 一応上記のコードで表示されるエラーコードの全文を載せましたが、 Python初心者で、仰られている「レスポンス」の意味が間違っているかもしれません…。 お忙しいところ恐縮ですが、何卒宜しくお願い致します。
vanderlvov

2019/12/12 01:47

回答を更新しました。APIの使い方を再確認してください。
maru19

2019/12/12 14:37

ご返信ありがとうございます。 試したところ再度エラーが出てしまいました…。 エラーメッセージを追記しておきます。 いったい何が原因なのでしょうか。
vanderlvov

2019/12/12 15:44

リクエストのURLはどうなっていますか?
maru19

2019/12/13 05:38

ご返信ありがとうございます。 リクエストURLを私のエンドポイントにした場合と、 東日本の場合のリクエストURLをエラーコードに追加しました。 お忙しいところ恐縮ですが、ご教授いただければ幸いです。
maru19

2019/12/13 05:54

何度も申し訳ございません。 conn.request("POST", "/face/v1.0/detect?returnFaceAttributes=emotions", image, headers) をemotionと書き直したところ、感情は帰ってきたのですがやはり Raspberry PiのHATに感情に適した絵文字を表示させることはできませんでした。砂時計の絵文字で止まってしまいます。 その時のエラーコードも追加しておきます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問