How to display dynamically and image? - python

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

Related

segmented image not displayed in flask app

I am making an image segmentation app which segments image into 'k' colors
the code for flask app goes like this:
##not pasting standard starting code
app.config['template_path'] = r'C:\Users\Asus\Documents\deep learning\deep_learn\NOTEBOOKS\app\templates'
def image_return():
if request.method == 'POST':
if request.files:
print('address accessed')
file = request.files['img']
k = request.values['k']
print('DONE FILE')
if not file.filename == '':
print('FILENAME EXISTS')
name = secure_filename(file.filename)
print(name)
address = os.path.join(
app.config['template_path'], 'uploads/', name)
file.save(address)
print('DONEEEE')
img = reader(address)
red_image, path = main(img, name, k)
print('image red. and saved to path')
return red_image, path
else:
redirect(request.url)
return flash('something went wrong try again')
# app.route('/transformed', methods=['POST'])
def transform():
red_image, path = image_return()
return render_template('imagetrans.html', address=path)
### ALL THE PRINT STATEMENTS RAN SUCCESSFULLY AND SAVED THE CONVERTED IMAGE TO THE PATH
## THE APPROACH I AM USING IS TO NOT DISPLAY LIVE IMAGE BUT TO SAVE IS FIRSTLY AND THEN DISPLAY IT FROM A SAVED LOCATION
the HTML goes like this:
<body>
<center>
<img src={{address}} alt="display.error" />
</center>
</body>
the python code for generating images works well
def color_reduction(img, k):
# transform the image
print(type(img))
data = np.float32(img).reshape((-1, 3))
# determine the criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)
# implementing k - means
ret, label, center = cv2.kmeans(
data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
result = center[label.flatten()]
result = result.reshape(img.shape)
return result
template_path = r'C:\Users\Asus\Documents\deep learning\deep_learn\NOTEBOOKS\app\templates\transformed'
def main(img, filename, k=5, title=None):
red_image = color_reduction(img, k=int(k))
path = os.path.join(template_path, f'{filename}_{k}.jpg')
cv2.imwrite(path, red_image)
return red_image, path
the reduced_image is not read in img src even after passing correct variable address
I think I am going wrong at the HTML part!
Have you checked what the value for address is in the html, i.e. if you look at the page source what does the address value render as in your browser?
I think this is probably going wrong since it looks like you are passing an absolute filepath to the html whereas really you should pass a path that is relative to the flask app instance.
i.e. if your flask app is in a folder called my_site then to src you would just pass the path from my_site to the image, i.e. my_site\static\img\img.jpg rather than C:\Users\Documents\projects\my_site\static\img\img.jpg.

Flask python Script runs before values are given

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)

Python Flask File Upload fails with 404 error

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.

Passing PIL PngImageFile to tensorflow for image recognition

I take an image in from the user and I want to pass it to tensorflow to determine what is in it:
#app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
i = Image.open(f)
image_handler(i)
def image_handler(image):
create_graph()
print("Model loaded")
node_lookup = NodeLookup()
print("Node lookup loaded")
print("Img: ")
print(image)
predictions = dict(run_inference_on_image(image))
print(predictions)
return jsonify(predictions=predictions)
image_handler() is using the functions and the NodeLookup class from the tensorflow imagenet repo found here:
https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py
The problem is when I run the app it will load fine, the user can select an image fine too but when they hit submit it get the following error when getting the predictions:
Expected binary or unicode string, got <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=200x200 at 0x243126ABA90>

How to update an existing Python Flask web page based on form input?

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)

Categories

Resources