我有一个MongoDB,其中一些小的图像样本存储为Base64。 我的目标是用python创建一个脚本,witch能够读取这些脚本并向API发送多部分/表单请求。 以下是API在postman上的外观:
实际上,这是我用python编写的代码:
from pymongo import MongoClient
import numpy as np
import cv2
import base64
import requests
def readb64(base64_string):
sbuf = StringIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
client = MongoClient("mongodb://root:example@localhost:27017/")
mydb = client["image"]
mycol = mydb["samples"]
mydoc = mycol.find( { "api_shape_processed": False},
{ "_id": 1,"samples.eroded_sample_inverted_b64": 1}
)
url = 'http://localhost:8000/prediction/'
for x in mydoc:
payload = {base64.b64decode(x)}
files = {"foo": "bar"}
response = requests.put(url, data=payload, file=files)
运行时,我收到以下错误消息:
raise TypeError("argument should be a bytes-like object or ASCII "
TypeError: argument should be a bytes-like object or ASCII string, not 'dict'
我不知道如何创建正确的请求来正确调用API。 如有任何意见,请提前通知Thx
更新
使用上面检索到的记录的查询:
{'_id': ObjectId('5fe0d16baa01291a71c5bf55'), 'samples': [{'eroded_sample_inverted_b64': '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr........'}, {'eroded_sample_inverted_b64': '/9j/4AAQSkZJR.......}]}
如果我使用此sintax生成有效负载:
for x in mydoc:
payload = {base64.b64decode(x['samples']['eroded_sample_inverted_b64'])}
print(payload)
我得到这个错误:
payload = {base64.b64decode(x['samples']['eroded_sample_inverted_b64'])}
TypeError: list indices must be integers or slices, not str
更新2 使用此代码:
url = 'http://localhost:8000/prediction/'
for x in mydoc:
for sample in x.get('samples', []):
payload = {base64.b64decode(sample['eroded_sample_inverted_b64'])}
nparr = np.fromstring(base64.b64decode(sample['eroded_sample_inverted_b64']), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
files={"foo": "bar"}
response = requests.post(url, data={'File': cv2.imdecode(nparr, cv2.IMREAD_COLOR)}, files=files)
print(response)
我从API端获得此错误:
"POST /prediction/ HTTP/1.1" 422 Unprocessable Entity
我真的不明白如何正确地塑造POST请求
samples
是一个列表,因此您必须迭代该列表;e、 g印刷品:
当您使用
find()
迭代游标时,每个文档将表示为dict
项;因此,您将传递整个文档进行解码,而不是传递带有编码数据的特定字段这可能更接近您的需要:
相关问题 更多 >
编程相关推荐