-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
61 lines (47 loc) · 2.24 KB
/
app.py
File metadata and controls
61 lines (47 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import numpy as np
import tensorflow as tf
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
app = Flask(__name__)
# Load mô hình đã huấn luyện
model = load_model('ml/best_model.keras')
class_names = ['butterfly', 'cat', 'chicken', 'cow', 'dog', 'elephant', 'hourse', 'sheep', 'spider', 'squirrel']
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def preprocess_image(img_path):
"""Tiền xử lý ảnh."""
img = image.load_img(img_path, target_size=(224, 224))
img_array = image.img_to_array(img) / 255.0 # Chuẩn hóa
img_array = np.expand_dims(img_array, axis=0)
return img_array
@app.route("/", methods=["GET", "POST"])
def upload_folder():
if request.method == "POST":
if "file" not in request.files:
return render_template("index.html", error="No files uploaded")
files = request.files.getlist("file") # Nhận danh sách ảnh tải lên
if not files or files[0].filename == "":
return render_template("index.html", error="No valid images selected")
# Tạo thư mục nếu chưa tồn tại
extract_folder = os.path.join(app.config["UPLOAD_FOLDER"], "extracted")
os.makedirs(extract_folder, exist_ok=True)
uploaded_images = []
predictions = []
for file in files:
if file.filename.lower().endswith((".png", ".jpg", ".jpeg")):
img_path = os.path.join(extract_folder, secure_filename(file.filename))
file.save(img_path)
# Dự đoán ảnh
img_array = preprocess_image(img_path)
prediction = model.predict(img_array)[0]
predicted_class = class_names[np.argmax(prediction)]
confidence = np.max(prediction) * 100
uploaded_images.append(img_path)
predictions.append({"class": predicted_class, "confidence": confidence})
return render_template("result.html", images=uploaded_images, predictions=predictions)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)