Python 如何修复';TypeError:bytes类型的对象不可JSON序列化';

Python 如何修复';TypeError:bytes类型的对象不可JSON序列化';,python,json,azure,serialization,azure-ai,Python,Json,Azure,Serialization,Azure Ai,我正在使用Microsoft Azures Vision API从本地JPEG图像识别手写文本。我正在编辑Microsofts的源代码,以允许从本地源而不是URL识别图像。但是,我不确定如何处理此错误:“TypeError:bytes类型的对象不可JSON序列化” image_path = "/Users/FelixWallis/Downloads/IMG_2430.jpg" image_data = open(image_path, "rb").read() headers = {'Ocp-

我正在使用Microsoft Azures Vision API从本地JPEG图像识别手写文本。我正在编辑Microsofts的源代码,以允许从本地源而不是URL识别图像。但是,我不确定如何处理此错误:“TypeError:bytes类型的对象不可JSON序列化”

image_path = "/Users/FelixWallis/Downloads/IMG_2430.jpg"

image_data = open(image_path, "rb").read()
headers = {'Ocp-Apim-Subscription-Key': subscription_key}

params  = {'mode': 'Handwritten'}
response = requests.post(
    text_recognition_url, headers=headers, params=params, json=image_data)
response.raise_for_status()


operation_url = response.headers["Operation-Location"]

analysis = {}
poll = True
while (poll):
    response_final = requests.get(
        response.headers["Operation-Location"], headers=headers)
    analysis = response_final.json()
    time.sleep(1)
    if ("recognitionResult" in analysis):
        poll= False 
    if ("status" in analysis and analysis['status'] == 'Failed'):
        poll= False

polygons=[]
if ("recognitionResult" in analysis):
    # Extract the recognized text, with bounding boxes.
    polygons = [(line["boundingBox"], line["text"])
        for line in analysis["recognitionResult"]["lines"]]

plt.figure(figsize=(15, 15))
image = Image.open(BytesIO(image_data))
ax = plt.imshow(image)
for polygon in polygons:
    vertices = [(polygon[0][i], polygon[0][i+1])
        for i in range(0, len(polygon[0]), 2)]
    text     = polygon[1]
    patch    = Polygon(vertices, closed=True, fill=False, linewidth=2, color='y')
    ax.axes.add_patch(patch)
    plt.text(vertices[0][0], vertices[0][1], text, fontsize=20, va="top")
_ = plt.axis("off")
回溯:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-9eba870c3121> in <module>
     32 params  = {'mode': 'Handwritten'}
     33 response = requests.post(
---> 34     text_recognition_url, headers=headers, params=params, json=image_data)
     35 response.raise_for_status()
     36 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py in post(url, data, json, **kwargs)
    114     """
    115 
--> 116     return request('post', url, data=data, json=json, **kwargs)
    117 
    118 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py in request(method, url, **kwargs)
     58     # cases, and look like a memory leak in others.
     59     with sessions.Session() as session:
---> 60         return session.request(method=method, url=url, **kwargs)
     61 
     62 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    517             hooks=hooks,
    518         )
--> 519         prep = self.prepare_request(req)
    520 
    521         proxies = proxies or {}

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py in prepare_request(self, request)
    460             auth=merge_setting(auth, self.auth),
    461             cookies=merged_cookies,
--> 462             hooks=merge_hooks(request.hooks, self.hooks),
    463         )
    464         return p

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json)
    314         self.prepare_headers(headers)
    315         self.prepare_cookies(cookies)
--> 316         self.prepare_body(data, files, json)
    317         self.prepare_auth(auth, url)
    318 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py in prepare_body(self, data, files, json)
    464             # provides this natively, but Python 3 gives a Unicode string.
    465             content_type = 'application/json'
--> 466             body = complexjson.dumps(json)
    467             if not isinstance(body, bytes):
    468                 body = body.encode('utf-8')

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    229         cls is None and indent is None and separators is None and
    230         default is None and not sort_keys and not kw):
--> 231         return _default_encoder.encode(obj)
    232     if cls is None:
    233         cls = JSONEncoder

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258 
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py in default(self, o)
    177 
    178         """
--> 179         raise TypeError(f'Object of type {o.__class__.__name__} '
    180                         f'is not JSON serializable')
    181 

TypeError: Object of type bytes is not JSON serializable
TypeError回溯(最近一次调用)
在里面
32参数={'mode':'handrited'}
33 response=requests.post(
--->34 text_recognition_url,headers=headers,params=params,json=image_data)
35响应。针对_状态提出_()
36
/post中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py(url、数据、json、**kwargs)
114     """
115
-->116返回请求('post',url,data=data,json=json,**kwargs)
117
118
/请求中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py(方法、url、**kwargs)
58个案例,其他案例看起来像是内存泄漏。
59带有会话。会话()作为会话:
--->60返回会话。请求(方法=方法,url=url,**kwargs)
61
62
/请求中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py(self、method、url、params、data、header、cookies、files、auth、timeout、allow_重定向、代理、hook、stream、verify、cert、json)
517挂钩=挂钩,
518         )
-->519准备=自我准备请求(req)
520
521代理=代理或{}
/prepare_request(self,request)中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py
460 auth=合并设置(auth,self.auth),
461 cookies=合并的\u cookies,
-->462钩子=合并钩子(request.hooks,self.hooks),
463         )
464返回p
/prepare中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py(self、method、url、header、files、data、params、auth、cookies、hooks、json)
314.自行准备_标题(标题)
315.自己准备饼干(饼干)
-->316.准备正文(数据、文件、json)
317 self.prepare\u auth(auth,url)
318
/prepare_body中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py(self、data、files、json)
464#以本机方式提供了此功能,但Python3提供了一个Unicode字符串。
465内容类型='application/json'
-->466 body=complexjson.dumps(json)
467如果不是isinstance(正文,字节):
468 body=body.encode('utf-8')
/库/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py在转储中(obj、skipkeys、sure_ascii、check_circular、allow_nan、cls、indent、分隔符、默认值、排序键、**kw)
229 cls为无,缩进为无,分隔符为无且
230默认值为无且不排序(U键且不为kw):
-->231返回默认编码器编码(obj)
232如果cls为无:
233 cls=JSONEncoder
/encode(self,o)中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py
例外情况没有那么详细。列表调用应该大致
198#相当于“”join()所使用的PySequence#Fast。
-->199 chunks=self.iterencode(o,\u one\u shot=True)
200如果不存在(块,(列表,元组)):
201块=列表(块)
/iterencode中的Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py(self,o,_one_shot)
255 self.key\u分隔符、self.item\u分隔符、self.sort\u键、,
256个自拍镜头(一张)
-->257返回码(o,0)
258
259定义生成代码(标记、默认、编码器、缩进、浮动、,
/默认情况下为Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py(self,o)
177
178         """
-->179 raise TypeError(f'类型为{o.\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\的对象'
180 f'不可JSON序列化')
181
TypeError:bytes类型的对象不可JSON序列化

根据您的代码和错误信息,问题是由于将本地图像的
图像\u数据
值传递到不正确的参数
json
(应该是
数据
)方法
请求中缺少本地图像的
内容类型
标题。post
,请仔细参阅

这是我的代码作为参考

import requests

image_path = '<the file path, like /Users/FelixWallis/Downloads/IMG_2430.jpg>'
image_data = open(image_path, "rb").read()

headers = {
    'Ocp-Apim-Subscription-Key': '<your subscription key>',
    'Content-Type': 'application/octet-stream'
}

params  = {'mode': 'Handwritten'}
text_recognition_url = 'https://<your cognitive service region, such as southeastasia for me>.api.cognitive.microsoft.com/vision/v2.0/recognizeText'
response = requests.post(text_recognition_url, headers=headers, params=params, data=image_data)

print(response.raw.status) # the result is 202
print(response.raise_for_status()) # the result is None

operation_url = response.headers["Operation-Location"]
print(operation_url) # the result for me is like https://southeastasia.api.cognitive.microsoft.com/vision/v2.0/textOperations/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
导入请求
图像路径=“”
image\u data=open(image\u路径,“rb”).read()
标题={
“Ocp Apim订阅密钥”:“,
“内容类型”:“应用程序/八位字节流”
}
params={'mode':'handrited'}
文本识别https://.api.cognitive.microsoft.com/vision/v2.0/recognizeText'
response=requests.post(text\u recognition\u url,headers=headers,params=params,data=image\u data)
打印(response.raw.status)#结果为202
打印(response.raise_for_status())#结果为无
operation\u url=response.headers[“操作位置”]
打印(操作url)#结果对我来说就像https://southeastasia.api.cognitive.microsoft.com/vision/v2.0/textOperations/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

不要使用“json”在requests.post中,但在files中:感谢您的建议。我尝试了您的修复,但不幸的是,Microsoft Vision不支持此媒体类型。HTTPError:415客户端错误:url的媒体类型不受支持:您有你还有其他想法吗?