Reputation:
I need send image from client via request library with some json data to flask server. I found some tips but everything was either confucing or doesn't work.
I guest that it will look something like:
image = open('some_image.pgm', 'rb')
description = {"author" : "Superman", "sex" : "male"}
url = "localhost://995/image"
request = requests.post(url, file = image, data = description)
Thanks in advance for your help.
Upvotes: 0
Views: 3503
Reputation: 31
You could encode the image in a string and send it in a json like this:
import requests
import cv2
import base64
img = cv2.imread('image.jpg')
string_img = base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()
req = {"author": "Superman", "sex" : "male", "image": string_img}
res = requests.post(YOUR_URL, json=req)
You can decode the image in the flask server like this:
import cv2
@app.route('/upload_image', methods=['POST'])
def upload_image():
req = request.json
img_str = req['image']
#decode the image
jpg_original = base64.b64decode(img_str)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
cv2.imwrite('./images.jpg', img)
Upvotes: 3