Google Cloud Visionを使ってみようとしたときの「TypeError: Object of type 'bytes' is not JSON serializable」
久しぶりにGoogle Cloud Visionを使ってみようとしたら「TypeError: Object of type 'bytes' is not JSON serializable」。
巷に落ちているサンプルコードをそのまま試してみた。
それが次のようなやつ。
# 画像読み込み img_file_path = './input/' img_file_name = 'sample.jpg' img = open(img_file_path+img_file_name, 'rb') img_byte = img.read() img_content = base64.b64encode(img_byte) # リクエストBody作成 item = { 'requests': [{ 'image': { 'content': img_content }, 'features': [{ 'type': 'LABEL_DETECTION', 'maxResults': 10, }] }] } req_body = json.dumps(item)
そしたら、次のエラーが出たの。
TypeError: Object of type 'bytes' is not JSON serializable
ライブラリのバグなのか仕様変更なのか調べたら、ここで議論されているように「img_content = base64.b64encode(img_byte).decode("utf-8")」としてutf-8でdecodeすれば解決した。
なんで?base64encodeしてからutf-8でdecode。
# 画像読み込み img_file_path = './input/' img_file_name = 'sample.jpg' img = open(img_file_path+img_file_name, 'rb') img_byte = img.read() img_content = base64.b64encode(img_byte).decode("utf-8") # リクエストBody作成 item = { 'requests': [{ 'image': { 'content': img_content }, 'features': [{ 'type': 'LABEL_DETECTION', 'maxResults': 10, }] }] } req_body = json.dumps(item)