save pil or cv2 based image inside flask server and then serving that url for image rendering in the front end The 2019 Stack Overflow Developer Survey Results Are InHow can I save an image with PIL?Saving Image with PILHow to convert huge image from PIL to cv2Twitter oauth with flask_oauthlib, Failed to generate request tokenFlask with mod_wsgi - Cannot call my modulesDeploying structured Flask app on EB - View function mapping errorOpenCV python layer is not working with caffe/digits frameworkHow to upload and display an image in Flaskcv2.imshow() not responding after showing few images to a window one by one when images are coming from front end
Is there a symbol for a right arrow with a square in the middle?
What is the meaning of the verb "bear" in this context?
Pokemon Turn Based battle (Python)
How can I autofill dates in Excel excluding Sunday?
Is a "Democratic" Oligarchy-Style System Possible?
Is an up-to-date browser secure on an out-of-date OS?
Why not take a picture of a closer black hole?
Are there any other methods to apply to solving simultaneous equations?
Why hard-Brexiteers don't insist on a hard border to prevent illegal immigration after Brexit?
Identify boardgame from Big movie
Do these rules for Critical Successes and Critical Failures seem Fair?
What does Linus Torvalds mean when he says that Git "never ever" tracks a file?
How to manage monthly salary
Is flight data recorder erased after every flight?
Falsification in Math vs Science
Why isn't the circumferential light around the M87 black hole's event horizon symmetric?
A poker game description that does not feel gimmicky
Can you compress metal and what would be the consequences?
Aging parents with no investments
Why do we hear so much about the Trump administration deciding to impose and then remove tariffs?
Why is the maximum length of OpenWrt’s root password 8 characters?
Why do UK politicians seemingly ignore opinion polls on Brexit?
When should I buy a clipper card after flying to OAK?
How to answer pointed "are you quitting" questioning when I don't want them to suspect
save pil or cv2 based image inside flask server and then serving that url for image rendering in the front end
The 2019 Stack Overflow Developer Survey Results Are InHow can I save an image with PIL?Saving Image with PILHow to convert huge image from PIL to cv2Twitter oauth with flask_oauthlib, Failed to generate request tokenFlask with mod_wsgi - Cannot call my modulesDeploying structured Flask app on EB - View function mapping errorOpenCV python layer is not working with caffe/digits frameworkHow to upload and display an image in Flaskcv2.imshow() not responding after showing few images to a window one by one when images are coming from front end
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am updating an image sent through post method using cv2 in the flask backend.
Then when I am trying to save that image using cv2.imwrite() to a path inside the flask server and then send that path as image-src response back,its unable to find the file.I have also tried to convert the opencv version image to pillow based image and then save it to the flask server,but also failed.I mainly want to know how can I save the image using cv2/pillow inside the flask backend and serve that url as image source to render in the front-end.
My code is below:
# import the necessary packages
from PIL import Image
import numpy as np
import flask
import io
import base64
from flask import request, render_template, Flask
import cv2
from keras.models import model_from_json
import re, os
import uuid
# initialize our Flask application and the Keras model
model = None
full_path = None
def create_app():
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.config["UPLOAD_FOLDER"]=os.path.join(APP_ROOT,"uploads")
def load_model():
print("hello")
global model
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights("model.h5")
print("Loaded model from disk")
model.compile(loss='categorical_crossentropy',
optimizer="rmsprop",
metrics=['accuracy'])
load_model()
return app
app = create_app()
def do_prediction(im):
global full_path
label_map = ["Angry", "Fear", "Happy",
"Sad", "Surprise", "Neutral"]
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
print(im)
face_cascade = cv2.CascadeClassifier("cascade_frontface.xml")
faces = face_cascade.detectMultiScale(gray, 1.2, 3, minSize=(80, 80))
print(len(faces))
font = cv2.FONT_HERSHEY_SIMPLEX
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)
face_crop = im[y:y + h, x:x + w]
face_crop = cv2.resize(face_crop, (48, 48))
face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
face_crop = face_crop.astype('float32') / 255.0
face_crop = np.asarray(face_crop)
face_crop = face_crop.reshape(
1, face_crop.shape[0], face_crop.shape[1], 1)
result = label_map[np.argmax(model.predict(face_crop))]
cv2.putText(im, result, (x, y), font, 2, (200, 0, 0), 3, cv2.LINE_AA)
random_value = str(uuid.uuid4())
new_image = random_value + ".jpg"
if not os.path.isdir(app.config["UPLOAD_FOLDER"]):
os.mkdir(app.config["UPLOAD_FOLDER"])
full_path = os.path.join(app.config['UPLOAD_FOLDER'], new_image)
# cv2.imshow("image",im)
# cv2.imwrite(full_path, im)
# predicted_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
pil_image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
updated_image = Image.fromarray(pil_image, mode='RGB')
print("converted to pil")
print(updated_image)
updated_image.save(full_path,'JPEG')
@app.route("/", methods=["GET"])
def index():
return render_template("predict.html")
@app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
data = "success": False
message = request.get_json(force=True)
encoded = message["image"]
encoded = re.sub('^data:image/.+;base64,', '', encoded)
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
open_cv_image = cv2.cvtColor(np.array(image),cv2.COLOR_RGB2BGR)
# # Convert RGB to BGR
# open_cv_image = open_cv_image[:, :, ::-1].copy()
print(open_cv_image)
# classify the input image and then initialize the list
# of predictions to return to the client
do_prediction(open_cv_image)
# indicate that the request was a success
data["success"] = True
data["image"] = full_path
# return the data dictionary as a JSON response
return flask.jsonify(data)
if __name__ == "__main__":
app.run()
python opencv flask python-imaging-library
add a comment |
I am updating an image sent through post method using cv2 in the flask backend.
Then when I am trying to save that image using cv2.imwrite() to a path inside the flask server and then send that path as image-src response back,its unable to find the file.I have also tried to convert the opencv version image to pillow based image and then save it to the flask server,but also failed.I mainly want to know how can I save the image using cv2/pillow inside the flask backend and serve that url as image source to render in the front-end.
My code is below:
# import the necessary packages
from PIL import Image
import numpy as np
import flask
import io
import base64
from flask import request, render_template, Flask
import cv2
from keras.models import model_from_json
import re, os
import uuid
# initialize our Flask application and the Keras model
model = None
full_path = None
def create_app():
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.config["UPLOAD_FOLDER"]=os.path.join(APP_ROOT,"uploads")
def load_model():
print("hello")
global model
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights("model.h5")
print("Loaded model from disk")
model.compile(loss='categorical_crossentropy',
optimizer="rmsprop",
metrics=['accuracy'])
load_model()
return app
app = create_app()
def do_prediction(im):
global full_path
label_map = ["Angry", "Fear", "Happy",
"Sad", "Surprise", "Neutral"]
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
print(im)
face_cascade = cv2.CascadeClassifier("cascade_frontface.xml")
faces = face_cascade.detectMultiScale(gray, 1.2, 3, minSize=(80, 80))
print(len(faces))
font = cv2.FONT_HERSHEY_SIMPLEX
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)
face_crop = im[y:y + h, x:x + w]
face_crop = cv2.resize(face_crop, (48, 48))
face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
face_crop = face_crop.astype('float32') / 255.0
face_crop = np.asarray(face_crop)
face_crop = face_crop.reshape(
1, face_crop.shape[0], face_crop.shape[1], 1)
result = label_map[np.argmax(model.predict(face_crop))]
cv2.putText(im, result, (x, y), font, 2, (200, 0, 0), 3, cv2.LINE_AA)
random_value = str(uuid.uuid4())
new_image = random_value + ".jpg"
if not os.path.isdir(app.config["UPLOAD_FOLDER"]):
os.mkdir(app.config["UPLOAD_FOLDER"])
full_path = os.path.join(app.config['UPLOAD_FOLDER'], new_image)
# cv2.imshow("image",im)
# cv2.imwrite(full_path, im)
# predicted_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
pil_image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
updated_image = Image.fromarray(pil_image, mode='RGB')
print("converted to pil")
print(updated_image)
updated_image.save(full_path,'JPEG')
@app.route("/", methods=["GET"])
def index():
return render_template("predict.html")
@app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
data = "success": False
message = request.get_json(force=True)
encoded = message["image"]
encoded = re.sub('^data:image/.+;base64,', '', encoded)
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
open_cv_image = cv2.cvtColor(np.array(image),cv2.COLOR_RGB2BGR)
# # Convert RGB to BGR
# open_cv_image = open_cv_image[:, :, ::-1].copy()
print(open_cv_image)
# classify the input image and then initialize the list
# of predictions to return to the client
do_prediction(open_cv_image)
# indicate that the request was a success
data["success"] = True
data["image"] = full_path
# return the data dictionary as a JSON response
return flask.jsonify(data)
if __name__ == "__main__":
app.run()
python opencv flask python-imaging-library
add a comment |
I am updating an image sent through post method using cv2 in the flask backend.
Then when I am trying to save that image using cv2.imwrite() to a path inside the flask server and then send that path as image-src response back,its unable to find the file.I have also tried to convert the opencv version image to pillow based image and then save it to the flask server,but also failed.I mainly want to know how can I save the image using cv2/pillow inside the flask backend and serve that url as image source to render in the front-end.
My code is below:
# import the necessary packages
from PIL import Image
import numpy as np
import flask
import io
import base64
from flask import request, render_template, Flask
import cv2
from keras.models import model_from_json
import re, os
import uuid
# initialize our Flask application and the Keras model
model = None
full_path = None
def create_app():
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.config["UPLOAD_FOLDER"]=os.path.join(APP_ROOT,"uploads")
def load_model():
print("hello")
global model
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights("model.h5")
print("Loaded model from disk")
model.compile(loss='categorical_crossentropy',
optimizer="rmsprop",
metrics=['accuracy'])
load_model()
return app
app = create_app()
def do_prediction(im):
global full_path
label_map = ["Angry", "Fear", "Happy",
"Sad", "Surprise", "Neutral"]
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
print(im)
face_cascade = cv2.CascadeClassifier("cascade_frontface.xml")
faces = face_cascade.detectMultiScale(gray, 1.2, 3, minSize=(80, 80))
print(len(faces))
font = cv2.FONT_HERSHEY_SIMPLEX
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)
face_crop = im[y:y + h, x:x + w]
face_crop = cv2.resize(face_crop, (48, 48))
face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
face_crop = face_crop.astype('float32') / 255.0
face_crop = np.asarray(face_crop)
face_crop = face_crop.reshape(
1, face_crop.shape[0], face_crop.shape[1], 1)
result = label_map[np.argmax(model.predict(face_crop))]
cv2.putText(im, result, (x, y), font, 2, (200, 0, 0), 3, cv2.LINE_AA)
random_value = str(uuid.uuid4())
new_image = random_value + ".jpg"
if not os.path.isdir(app.config["UPLOAD_FOLDER"]):
os.mkdir(app.config["UPLOAD_FOLDER"])
full_path = os.path.join(app.config['UPLOAD_FOLDER'], new_image)
# cv2.imshow("image",im)
# cv2.imwrite(full_path, im)
# predicted_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
pil_image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
updated_image = Image.fromarray(pil_image, mode='RGB')
print("converted to pil")
print(updated_image)
updated_image.save(full_path,'JPEG')
@app.route("/", methods=["GET"])
def index():
return render_template("predict.html")
@app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
data = "success": False
message = request.get_json(force=True)
encoded = message["image"]
encoded = re.sub('^data:image/.+;base64,', '', encoded)
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
open_cv_image = cv2.cvtColor(np.array(image),cv2.COLOR_RGB2BGR)
# # Convert RGB to BGR
# open_cv_image = open_cv_image[:, :, ::-1].copy()
print(open_cv_image)
# classify the input image and then initialize the list
# of predictions to return to the client
do_prediction(open_cv_image)
# indicate that the request was a success
data["success"] = True
data["image"] = full_path
# return the data dictionary as a JSON response
return flask.jsonify(data)
if __name__ == "__main__":
app.run()
python opencv flask python-imaging-library
I am updating an image sent through post method using cv2 in the flask backend.
Then when I am trying to save that image using cv2.imwrite() to a path inside the flask server and then send that path as image-src response back,its unable to find the file.I have also tried to convert the opencv version image to pillow based image and then save it to the flask server,but also failed.I mainly want to know how can I save the image using cv2/pillow inside the flask backend and serve that url as image source to render in the front-end.
My code is below:
# import the necessary packages
from PIL import Image
import numpy as np
import flask
import io
import base64
from flask import request, render_template, Flask
import cv2
from keras.models import model_from_json
import re, os
import uuid
# initialize our Flask application and the Keras model
model = None
full_path = None
def create_app():
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.config["UPLOAD_FOLDER"]=os.path.join(APP_ROOT,"uploads")
def load_model():
print("hello")
global model
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights("model.h5")
print("Loaded model from disk")
model.compile(loss='categorical_crossentropy',
optimizer="rmsprop",
metrics=['accuracy'])
load_model()
return app
app = create_app()
def do_prediction(im):
global full_path
label_map = ["Angry", "Fear", "Happy",
"Sad", "Surprise", "Neutral"]
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
print(im)
face_cascade = cv2.CascadeClassifier("cascade_frontface.xml")
faces = face_cascade.detectMultiScale(gray, 1.2, 3, minSize=(80, 80))
print(len(faces))
font = cv2.FONT_HERSHEY_SIMPLEX
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)
face_crop = im[y:y + h, x:x + w]
face_crop = cv2.resize(face_crop, (48, 48))
face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
face_crop = face_crop.astype('float32') / 255.0
face_crop = np.asarray(face_crop)
face_crop = face_crop.reshape(
1, face_crop.shape[0], face_crop.shape[1], 1)
result = label_map[np.argmax(model.predict(face_crop))]
cv2.putText(im, result, (x, y), font, 2, (200, 0, 0), 3, cv2.LINE_AA)
random_value = str(uuid.uuid4())
new_image = random_value + ".jpg"
if not os.path.isdir(app.config["UPLOAD_FOLDER"]):
os.mkdir(app.config["UPLOAD_FOLDER"])
full_path = os.path.join(app.config['UPLOAD_FOLDER'], new_image)
# cv2.imshow("image",im)
# cv2.imwrite(full_path, im)
# predicted_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
pil_image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
updated_image = Image.fromarray(pil_image, mode='RGB')
print("converted to pil")
print(updated_image)
updated_image.save(full_path,'JPEG')
@app.route("/", methods=["GET"])
def index():
return render_template("predict.html")
@app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
data = "success": False
message = request.get_json(force=True)
encoded = message["image"]
encoded = re.sub('^data:image/.+;base64,', '', encoded)
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
open_cv_image = cv2.cvtColor(np.array(image),cv2.COLOR_RGB2BGR)
# # Convert RGB to BGR
# open_cv_image = open_cv_image[:, :, ::-1].copy()
print(open_cv_image)
# classify the input image and then initialize the list
# of predictions to return to the client
do_prediction(open_cv_image)
# indicate that the request was a success
data["success"] = True
data["image"] = full_path
# return the data dictionary as a JSON response
return flask.jsonify(data)
if __name__ == "__main__":
app.run()
python opencv flask python-imaging-library
python opencv flask python-imaging-library
asked Mar 22 at 3:48
Al Mashud ShishirAl Mashud Shishir
14
14
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292619%2fsave-pil-or-cv2-based-image-inside-flask-server-and-then-serving-that-url-for-im%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292619%2fsave-pil-or-cv2-based-image-inside-flask-server-and-then-serving-that-url-for-im%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown