Perquisites
- Want machine studying mannequin(with .h5 extension).By this clarification I used sing language detection mannequin.
- Establish the labels that are used for coaching the mannequin. For an instance when you prepare mannequin for determine canines and cats then classification labels have to be “canine and cat”.
- Set up python model 3.8.0 when you’re not set up already and set path accurately.
- Set up vs code when you’re not set up already.
- Make listing any location no matter you need and open it utilizing vs code.
- Open terminal and run beneath 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 recordsdata comparable to index.html and consequence.html
Then navigate once more into root director and create remainder of the recordsdata app.py ,model_name.h5 ,labels.txt and requirments.txt recordsdata.
index.html file makes use of for present the house web page and thru web page consumer in a position to add pictures.
consequence.html file makes use of for exhibiting consequence which is returning by mannequin.
app.py is the center of the code. all of the implementation components 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 technique in one other computer.
Step 2 : Import related libraries.
Beneath recordsdata perhaps fluctuate and a few fashions want extra libraries. Generally beneath recordsdata 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 recordsdata.
uploaded_files = []
Step 5 : Initialize preprocessing half.
def preprocess_image(image_path):
picture = Picture.open(image_path).convert("RGB")
dimension = (224, 224)
picture = ImageOps.match(picture, dimension, 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 dwelling():
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':
recordsdata = request.recordsdata.getlist('recordsdata[]')
predictions = []
for file in recordsdata:
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": "Photographs uploaded efficiently."
})
Step 8 : Outline route and relent code for the airing consequence.
@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 recordsdata for subsequent submission
return render_template('consequence.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")
dimension = (224, 224)
picture = ImageOps.match(picture, dimension, 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':
recordsdata = request.recordsdata.getlist('recordsdata[]')
predictions = []
for file in recordsdata:
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": "Photographs 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 recordsdata for subsequent submission
return render_template('consequence.html', predictions=predictions)
@app.route('/')
def dwelling():
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 title="viewport" content material="width=device-width, initial-scale=1.0" />
<title>Add Photographs</title>
<type>
#imagePreview {
show: flex;
flex-wrap: wrap;
hole: 10px;
}.preview-image {
width: 100px;
top: 100px;
object-fit: cowl;
}
</type>
<script>
let selectedFiles = [];
perform handleFileSelect(occasion) {
const recordsdata = Array.from(occasion.goal.recordsdata);
if (selectedFiles.size + recordsdata.size > 5) {
alert("You'll be able to add a most of 5 pictures");
return;
}
recordsdata.forEach((file) => {
selectedFiles.push(file);
});
updateImagePreview();
uploadFiles(recordsdata);
}
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.consequence;
img.classList.add("preview-image");
imagePreview.appendChild(img);
};
reader.readAsDataURL(file);
});
}
perform uploadFiles(recordsdata) {
const formData = new FormData();
recordsdata.forEach((file) => {
formData.append("recordsdata[]", file);
});
fetch("/predict", {
technique: "POST",
physique: formData,
})
.then((response) => response.json())
.then((information) => {
console.log(information);
if (information.standing === "uploaded") {
alert("Photographs uploaded efficiently");
}
})
.catch((error) => console.error("Error importing recordsdata:", error));
}
</script>
<hyperlink
href="https://cdn.jsdelivr.internet/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="nameless"
/>
</head>
<physique>
<div class="container-fluid" type="margin-left: 170px">
<br />
<h3>Add Photographs</h3>
<br />
<kind id="uploadForm" enctype="multipart/form-data">
<enter
kind="file"
title="recordsdata[]"
a number of
settle for="picture/*"
onchange="handleFileSelect(occasion)"
/>
<div id="imagePreview"></div>
</kind>
<br />
<kind motion="/final_result" technique="get">
<button
kind="submit"
class="btn btn-info"
type="border-radius: 0; width: 300px"
>
Get Consequence
</button>
</kind>
</div>
</physique>
</html>
Step 11 : Develop consequence.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta title="viewport" content material="width=device-width, initial-scale=1.0">
<title>Prediction Outcomes</title>
</script>
<hyperlink href="https://cdn.jsdelivr.internet/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 type="width: 500px;">{% for prediction in predictions %}{{ prediction }} {% endfor %}</textarea><br/>
</div>
<a href="/" > <button kind="submit" class="btn btn-info" type="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 Okay
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 house
27 nothing
28 del
Step 13 : Create requirment.txt file
flask
tensorflow
keras
pillow
numpy
Step 14 : Run predominant.py
python predominant.py