Last active
April 3, 2020 21:20
-
-
Save jitunayak/bdf57fccf0588496b753c45cdd4911de to your computer and use it in GitHub Desktop.
send image to flask REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import requests | |
import json | |
import cv2 | |
addr = 'http://localhost:5000' | |
test_url = addr + '/iamge/api' | |
# prepare headers for http request | |
content_type = 'image/jpeg' | |
headers = {'content-type': content_type} | |
img = cv2.imread('lena.jpg') | |
# encode image as jpeg | |
_, img_encoded = cv2.imencode('.jpg', img) | |
# send http request with image and receive response | |
response = requests.post(test_url, data=img_encoded.tostring(), headers=headers) | |
# decode response | |
print(json.loads(response.text)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, Response | |
import jsonpickle | |
import numpy as np | |
import cv2 | |
import os | |
# Initialize the Flask application | |
app = Flask(__name__) | |
# route http posts to this method | |
@app.route('/image/api', methods=['POST']) | |
def test(): | |
r = request | |
# convert string of image data to uint8 | |
nparr = np.fromstring(r.data, np.uint8) | |
# decode image | |
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
img2 = img | |
img_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) | |
os.chdir('/Users/jitunayak/Projects/python/image_rest_api') | |
cv2.imwrite("len_gray.jpg",img_gray) | |
print("Saved gray image") | |
# do some fancy processing here.... | |
# build a response dict to send back to client | |
response = {'message': 'image received. size={}x{}'.format(img.shape[1], img.shape[0]) | |
} | |
# encode response using jsonpickle | |
response_pickled = jsonpickle.encode(response) | |
return Response(response=response_pickled, status=200, mimetype="application/json") | |
# start flask app | |
app.run(host="0.0.0.0", port=5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment