如何将与post请求一起发送的图像发送给模型进行预测



我正在运行一个flask应用程序,该应用程序通过post请求接收base64编码的图像,并应将其发送分类。不幸的是,这就是我遇到错误的地方。这是我发出post请求的代码:

def encode_image(img_path):
with open(img_path, 'rb') as f:
encoded_string = base64.b64encode(f.read())
return encoded_string

def send_image(img_path):
img = encode_image(img_path)
data = {'imageBase64': img.decode('UTF-8')}
r = requests.post(url, data = json.dumps(data))
send_image('/path/to/image.jpg')

这是我的flask app代码:

@app.route('/', methods = ['POST'])
def predict():
if request.method == 'POST':  
base64img = request.data

base64img += b'=' * (-len(base64img) % 4)

img = base64.b64decode(base64img)
img = image.load_img(BytesIO(img), target_size = (28, 28), color_mode = 'grayscale')
img = Image.open(img)
img = image.img_to_array(image.load_img(BytesIO(img)), target_size = (28, 28))
payload = {
'instances': [{'input_image': img.to_list()}]
}
r = request.post(url, json = payload)
pred = json.loads(r.content.decode('utf-8'))
return pred

img = image.load_img(BytesIO(img))行抛出这个错误:

TypeError: expected str, bytes or os.PathLike object, not BytesIO

我不知道如何解决这个问题,有人有任何想法吗?

好的,我是这样做的:

@app.route('/', methods = ['POST'])
def predict():
if request.method == 'POST':
base64img = request.get_json()['img'].encode('utf-8')
img = base64.b64decode(base64img)
with open('imgtemp.png', 'wb') as f:
f.write(img)
img = cv2.imread('imgtemp.png', 1)

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
payload = {
'instances': [{'input_image': img.tolist()}]
}
r = requests.post(url, json = payload)
pred = json.loads(r.content.decode('utf-8'))
return pred

相关内容

  • 没有找到相关文章

最新更新