前提・実現したいこと
Raspberry piをFACE APIを使用してemoji-unicornhathdの動作を試みています。
上記を参考にしながら動作を試みたのですが、
数年前と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
回答2件
あなたの回答
tips
プレビュー