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;








0















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()









share|improve this question




























    0















    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()









    share|improve this question
























      0












      0








      0








      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()









      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 3:48









      Al Mashud ShishirAl Mashud Shishir

      14




      14






















          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
          );



          );













          draft saved

          draft discarded


















          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















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현