I have a simple Flask python script where I want to via a form add 2 image paths, send those paths to python do stuff and send back a string. The problem I have is that the script runs before the form is filled out and the button is pressed. How to I make the script wait and only run on the press of the submit button?
Code for reference
#app.route('/', methods=['GET', 'POST'])
#app.route('/index')
def index():
PATH_REFERENCE = request.form.get("referencePhoto")
PATH_TEST = request.form.get("testPhoto")
testImage = cv2.imread(PATH_TEST)
reference = setupReference(PATH_REFERENCE)
face_locations, face_encodings = getFaceEmbeddingsFromImage(testImage, convertToRGB=True)
for location, face_encoding in zip(face_locations, face_encodings):
distances = face_recognition.face_distance(reference[0], face_encoding)
if distances <= 0.6:
result = 'Match!'
else:
result = 'Not Match!'
return render_template('index.html', title='Home', result=result)
The error is that The script cant do stuff with a NoneObject. Which makes sense condisering the form hasnt sent the paths needed.
Only do the form logic on a Post- on a get, just serve the form.
#app.route('/', methods=['GET', 'POST'])
#app.route('/index')
def index():
result = ""
if request.method == "POST":
PATH_REFERENCE = request.form.get("referencePhoto")
PATH_TEST = request.form.get("testPhoto")
testImage = cv2.imread(PATH_TEST)
reference = setupReference(PATH_REFERENCE)
face_locations, face_encodings = getFaceEmbeddingsFromImage(testImage, convertToRGB=True)
for location, face_encoding in zip(face_locations, face_encodings):
distances = face_recognition.face_distance(reference[0], face_encoding)
if distances <= 0.6:
result = 'Match!'
else:
result = 'Not Match!'
return render_template('index.html', title='Home', result=result)
Related
I want to show video frame image variable to HTML.
Here is my video code.
def webcam(queue, capture):
while True:
frame_pos = capture.get(cv2.CAP_PROP_POS_FRAMES)
frame_count = capture.get(cv2.CAP_PROP_FRAME_COUNT)
(grabbed, frame) = capture.read()
if not grabbed:
print ("Not grabbed.")
break;
if((frame_pos%50) == 0):
results = model.detect([frame], verbose=1)
# Visualize results
r = results[0]
masked_frame = display_instances(frame, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])
and this is flask code
def threaded() -> 'html':
app = Flask(__name__)
run_with_ngrok(app)
#app.route("/")
def home()-> 'html':
return render_template('test.html')
app.run()
I used these 2 functions by using thread like this
start_new_thread(threaded, ())
while True:
start_new_thread(webcam(enclosure_queue,capture), (enclosure_queue,))
I want the local variable 'masked_frame' to flask function and show it to HTML web page.
But I don't know what to do...
Can I get the local image variable in flask function?
And how to connect that to HTML?
Please help me
I have an image retrieval program in python, I want to make a web-based program using flask. But, I don't understand how to get input images from flask. So I can process the input image in my image retrieval program then show the result in my flask page.
here my flask code:
import os
from flask import Flask, flash, request, redirect, url_for, send_from_directory, Request, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'res/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return render_template('home.html')
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
app.run(host='0.0.0.0', port= 81)
and this is part of my image retrieval program, I need the input image from flask to fill 'inputImage.jpg' on my queryPath:
from PIL import Image
# Define path of testing data and indexing file
queryPath = root_path + 'inputImage.jpg'
index_file = root_path + 'mtcd.csv'
# define the bins for quantization
colorBins = 64
R_Bins = 4
G_Bins = 4
B_Bins = 4
edgeBins = 18
query = cv2.imread(queryPath)
# Color Quantization
colorQuant = combineColorQuantization(query, B_Bins, G_Bins, R_Bins)
# Edge Quantization
edgeQuant = edgeQuantization(query, edgeBins)
# Texton Search
features = textonSearch(colorQuant, colorBins, edgeQuant, edgeBins)
# GLCM
glcm, en = GLCM(query)
features.extend(glcm[0])
features.extend(glcm[1])
features.extend(glcm[2])
features.extend(en)
# perform the search
searcher = Searcher(index_file)
results = searcher.search(features)
# display the query
fig = figure(figsize=(5,5))
title('Query Image')
imshow(array(Image.open(queryPath)))
axis('off')
# loop over the results
fig = figure(num=None, figsize=(20,5))
title('Result Image')
result = []
i = 1
for (score, resultID) in results:
# load the result image and display it
a = fig.add_subplot(2, 6, i)
image = imread(root_path + 'batik/'+resultID)
i += 1
imshow(image)
axis('off')
print(result)
You can def the image processing code as a seperate function like this
def process_file(path)
# Define path of testing data and indexing file
queryPath = path
index_file = root_path + 'mtcd.csv'
# define the bins for quantization
colorBins = 64
R_Bins = 4
G_Bins = 4
B_Bins = 4
edgeBins = 18
query = cv2.imread(queryPath)
# Color Quantization
colorQuant = combineColorQuantization(query, B_Bins, G_Bins, R_Bins)
# Edge Quantization
edgeQuant = edgeQuantization(query, edgeBins)
# Texton Search
features = textonSearch(colorQuant, colorBins, edgeQuant, edgeBins)
# GLCM
glcm, en = GLCM(query)
features.extend(glcm[0])
features.extend(glcm[1])
features.extend(glcm[2])
features.extend(en)
# perform the search
searcher = Searcher(index_file)
results = searcher.search(features)
# display the query
fig = figure(figsize=(5,5))
title('Query Image')
imshow(array(Image.open(queryPath)))
axis('off')
# loop over the results
fig = figure(num=None, figsize=(20,5))
title('Result Image')
result = []
i = 1
for (score, resultID) in results:
# load the result image and display it
a = fig.add_subplot(2, 6, i)
image = imread(root_path + 'batik/'+resultID)
i += 1
imshow(image)
axis('off')
print(result)
call the process_file() method from flask route code block
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return render_template('home.html')
While following the Flask documentation / tutorials on how to upload a file I used this code:
main.py:
from flask import render_template, jsonify, Flask, redirect, url_for, request
from app import app
import random
import os
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
#app.route('/')
#app.route('/upload')
def upload_file2():
return render_template('index.html')
#app.route('/uploaded', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
path = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
model= ResNet50(weights='imagenet')
img = image.load_img(path, target_size=(224,224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
preds_decoded = decode_predictions(preds, top=3)[0]
print(decode_predictions(preds, top=3)[0])
f.save(path)
return render_template('uploaded.html', title='Success', predictions=preds_decoded, user_image=f.filename)
#app.route('/index')
def index():
return render_template('index.html', title='Home')
#app.route('/map')
def map():
return render_template('map.html', title='Map')
#app.route('/map/refresh', methods=['POST'])
def map_refresh():
points = [(random.uniform(48.8434100, 48.8634100),
random.uniform(2.3388000, 2.3588000))
for _ in range(random.randint(2, 9))]
return jsonify({'points': points})
#app.route('/contact')
def contact():
return render_template('contact.html', title='Contact')
Everything seems to be fine in the code. I have checked several times.
Well when running it on localhost on my Windows machine.
I get an 404 http-status-code (page not found).
I tried: on http://localhost:5000/ and http://localhost:5500/
Also I cleaned my browser...
Change
#app.route('/uploaded', methods = ['GET', 'POST'])
To
#app.route('/upload.php', methods = ['GET', 'POST'])
Or, change your front end form to post to uploaded.
Hello I am making an small page to show my results I am working in a project about sentiment analysis first I have the following labels:
senti=["furious","angry","angry0","Indiferent","happy","enthusiastic","Euphoric"]
I show this labels depending of the result of a predict function that I performed using keras, at this moment all is working well I wish to show an image depending of the label of above I tried creating an array with the path of the images as follows, I am not sure how to write the image function,
images=['home/image0.jpg','home/image1.jpg','home/image2.jpg','home/image3.jpg','home/image4.jpg','home/image5.jpg','home/image6.jpg']
def image():
This is the function that perform the predict, at this moment it is just showing a label of above, I would like to also display a distinct image, so I need to modify the following function:
def predict(text):
seqs = tok.texts_to_sequences([text])
print(text)
word_index = tok.word_index
print('Found %s unique tokens.' % len(word_index))
sequence_pred = sequence.pad_sequences(seqs, maxlen=MAX_SEQUENCE_LENGTH)
print(sequence_pred)
prediction = model.predict(sequence_pred)
print(prediction)
return senti[np.argmax(prediction[0])]
#app.route("/", methods=['GET', 'POST'])
def index():
print(request.method)
if request.method == 'POST':
q=request.form['querytext']
prediction=predict(q)
return render_template("result.html",prediction=prediction,text=q)
return render_template("main.html")
Since I am a beginner at flask I would like to appreciate support or suggestions to overcome this situation thanks for the help,
After a very useful feedback I tried:
senti=["furious","angry","angry0","Indiferent","happy","enthusiastic","Euphoric"]
def predict(text):
seqs = tok.texts_to_sequences([text])
print(text)
word_index = tok.word_index
print('Found %s unique tokens.' % len(word_index))
sequence_pred = sequence.pad_sequences(seqs, maxlen=MAX_SEQUENCE_LENGTH)
print(sequence_pred)
prediction = model.predict(sequence_pred)
print(prediction)
return senti[np.argmax(prediction[0])]
#app.route("/", methods=['GET', 'POST'])
def index():
senti=["furious","angry","angry0","Indiferent","happy","enthusiastic","Euphoric"]
images=['smile.jpg','smile.jpg','smile.jpg','smile.jpg','smile.jpg','smile.jpg','smile.jpg']
lookup_keys = dict(zip(senti, images))
print(request.method)
if request.method == 'POST':
q=request.form['querytext']
prediction=predict(q)
image_path = lookup_keys[prediction] # get the path
return render_template("result.html",
prediction=prediction,
text=q,
image_url=image_path)
return render_template("main.html")
I am not getting any error but the image is not displayed I am not so sure what is wrong, at this moment I am just trying with one image located at the same level of my file called app.py, smile.jpg
$ ls
app.py smile.jpg
Just create a dictionary of your keys and the image values; and use that to return the image for the particular sentiment:
>>> senti=["furious","angry","angry0","Indiferent","happy","enthusiastic","Euphoric"]
>>> images=['home/image0.jpg','home/image1.jpg','home/image2.jpg','home/image3.jpg','home/image4.jpg','home/image5.jpg','home/image6.jpg']
>>> dict(zip(senti, images))
{'enthusiastic': 'home/image5.jpg', 'Indiferent': 'home/image3.jpg', 'furious': 'home/image0.jpg', 'Euphoric': 'home/image6.jpg', 'angry': 'home/image1.jpg', 'happy': 'home/image4.jpg', 'angry0': 'home/image2.jpg'}
>>> lookup_values = dict(zip(senti, images))
>>> lookup_values['angry']
'home/image1.jpg'
You can use this in your view method, to get the right image path and the send it to the template:
#app.route("/", methods=['GET', 'POST'])
def index():
senti=["furious","angry","angry0","Indiferent","happy","enthusiastic","Euphoric"]
images=['home/image0.jpg','home/image1.jpg','home/image2.jpg','home/image3.jpg','home/image4.jpg','home/image5.jpg','home/image6.jpg']
lookup_keys = dict(zip(senti, images))
print(request.method)
if request.method == 'POST':
q=request.form['querytext']
prediction=predict(q)
image_path = lookup_keys[prediction] # get the path
return render_template("result.html",
prediction=prediction,
text=q,
image_url=image_path)
return render_template("main.html")
I am trying to build a prediction web application with Flask. The app should take in user input, process it through a python trained model, then display the results as a chart beside the input form.
My code looks like this:
HTML Form:
<form class = "prediction-options" method = "post" action = "/prediction/results">
<!--the input fields-->
</form>
Flask app.py
#app.route("/")
def main():
return render_template('index.html')
#app.route("/prediction/results", methods = ['POST'])
def predict():
input_aqi = float(request.form['aqi'])/272
input_pm2_5 = float(request.form['pm2_5'])/224
input_pm10 = float(request.form['pm10'])/283
input_so2 = float(request.form['so2'])/36
input_no2 = float(request.form['no2'])/110
input_co = float(request.form['co'])/1.83
input_o3 = float(request.form['o3'])/124
input_list = [[input_aqi,input_pm2_5,input_pm10,input_so2,input_no2,input_co,input_o3]]
output_acute_bronchitis = model_acute_bronchitis.predict(input_list)
output_asthma = model_asthma.predict(input_list)
output_asthmatic_bronchitis = model_asthmatic_bronchitis.predict(input_list)
output_aurti = model_aurti.predict(input_list)
output_bronchitis = model_bronchitis.predict(input_list)
output_pneumonia = model_pneumonia.predict(input_list)
d = collections.OrderedDict()
d['acute_bronchitis'] = output_acute_bronchitis[0]
d['asthma'] = output_asthma[0]
d['asthmatic_bronchitis'] = output_asthmatic_bronchitis[0]
d['aurti'] = output_aurti[0]
d['bronchitis'] = output_bronchitis[0]
d['pneumonia'] = output_pneumonia[0]
prediction = jsonify(d)
return prediction
Right now, I have managed to take in the user input and render the predicted results on the '/prediction/results' page. How can I get the results to show up on the '/' page? I tried to do this:
#app.route("/", methods = ['POST','GET'])
def main():
if request.method == 'POST':
def predict():
#predict function that returns prediction
return render_template('index.html')
But I always get a socket.error: [Errno 32] Broken pipe error message. What should I do?
You can use a session for this, before the last line in your predict route, store the prediction with
session['prediction'] = prediction
and then you can access in any other route in your application, for example you can have this for /
#app.route("/", methods = ['POST','GET'])
def main():
if request.method == 'POST':
pass
prediction = session['prediction']
return render_template('index.html', prediction=prediction)