Last time I even created a learning model.
This time, we will create an actual web application using the learning model and deploy it.
The completed image looks like this

main.py
#Import module
import cv2
import os
from flask import Flask, request, redirect, url_for, render_template, flash
from werkzeug.utils import secure_filename
from keras.models import Sequential, load_model
from keras.preprocessing import image
from PIL import Image
import tensorflow as tf
import numpy as np
from datetime import datetime
import face_recognition
#Player name
classes = ['Hinako Shibuno', 'Small celebration Sakura', 'Erika Hara']
num_classes = len(classes)
image_size = 64
#File to save the uploaded image
UPLOAD_FOLDER = "uploads/"
#Specify the extension that allows uploading
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
#Set up an instance of the Flask class
app = Flask(__name__)
#Define a function to check the extension of uploaded files
def allowed_file(filename):
    #First condition: in the variable filename'.'Does it contain the characters?
    #Second condition: variable filename.The character string after is ALLOWED_Which of the EXTENSIONS is applicable
    #In rsplit, the order of delimiter is "1" from the end of the character string. lower converts strings to lowercase
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#Detect face(haarcascade)
def detect_face(img_path):
    image = face_recognition.load_image_file(img_path)
    faces = face_recognition.face_locations(image)
    if len(faces)>0:
        face_max = [(abs(faces[i][0]-faces[i][2])) * (abs(faces[i][1]-faces[i][3])) for i in range(len(faces))]
        top, right, bottom, left = faces[face_max.index(max(face_max))]#There is no problem because only one person is shown
        faceImage = image[top:bottom, left:right]
        final = Image.fromarray(faceImage)
        final = np.asarray(final.resize((image_size,image_size)))
        final = Image.fromarray(final)
        basename = datetime.now().strftime("%Y%m%d-%H%M%S")
        filepath = UPLOAD_FOLDER + basename+".png "
        final.save(filepath)
        return final
    else:
        return "Please enter a face image"
#Load the trained model
model = load_model('./golfer.h5', compile=False)
graph = tf.get_default_graph()
# app.route()Associate the URL specified in the function with./ http://127.0.0.1:5000/Specify the following URL
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    global graph
    # as_default()Specify the target graph with
    with graph.as_default():
        #If the HTTP method is POST
        if request.method == 'POST':
            #Does the POST request contain file data?
            if 'file' not in request.files:
                flash('File does not exist')
                #redirect is a function that redirects to the argument URL
                return redirect(request.url)
            file = request.files['file']
            if file.filename == '':
                flash('File does not exist')
                return redirect(request.url)
            
            #If the file exists and is in an allowed format
            if file and allowed_file(file.filename):
                #If there is a dangerous character string in the file name, disable it.
                filename = secure_filename(file.filename)
                #Save to uploads folder
                file.save(os.path.join(UPLOAD_FOLDER, filename))
                #Create a file path
                filepath = os.path.join(UPLOAD_FOLDER, filename)
                
                # #Read the received image and convert it to np format
                img = image.load_img(filepath, grayscale=False, target_size=(image_size,image_size))
                #Detect the face part
                img = detect_face(filepath)
                if type(img)!=str:
                    img = image.img_to_array(img)
                    data = np.array([img])
                    #Pass the transformed data to the model for prediction
                    result = model.predict(data)[0]
                    predicted = result.argmax()
                    pred_answer = "This female professional" + str(classes[predicted]) + "is"
                    return render_template("index.html",answer=pred_answer)
                else:
                    return render_template("index.html",answer=img)
        return render_template("index.html",answer="")
#Solve the problem that CSS is not reflected during web application development in Flask
@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)
def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.root_path,
                                 endpoint, filename)
            values['q'] = int(os.stat(file_path).st_mtime)
    return url_for(endpoint, **values)
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 8080))
    app.run(host ='0.0.0.0',port = port)
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Female professional golfer judgment</title>
    <!-- <link rel="stylesheet" href="./static/stylesheet.css"> -->
    <link rel= "stylesheet" type= "text/css" 
            href= "{{ url_for('static',filename='stylesheet.css') }}">
</head>
<body>
    <header>   
        <a class="header-logo" href="#">Female professional golfer judgment</a>
    </header>
    <div class="main">    
        <h2>Identify the face in the image</h2>
        <p>Please send the image</p>
        <form method="POST" enctype="multipart/form-data">
            <input class="file_choose" type="file" name="file">
            <input class="btn" value="submit!" type="submit">
        </form>
        <div class="answer">{{answer}}</div>
    </div>
    <footer>
    </footer>
</body>
</html>
stylesheet.css
header {
    background-color: rgb(100, 81, 255);
    height: 100px;
    margin: -8px;
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
}
.header-logo {
    color: #fff;
    font-size: 30px;
    margin: auto;
}
.header_img {
    height: 25px;
    margin: 15px 25px;
}
.main {
    height: 370px;
}
h2 {
    color: #444444;
    margin: 90px 0px;
    text-align: center;
}
p {
    color: #444444;
    margin: 70px 0px 30px 0px;
    text-align: center;
}
.answer {
    margin: 70px 0px 30px 0px;
    text-align: center;
    font-size: 30px;
    color: blue;
    font-weight: bold;
}
form {
    text-align: center;
}
h2 {
    color: #444444;
    text-align: center;
}
footer {
    background-color: #F7F7F7;
    height: 110px;
    margin: -8px;
    position: relative;
}
.footer_img {
    height: 25px;
    margin: 15px 25px;
}
small {
    margin: 15px 25px;
    position: absolute;
    left: 0;
    bottom: 0;
}
The structure of the file is as follows

Index.html in the templates folder stylesheet.css in static folder
Please refer to this article for the remaining files [Complete version] Procedure for deploying API created with Flask to Heroku (Note)
Heroku Register here
$ heroku login
Create New App ⇨ Enter your App name to register your country in United States. Go to the app page, go to Setteings and click Add build pack to add Python.
git init
__ * Only the first time. If you do it twice, you will not be able to deploy successfully. __
heroku git:remote -a (app name)
git add .
git commit -m “(Write a message about what has changed)”
git push heroku master
__ Deployment is complete __
Check with the code below
heroku open
This completes the posting of the image application three times.
Recommended Posts