CROP DISEASE IDENTIFICATION
ALGORITHM AND CODE
OF MAJOR PROJECT
BACHELOR OF
COMPUTER SCIENCE AND ENGINEERING
AND
DATASCIENCE AND ARTIFICIAL INTELLENGENCE
SUBMITTED BY:
AJITH S
DARSHAN L
SAKSHI R
SATHWIK C S
September 2023
IMPORTANT DIAGRAMS
USE CASE DIAGRAM:
In the Unified Modelling Language (UML), a use case diagram can summarize the
details of your system's users (also known as actors) and their interactions with the system. To
build one, you'll use a set of specialized symbols and connectors. An effective use case diagram
can help your team discuss and represent:
• Scenarios in which your system or application interacts with people, organizations,
or external system
• Goals that your system or application helps those entities (known as actors) achieve.
• The scope of your system.
Fig. 1: Use Case Diagram
FLOW DIAGRAM:
A flowchart is a type of diagram that represents a workflow or process. A flowchart
canalso be defined as a diagrammatic representation of an algorithm, a step-by-step approach
to solving a task. The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows.
Fig. 2: Flow Chart
IMPLIMENTATION OF CODE
Using CNN model for detecting the emotion of the user:
### Importing necessary libraries
import NumPy as np
import pandas as pd
import [Link] as plt
from [Link] import imread
import cv2
import random
import os
from os import listdir
from PIL import Image
import tensorflow as tf
from [Link] import image
from tensorflow. [Link] import img_to_array, array_to_img
from [Link] import Adam
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D
from [Link] import Activation, Flatten, Dropout, Dense
from sklearn. model_selection import train_test_split
from [Link] import model_from_json
from [Link] import to_categorical
print(tf. __version__)
### Defining the path of dataset directory
dataset_path = "C:\Plant-Disease-Detection\Dataset"
### Visualizing the images and Resize images
# Plotting 12 images to check dataset
[Link](figsize = (12, 12))
dataset_path = "C:\Plant-Disease-Detection\Dataset\Potato___Early_blight"
for i in range(1, 17):
[Link](4, 4, i)
plt.tight_layout()
rand_img = imread(dataset_path +'/'+ [Link](sorted([Link](dataset_path))))
[Link](rand_img)
[Link](rand_img.shape[1], fontsize = 10) # width of image
[Link](rand_img.shape[0], fontsize = 10) # height of image
### Convert the images into a Numpy array and normalize them
# Converting Images to array
def convert_image_to_array(image_dir):
try:
image = [Link](image_dir)
if image is not None :
image = [Link](image, (256, 256))
return img_to_array(image)
else :
return [Link]([])
except Exception as e:
print (f"Error: {e}")
return None
dataset_path = "C:\Plant-Disease-Detection\Dataset"
labels = [Link](dataset_path)
print(labels)
dataset_path = "C:\Plant-Disease-Detection\Dataset"
root_dir = listdir(dataset_path)
image_list, label_list = [], []
all_labels = ['Corn-Common_rust', 'Potato-Early_blight', 'Tomato-Bacterial_spot']
binary_labels = [0, 1, 2]
temp = -1
# Reading and converting image to numpy array
for directory in root_dir:
plant_image_list = listdir(f"{dataset_path}/{directory}")
temp += 1
for files in plant_image_list:
image_path = f"{dataset_path}/{directory}/{files}"
image_list.append(convert_image_to_array(image_path))
label_list.append(binary_labels[temp])
### Visualize the class count and Check for class imbalance
label_counts = pd. DataFrame(label_list).value_counts ()
label_counts.head()
image_list [0]. Shape
label_list = [Link](label_list)
label_list. Shape
### Splitting the dataset into train, validate and test sets
x_train, x_test, y_train, y_test = train_test_split (image_list, label_list, test_size=0.2, random_state =
10)
# Now we will normalize the dataset of our images. As pixel values ranges from 0 to 255 so we will
divide each image pixel with 255 to normalize the dataset.
x_train = [Link](x_train, dtype=np.float16) / 225.0
x_test = [Link](x_test, dtype=np.float16) / 225.0
x_train = x_train.reshape(-1, 256, 256, 3)
x_test = x_test.reshape(-1, 256, 256, 3)
### Performing one-hot encoding on target variable
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
### Creating the model architecture, compile the model and then fit it using the
training data
model = Sequential()
[Link] (Conv2D (32, (3, 3), padding = "same”, input_shape = (256, 256, 3), activation = "relu"))
[Link](MaxPooling2D (pool_size = (3, 3)))
[Link](Conv2D(16, (3, 3), padding = "same", activation = "relu"))
[Link](MaxPooling2D(pool_size = (2, 2)))
[Link](Flatten())
[Link](Dense(8, activation = "relu"))
[Link](Dense(3, activation = "softmax"))
model. summary ()
model. compile (loss = 'categorical_crossentropy', optimizer = Adam (0.0001), metrics = ['accuracy'])
# Splitting the training data set into training and validation data sets
x_train, x_val, y_train, y_val = train_test_split (x_train, y_train, test_size = 0.2, random_state = 10)
# Training the model
epochs = 50
batch_size = 128
history = [Link] (x_train, y_train, batch_size = batch_size, epochs = epochs, validation_data =
(x_val, y_val))
model. save("C:\Plant-Disease-Detection\Model\plant_disease_model.h5")
### Plot the accuracy and loss against each epoch
# Plot the training history
[Link](figsize = (12, 5))
[Link]([Link]['accuracy'], color = 'r')
[Link]([Link]['val_accuracy'], color = 'b')
[Link]('Model Accuracy')
[Link]('Accuracy')
[Link]('Epochs')
[Link](['train', 'val'])
plot. show ()
print ("Calculating model accuracy")
scores = model. Evaluate (x_test, y_test)
print (f"Test Accuracy: {scores [1] * 100}")
### Make predictions on testing data
y_pred = [Link](x_test)
### Visualizing the original and predicted labels for the test images
# Plotting image to compare
img = array_to_img (x_test [11])
img
# Finding max value from perdition list and comparing original value vs predicted
print ("Originally: ", all_labels [np. argmax (y_test [11])])
print ("Predicted : ", all_labels[[Link](y_pred[4])])
print (y_pred [2])