import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from tensorflow.keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt # Paths train_dir = 'Tomato_Plant_Disease' # Image Data Generator with Augmentation for training datagen = ImageDataGenerator( rescale=1./255, # Normalize pixel values rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, validation_split=0.2 # Use 20% for validation ) # Training and Validation Data train_generator = datagen.flow_from_directory( train_dir, target_size=(128, 128), batch_size=32, class_mode='binary', # 'binary' since it's a binary classification subset='training' ) validation_generator = datagen.flow_from_directory( train_dir, target_size=(128, 128), batch_size=32, class_mode='binary', subset='validation' ) # Define the CNN model model = Sequential() # 1st Convolution Layer model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3))) model.add(MaxPooling2D(pool_size=(2, 2))) # 2nd Convolution Layer model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) # 3rd Convolution Layer model.add(Conv2D(128, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) # Flatten the output model.add(Flatten()) # Fully connected layer model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) # Dropout to prevent overfitting # Output layer model.add(Dense(1, activation='sigmoid')) # Binary classification, hence 'sigmoid' # Compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Summary model.summary() history = model.fit( train_generator, steps_per_epoch=train_generator.samples // 32, validation_data=validation_generator, validation_steps=validation_generator.samples // 32, epochs=20 # You can adjust based on performance ) # Plot training & validation accuracy values plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Validation'], loc='upper left') plt.show() # Plot training & validation loss values plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Validation'], loc='upper left') plt.show() # Assuming you have a test directory test_dir = 'Tomato_Plant_Disease' # Path to your test dataset # Create a test data generator (without augmentation) test_datagen = ImageDataGenerator(rescale=1./255) # Load test data test_generator = test_datagen.flow_from_directory( test_dir, target_size=(128, 128), batch_size=32, class_mode='binary' ) test_loss, test_acc = model.evaluate(test_generator, steps=test_generator.samples // 32) print(f"Test Accuracy: {test_acc}") model.save('tomato_disease_detection_model.h5') from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image import numpy as np from PIL import Image # Load the model model = load_model('tomato_disease_detection_model.h5') def predict_disease(img_path): # Load and preprocess the image img = Image.open(img_path) img = img.resize((128, 128)) # Resize image to match model input size img = np.array(img) # Convert to array img = img / 255.0 # Normalize pixel values img = np.expand_dims(img, axis=0) # Add batch dimension # Make prediction prediction = model.predict(img) # Determine if infected or healthy if prediction[0][0] > 0.5: print("The plant is healthy.") else: print("The plant is infected.") # Example usage: img_path = 'Tomato_Plant_Disease/0/0045ba29-ed1b-43b4-afde-719cc7adefdb___GCREC_Bact.Sp 6254.JPG' predict_disease(img_path) import gradio as gr from tensorflow.keras.models import load_model from PIL import Image import numpy as np # Load the pre-trained model model = load_model('tomato_disease_detection_model.h5') # Prediction function to be used in Gradio def predict_disease(img): # Preprocess the image img = img.resize((128, 128)) # Resize to match model input size img = np.array(img) # Convert to array img = img / 255.0 # Normalize pixel values img = np.expand_dims(img, axis=0) # Add batch dimension # Make prediction prediction = model.predict(img) # Determine if infected or healthy if prediction[0][0] > 0.5: return "The plant is healthy." else: return "The plant is infected." # Gradio interface interface = gr.Interface( fn=predict_disease, inputs=gr.Image(type="pil"), # Corrected input without 'shape' argument outputs=gr.Textbox(), # Output component title="Tomato Plant Disease Detection", description="Upload an image of a tomato leaf to determine if it's infected or healthy." ) # Launch the Gradio interface interface.launch()