Perquisites
- Want machine studying mannequin(with .h5 extension).By way of this rationalization I used sing language detection mannequin.
- Establish the labels that are used for coaching the mannequin. For an instance should you practice mannequin for determine canines and cats then classification labels have to be “canine and cat”.
- Set up python model 3.8.0 should you’re not set up already and set path accurately.
- Set up vs code should you’re not set up already.
- Make listing any location no matter you need and open it utilizing vs code.
- Open terminal and run under instructions.
python -m pip set up --upgrade pip --user
pip set up flask --user
pip set up pillow --user
pip set up tensorflow --user
pip set up numpy --user
pip set up keras --user
Step 1: Make folder construction
Inside root listing make a listing referred to as templates and inside it creates two html information corresponding to index.html and end result.html
Then navigate once more into root director and create remainder of the information app.py ,model_name.h5 ,labels.txt and requirments.txt information.
index.html file makes use of for present the house web page and thru web page consumer capable of add photos.
end result.html file makes use of for exhibiting end result which is returning by mannequin.
app.py is the center of the code. all of the implementation elements are included right here.
labele.txt file embrace all of the labels which imply the way in which that we categorised the mannequin
requirments.txt makes use of for together with all the necessities libraries .This file import as soon as if we set up this method in one other computer.
Step 2 : Import related libraries.
Under information possibly range and a few fashions want extra libraries. Generally under information are used.
from flask import Flask, render_template, request, jsonify
from keras.fashions import load_model
from PIL import Picture, ImageOps
import numpy as np
import os
Step 3 : Initialize loading mannequin.
app = Flask(__name__)mannequin = load_model("keras_model.h5", compile=False)
class_names = open("labels.txt", "r").readlines()
Step 4 : Initialize variable for storing uploaded information.
uploaded_files = []
Step 5 : Initialize preprocessing half.
def preprocess_image(image_path):
picture = Picture.open(image_path).convert("RGB")
measurement = (224, 224)
picture = ImageOps.match(picture, measurement, Picture.Resampling.LANCZOS)
image_array = np.asarray(picture)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
information = np.ndarray(form=(1, 224, 224, 3), dtype=np.float32)
information[0] = normalized_image_array
return information
Step 6 : Outline path to render the index.html template.
@app.route('/')
def house():
return render_template('index.html')
Step 7 : Outline route and relent code for the dealing with the prediction course of
@app.route('/predict', strategies=['POST'])
def predict():
world uploaded_files
if request.technique == 'POST':
information = request.information.getlist('information[]')
predictions = []
for file in information:
file_path = os.path.be a part of("uploads", file.filename)
file.save(file_path)
uploaded_files.append(file_path)
information = preprocess_image(file_path)
prediction = mannequin.predict(information)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
return jsonify({
"standing": "uploaded",
"message": "Photos uploaded efficiently."
})
Step 8 : Outline route and relent code for the airing end result.
@app.route('/final_result')
def final_result():
world uploaded_files
predictions = []
for file_path in uploaded_files:
information = preprocess_image(file_path)
prediction = mannequin.predict(information)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
uploaded_files = [] # Clear uploaded information for subsequent submission
return render_template('end result.html', predictions=predictions)
Step 9 : Accomplished app.py code
from flask import Flask, render_template, request, jsonify
from keras.fashions import load_model
from PIL import Picture, ImageOps
import numpy as np
import osapp = Flask(__name__)
mannequin = load_model("keras_model.h5", compile=False)
class_names = open("labels.txt", "r").readlines()
def preprocess_image(image_path):
picture = Picture.open(image_path).convert("RGB")
measurement = (224, 224)
picture = ImageOps.match(picture, measurement, Picture.Resampling.LANCZOS)
image_array = np.asarray(picture)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
information = np.ndarray(form=(1, 224, 224, 3), dtype=np.float32)
information[0] = normalized_image_array
return information
uploaded_files = []
@app.route('/predict', strategies=['POST'])
def predict():
world uploaded_files
if request.technique == 'POST':
information = request.information.getlist('information[]')
predictions = []
for file in information:
file_path = os.path.be a part of("uploads", file.filename)
file.save(file_path)
uploaded_files.append(file_path)
information = preprocess_image(file_path)
prediction = mannequin.predict(information)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
return jsonify({
"standing": "uploaded",
"message": "Photos uploaded efficiently."
})
@app.route('/final_result')
def final_result():
world uploaded_files
predictions = []
for file_path in uploaded_files:
information = preprocess_image(file_path)
prediction = mannequin.predict(information)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
uploaded_files = [] # Clear uploaded information for subsequent submission
return render_template('end result.html', predictions=predictions)
@app.route('/')
def house():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Step 10 : Develop index.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>Add Photos</title>
<model>
#imagePreview {
show: flex;
flex-wrap: wrap;
hole: 10px;
}.preview-image {
width: 100px;
peak: 100px;
object-fit: cowl;
}
</model>
<script>
let selectedFiles = [];
perform handleFileSelect(occasion) {
const information = Array.from(occasion.goal.information);
if (selectedFiles.size + information.size > 5) {
alert("You'll be able to add a most of 5 photos");
return;
}
information.forEach((file) => {
selectedFiles.push(file);
});
updateImagePreview();
uploadFiles(information);
}
perform updateImagePreview() {
const imagePreview = doc.getElementById("imagePreview");
imagePreview.innerHTML = "";
selectedFiles.forEach((file) => {
const reader = new FileReader();
reader.onload = perform (e) {
const img = doc.createElement("img");
img.src = e.goal.end result;
img.classList.add("preview-image");
imagePreview.appendChild(img);
};
reader.readAsDataURL(file);
});
}
perform uploadFiles(information) {
const formData = new FormData();
information.forEach((file) => {
formData.append("information[]", file);
});
fetch("/predict", {
technique: "POST",
physique: formData,
})
.then((response) => response.json())
.then((information) => {
console.log(information);
if (information.standing === "uploaded") {
alert("Photos uploaded efficiently");
}
})
.catch((error) => console.error("Error importing information:", error));
}
</script>
<hyperlink
href="https://cdn.jsdelivr.web/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="nameless"
/>
</head>
<physique>
<div class="container-fluid" model="margin-left: 170px">
<br />
<h3>Add Photos</h3>
<br />
<type id="uploadForm" enctype="multipart/form-data">
<enter
sort="file"
identify="information[]"
a number of
settle for="picture/*"
onchange="handleFileSelect(occasion)"
/>
<div id="imagePreview"></div>
</type>
<br />
<type motion="/final_result" technique="get">
<button
sort="submit"
class="btn btn-info"
model="border-radius: 0; width: 300px"
>
Get Consequence
</button>
</type>
</div>
</physique>
</html>
Step 11 : Develop end result.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta identify="viewport" content material="width=device-width, initial-scale=1.0">
<title>Prediction Outcomes</title>
</script>
<hyperlink href="https://cdn.jsdelivr.web/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="nameless"></head>
<physique>
<div class="container">
<h3 class="mt-4">Prediction Outcomes</h3><br/>
<div class="form-group">
<textarea id="predictions" class="form-control" readonly model="width: 500px;">{% for prediction in predictions %}{{ prediction }} {% endfor %}</textarea><br/>
</div>
<a href="/" > <button sort="submit" class="btn btn-info" model="border-radius: 0; width: 200px;">Again</button> </a>
</div>
</physique>
</html>
Step 12 : Create labels.txt file
0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
8 I
9 J
10 Ok
11 L
12 M
13 N
14 O
15 P
16 Q
17 R
18 S
19 T
20 U
21 V
22 W
23 X
24 Y
25 Z
26 area
27 nothing
28 del
Step 13 : Create requirment.txt file
flask
tensorflow
keras
pillow
numpy
Step 14 : Run most important.py
python most important.py