File size: 1,980 Bytes
05ec9f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
from flask import Flask, request, render_template
import os
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import numpy as np

app = Flask(__name__)

# đường dẫn ảnh
UPLOAD_FOLDER = 'static/uploads/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# load model
model = load_model('cnn_cats_dogs.h5')

# xử lý ảnh và dự đoán
def detect_img(image_path):
    img = load_img(image_path, target_size=(150, 150))
    img_array = img_to_array(img)
    # thêm chiều batch
    img_array = np.expand_dims(img_array, axis=0)
    img_array = img_array / 255.0
    
    
    #dự đoán
    prediction = model.predict(img_array)
    if prediction[0][0] > 0.5:
        res = np.round(prediction[0][0] * 100, 2)
        return f"Chó {res}%"
    else:
        res = np.round(100 - prediction[0][0] * 100, 2)
        return f"Mèo {res}%"

# trang chủ
@app.route('/', methods=['GET', 'POST'])
def index():
    result = None
    image_path = None
    
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'Không có file nào được tải lên'
        file = request.files['file']
        if file.name == '':
            return 'Chưa chọn file!'
        
        # lưu ảnh vào thư mục static/uploads
        if file:
            filename = 'upload_image.jpg'
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)
            
            #dự đoán
            result = detect_img(file_path)
            image_path = f'uploads/{filename}'
            
    return render_template('index.html', result=result, image_path=image_path)

if __name__ == '__main__':
    #tạo thư mục uploads nếu chưa có
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(debug=True, host='0.0.0.0', port=5000)