Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. from flask import Flask, render_template, request
  2. from io import BytesIO
  3. from keras.preprocessing import image
  4. from keras.preprocessing.image import array_to_img, img_to_array
  5. from keras.models import load_model
  6. import os
  7. from PIL import Image
  8. import numpy as np
  9. from base64 import b64encode
  10.  
  11. from flask_bootstrap import Bootstrap
  12. from flask_wtf import FlaskForm
  13. from flask_wtf.file import FileField, FileRequired, FileAllowed
  14. from wtforms import SubmitField
  15.  
  16. # code which helps initialize our server
  17. app = Flask(__name__)
  18. app.config['SECRET_KEY'] = 'any secret key'
  19.  
  20. bootstrap = Bootstrap(app)
  21.  
  22. saved_model = load_model("models/model1.h5")
  23. saved_model._make_predict_function()
  24.  
  25. class UploadForm(FlaskForm):
  26. photo = FileField('Upload an image',validators=[FileAllowed(['jpg', 'png', 'jpeg'], u'Image only!'), FileRequired(u'File was empty!')])
  27. submit = SubmitField(u'Predict')
  28.  
  29. def preprocess(img):
  30. width, height = img.shape[0], img.shape[1]
  31. img = image.array_to_img(img, scale=False)
  32.  
  33. desired_width, desired_height = 100, 100
  34.  
  35. if width < desired_width:
  36. desired_width = width
  37. start_x = np.maximum(0, int((width-desired_width)/2))
  38.  
  39. img = img.crop((start_x, np.maximum(0, height-desired_height), start_x+desired_width, height))
  40. img = img.resize((100, 100))
  41.  
  42. img = image.img_to_array(img)
  43. return img / 255.
  44.  
  45. @app.route('/', methods=['GET','POST'])
  46. def predict():
  47. form = UploadForm()
  48. if form.validate_on_submit():
  49. print(form.photo.data)
  50. image_stream = form.photo.data.stream
  51. original_img = Image.open(image_stream)
  52. img = image.img_to_array(original_img)
  53. img = preprocess(img)
  54. img = np.expand_dims(img, axis=0)
  55. prediction = saved_model.predict_classes(img)
  56.  
  57. if (prediction[0][0]==0):
  58. result = "CACTUS"
  59. else:
  60. result = "NOT CACTUS"
  61.  
  62. byteIO = BytesIO()
  63. original_img.save(byteIO, format=original_img.format)
  64. byteArr = byteIO.getvalue()
  65. encoded = b64encode(byteArr)
  66.  
  67. return render_template('result.html', result=result, encoded_photo=encoded.decode('ascii'))
  68.  
  69. return render_template('index.html', form=form)
  70.  
  71. if __name__ == '__main__':
  72. app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement