File size: 5,718 Bytes
b584001 |
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
from flask import Flask, render_template, request, jsonify
from PIL import Image
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.layers import (
Input,
Conv2D,
MaxPooling2D,
Flatten,
Dense,
BatchNormalization,
Activation,
Add,
Concatenate,
)
from tensorflow.keras.optimizers import Adam
from vit_keras import vit
app = Flask(__name__)
# Define the upload directory
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Define transitional block function
def transitional_block(x, filters):
x = Conv2D(filters, kernel_size=(3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)
return x
# Define pointwise convolution block function
def pointwise_conv_block(x, filters):
x = Conv2D(filters, kernel_size=(1, 1), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
return x
# Define the ViT model
input_shape = (224, 224, 3) # Example input shape
num_classes = 4 # Example number of classes
vit_model = vit.vit_b32(
image_size=input_shape[:2],
include_top=False,
pretrained=True,
pretrained_top=False,
classes=num_classes,
weights="imagenet21k",
)
# Freeze the layers of the ViT model
for layer in vit_model.layers:
layer.trainable = False
# Define the modified VGG19 model
def modified_vgg19(input_tensor):
# Block 1
x = Conv2D(64, kernel_size=(3, 3), strides=(1, 1), padding='same')(input_tensor)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = transitional_block(x, 64)
# Block 2
x = transitional_block(x, 128)
x = pointwise_conv_block(x, 128)
# Block 3
x = transitional_block(x, 256)
x = pointwise_conv_block(x, 256)
x = pointwise_conv_block(x, 256)
x = pointwise_conv_block(x, 256)
# Block 4
x = transitional_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
# Block 5
x = transitional_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
x = pointwise_conv_block(x, 512)
x = transitional_block(x, 1024)
x = pointwise_conv_block(x, 1024)
x = pointwise_conv_block(x, 1024)
x = pointwise_conv_block(x, 1024)
x = pointwise_conv_block(x, 1024)
x = Flatten()(x)
x = Dense(256, activation='relu')(x)
x = Dense(256, activation='relu')(x)
output_layer = Dense(4, activation='softmax')(x)
return output_layer
# Your modified VGG19 architecture here
# Register custom layers used in modified_vgg19
tf.keras.utils.get_custom_objects()['transitional_block'] = transitional_block
tf.keras.utils.get_custom_objects()['pointwise_conv_block'] = pointwise_conv_block
# Load the pre-trained model
path = "C:\\Users\\HI BUDDY\\Desktop\\PoultryApp\\strawberryy.h5"
loaded_model = load_model(path, custom_objects={
'transitional_block': transitional_block,
'pointwise_conv_block': pointwise_conv_block,
})
# Function to preprocess the image
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)
img_array = img_array / 255.0
return img_array
# Function to check if the file has an allowed extension
def allowed_file(filename):
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
# Check if the 'file' key is in the request
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
# Check if file is empty
if file.filename == '':
return jsonify({'error': 'No selected file'})
# Check if file is allowed
if file and allowed_file(file.filename):
# Create the upload directory if it doesn't exist
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
img_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(img_path)
# Preprocess the image
img_array = preprocess_image(img_path)
#labels
class_labels = ['klebsila', 'healthy', 'ecoli' , 'pseudomonas', 'staphylococcus', 'streptococcus']
# Make predictions
predictions = loaded_model.predict(img_array)
# Set confidence threshold
confidence_threshold = 0.50 # Adjust as needed #.55 for normal #.85 for microscope
# Get the predicted class label and confidence
max_confidence = np.max(predictions)
if max_confidence >= confidence_threshold:
predicted_class_index = np.argmax(predictions)
predicted_class_label = class_labels[predicted_class_index]
return jsonify({'prediction': predicted_class_label})
else:
return jsonify({'prediction': "This format is not supported"})
return jsonify({'error': 'Invalid file format'})
if __name__ == '__main__':
app.run(debug=True)
|