| 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__)
|
|
|
|
|
| UPLOAD_FOLDER = 'static/uploads/'
|
| app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
|
|
|
|
| model = load_model('cnn_cats_dogs.h5')
|
|
|
|
|
| def detect_img(image_path):
|
| img = load_img(image_path, target_size=(150, 150))
|
| img_array = img_to_array(img)
|
|
|
| img_array = np.expand_dims(img_array, axis=0)
|
| img_array = img_array / 255.0
|
|
|
|
|
|
|
| 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}%"
|
|
|
|
|
| @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!'
|
|
|
|
|
| if file:
|
| filename = 'upload_image.jpg'
|
| file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| file.save(file_path)
|
|
|
|
|
| result = detect_img(file_path)
|
| image_path = f'uploads/{filename}'
|
|
|
| return render_template('index.html', result=result, image_path=image_path)
|
|
|
| if __name__ == '__main__':
|
|
|
| if not os.path.exists(UPLOAD_FOLDER):
|
| os.makedirs(UPLOAD_FOLDER)
|
| app.run(debug=True, host='0.0.0.0', port=5000) |