I changed the Python program created in Python x Flask x Tensorflow.Keras Web application that predicts cat breeds.
sever.py
from flask import Flask, render_template, request
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.models import load_model
import numpy as np
from image_process import examine_cat_breeds
from datetime import datetime
import os
import cv2
import pandas as pd
import base64
from io import BytesIO
app = Flask(__name__)
#model(model.h5)And a list of classes(cat_list)Read
model = load_model('model.h5')
cat_list = []
with open('cat_list.txt') as f:
cat_list = [s.strip() for s in f.readlines()]
print('= = cat_list = =')
print(cat_list)
@app.route("/", methods=["GET","POST"])
def upload_file():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
#Save the uploaded file once
f = request.files["file"]
#filepath = "./static/" + datetime.now().strftime("%Y%m%d%H%M%S") + ".png "
#f.save(filepath)
#Load image file
#Resize image file
input_img = load_img(f, target_size=(299, 299))
#Execution of a function to check the type of cat
result = examine_cat_breeds(input_img, model, cat_list)
print("result")
print(result)
no1_cat = result[0,0]
no2_cat = result[1,0]
no3_cat = result[2,0]
no1_cat_pred = result[0,1]
no2_cat_pred = result[1,1]
no3_cat_pred = result[2,1]
#Secure a buffer for writing images
buf = BytesIO()
#Write image data to buffer
input_img.save(buf,format="png")
#Encode binary data with base64
# utf-Decode at 8
input_img_b64str = base64.b64encode(buf.getvalue()).decode("utf-8")
#Add incidental information
input_img_b64data = "data:image/png;base64,{}".format(input_img_b64str)
#Pass to HTML
return render_template("index.html", input_img_b64data=input_img_b64data,
no1_cat=no1_cat, no2_cat=no2_cat, no3_cat=no3_cat,
no1_cat_pred=no1_cat_pred, no2_cat_pred=no2_cat_pred, no3_cat_pred=no3_cat_pred)
if __name__ == '__main__':
app.run(host="0.0.0.0")
index.html
<!DOCTYPE html>
<html>
<body>
{% if no1_cat %}
<img src="{{input_img_b64data}}" border="1" ><br>
Prediction result<br>
{{no1_cat}}:{{no1_cat_pred}}<br>
{{no2_cat}}:{{no2_cat_pred}}<br>
{{no3_cat}}:{{no3_cat_pred}}<br>
<hr>
{% endif %}
Please select a file and send<br>
<form action = "./" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
The image is displayed at 299 x 299 (the input size of the model remains ...)
Recommended Posts