| from flask import Flask, request, jsonify |
| from tensorflow.keras.models import load_model |
| from tensorflow.keras.preprocessing import image |
| import numpy as np |
| import os |
|
|
| |
| app = Flask(__name__) |
|
|
| |
| model = load_model('./butterfly_classifier.h5') |
|
|
| |
| def preprocess_image(image_path): |
| img = image.load_img(image_path, target_size=(224, 224)) |
| img_array = image.img_to_array(img) |
| img_array = np.expand_dims(img_array, axis=0) |
| return img_array |
|
|
| |
| @app.route('/predict', methods=['POST']) |
| def predict(): |
| if 'file' not in request.files: |
| return jsonify({'error': 'No file part'}) |
| |
| file = request.files['file'] |
| |
| |
| file_path = 'temp.jpg' |
| file.save(file_path) |
| |
| |
| processed_image = preprocess_image(file_path) |
| |
| |
| prediction = model.predict(processed_image) |
| |
| |
| predicted_class = np.argmax(prediction, axis=1) |
| |
| |
| os.remove(file_path) |
| |
| |
| return jsonify({'predicted_class': predicted_class.item()}) |
|
|
| |
| @app.route('/') |
| def welcome(): |
| return 'Welcome to Butterfly Classification API' |
|
|
| |
| if __name__ == '__main__': |
| app.run(debug=True) |
|
|
|
|