Books Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
Latest:- Important tips to get an Off Campus Placements
0 like 0 dislike
10.7k views
in AI-ML-Data Science Projects by (471 points)
edited by

This project is based on the detection of leaf disease.With the help of this we can easily detect the disease. We can implement this model with the help of CNN.

Scientists have found that on a global scale plant disease are reducing crop yields for crops by 10 percent to 40 percent ,according to a report by UC Agriculture and Natural Resource Scientist.



GOEDUHUB's Online Courses @ Udemy



2 Answers

0 like 0 dislike
by (471 points)
selected by
 
Best answer

PROJECT - LEAF DISEASE DETECTION AND RECOGNITION

Problem 

In Agriculture field all farmers facing the problem of plant disease.in olden days their are various way to destroy these disease but in technological time through detection we can easily detect which type of disease are available in particular plant.  

Basically we will first train our CNN models with a lot of  images of potato,pepper and tomato.

Why CNN:  As we have seen in CNN Tutorial,CNN reads a very large image in a simple manner. CNN most commonly used to analyze visual imagery and are frequently working behind the scenes in image classification.

Data Set

Various datasets are available on internet to detect your plant disease and train your model with these datasets. We can also create our own data set and train our model. we can download data set from kaggle. To download data set Click here

Implementation

#Intialization of Program. by Importing various LIbraries
import numpy as np
import matplotlib.pyplot as plt

# here we are working on Tensorflow version 2.1.0 so we need to write tensorflow.keras.
#keras is in built function in Tensorflow.

import os
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Input, Dropout,Flatten, Conv2D
from tensorflow.keras.layers import BatchNormalization, Activation, MaxPooling2D
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.utils import plot_model
from IPython.display import SVG, Image

Note

Here we import various libraries like numpy,matplotlib,os,tensorflow etc. we use here  tensorflow version 2.1.0 and keras is also available inside this tensorflow version. we use various layers and model,optimizer for train our model.

# For checking out that how many images are available in the train set we can use import OS
for types in os.listdir("F:/JetBrains/goeduhub training/PROJECTDATA 1/train_set/"):
    print(str(len(os.listdir(
"F:/JetBrains/goeduhub training/PROJECTDATA 1/train_set/"+ types)))+" "+ types+' images')

Output

image

Note

we use os.listdir for fatching list of all the images in the folder.inside this we give the path ("highlight")where images are store.here we take only train dataset images from our plant disease dataset.  

# Complete Dataset images can be loaded using ImageDataGenerator function
img_size=48
batch_size=64
datagen_train=ImageDataGenerator(horizontal_flip=True)
train_generator=datagen_train.flow_from_directory(
"F:/JetBrains/goeduhub training/PROJECTDATA 1/train_set",
target_size=(img_size,img_size),
batch_size=batch_size,
class_mode='categorical',
shuffle=True)

datagen_test=ImageDataGenerator(horizontal_flip=True)
validation_generator=datagen_test.flow_from_directory(
"F:/JetBrains/goeduhub training/PROJECTDATA 1/test_data",
target_size=(img_size,img_size),
batch_size=batch_size,
class_mode='categorical',
shuffle=True)

Output

total no. of images belonging 15 class

Note

This part of code is used to define train and test data into the model. The train dataset has 16222 images belonging to 15 classes and the test dataset has 1254 images belonging to 15 classes. here we use class mode 'categorical' because more then 2 classes are available here.

detection=Sequential()

Note

Now we use sequential model.The Sequential model API is a way of creating deep learning models where a sequential class is created and model layers are created and added to it

#convolutional layer-1
detection.add(Conv2D(64,(3,3),padding='same',input_shape=(48,48,3)))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(MaxPooling2D(pool_size=(2,2)))
detection.add(Dropout(0.25))


#2 -convolutional layer-2
detection.add(Conv2D(128,(5,5),padding='same'))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(MaxPooling2D(pool_size=(2,2)))
detection.add(Dropout(0.25))


#3 -convolutional layer-3
detection.add(Conv2D(256,(3,3),padding='same'))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(MaxPooling2D(pool_size=(2,2)))
detection.add(Dropout(0.25))


#4 -convolutional layer-4
detection.add(Conv2D(512,(3,3),padding='same'))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(MaxPooling2D(pool_size=(2,2)))
detection.add(Dropout(0.25))


#5 -convolutional layer-5
detection.add(Conv2D(512,(3,3),padding='same'))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(MaxPooling2D(pool_size=(2,2)))
detection.add(Dropout(0.25))

detection.add(Flatten())
detection.add(Dense(256))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(Dropout(0.25))

detection.add(Dense(512))
detection.add(BatchNormalization())
detection.add(Activation('relu'))
detection.add(Dropout(0.25)

detection.add(Dense(15,activation='softmax'))
optimum=Adam(lr=0.005)
#lr-learning rate
detection.compile(optimizer=optimum,loss='categorical_crossentropy',metrics=['accuracy'])

Note

Here we add various convolutional layers with the Relu activation function (Rectified Linear Unit).We pass the images through the layers more than once for better feature extraction.

Inside the conv2D first parameter show the number of filters,second show the size of filter/kernal,Input_shape represent here the RGB format of  images.The convolutional layer is then pass to MaxPooling layer,pooliing size is the window size. 

Flatten is used for convert data into 1D form. Dense layer is used for all neurons to the previous layer neurons so it is fully connected layer. Droupout function is use for not taking all the units in the neural network.optimize Adam is used for optimize our data with learning rate.

A metric is a function that is used to judge the performance of your model.  The optimizers are used for improving speed and performance for training a specific model.

detection.summary()

Output

Note

Now we print all the convolutional layer and their neurons in short we print all detail of  all layers.

ephocs=10
steps_per_epoch=train_generator.n//train_generator.batch_size
steps_per_epoch
validation_steps=validation_generator.n//validation_generator.batch_size
validation_steps
detection.fit(x=train_generator,
                    steps_per_epoch=steps_per_epoch,
                    epochs=ephocs,
                    validation_data=validation_generator,
                    validation_steps=validation_steps)
detection.save('Plant_Disease_Detection.h5')

Output

Note

This is most important part of our project.here we take 10 epochs for train our model. More epochs increase the accuracy and decrease the loss.

we can see here that accuracy in each step increase.we train our model 10 times.when test images train with lots of train images then accuracy will increase and our model predict more accuracy. more accuracy mean our model work properly and give desire output.  

The most important thing about this,it run only one time not run this step again and again  because epochs takes time once you run this step do not repeat it again. 

Here we save this model and if we want to use it in future then load this model.

from tensorflow.keras.models import load_model
Detection=load_model('Plant_Disease_Detection.h5')
from tensorflow.keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
import cv2
test_img=image.load_img(
"F:/JetBrains/goeduhub training/PROJECTDATA 1/test_data/Tomato_healthy/0d515778-61ef-4f0b-ab54-75607c80220f___RS_HL 9745.jpg",target_size=(48,48))
plt.imshow(test_img)
test_img=image.img_to_array(test_img)
test_img=np.expand_dims(test_img,axis=0)
result=Detection.predict(test_img)
a=result.argmax()
# print('a:',a)
classes=train_generator.class_indices
# print(classes)
# print(len(classes))
category=[]
for i in classes:
          category.append(i)
for i in range(len(classes)):
          if(i==a):
              output=category[i]
output 

Output

Tomato_healthy

from tensorflow.keras.models import load_model
Detection=load_model('Plant_Disease_Detection.h5')
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import cv2
test_img=image.load_img(
"F:/JetBrains/goeduhub training/PROJECTDATA 1/test_data/Pepper__bell___healthy/1dd1b153-8ded-439f-8c9e-c9970c67e642___JR_HL 8163.jpg",target_size=(48,48))
plt.imshow(test_img)
test_img=image.img_to_array(test_img)
test_img=np.expand_dims(test_img,axis=0)
result=Detection.predict(test_img)
a=result.argmax()
# print('a',a)
classes=train_generator.class_indices
category=[]
for i in classes:
          category.append(i)
for i in range(len(classes)):
           if(i==a):
                output=category[i]
output  

 

Output

Pepper__bell___healthy

pepper image

Introduction about project developer

The Leaf Disease Detection project is develop by Mohit Bansal from Global Institute of technology,jaipur. This project is developed during Goeduhub Online Summer training in Artificial Intelligence,Machine Learning and Deep Learning.

Greate Experience with this institute during this training.

Thank you smiley 

0 like 0 dislike
by (471 points)

OUTPUT ON WINDOW USING GUI METHOD

from  tkinter import * 
from tkinter import filedialog
from PIL import ImageTk,Image
window=Tk()
window.geometry("746x500")
label1=Label(window,text="                                                      ").grid(row=0,column=0)
label2=Label(window,text="welcome to your solution world ",font=('italic',30,'bold'),bg="cyan",padx=70,pady=20).grid(row=1,column=0)
label3=Label(window,text="                                                       ").grid(row=2,column=0)
def open_file():
      top=Toplevel()
      top.title("image  window")
      top.geometry("746x500")
      global my_image
      global file_open
      file_open =filedialog.askopenfilename(initialdir="
F:\JetBrains\goeduhub training\PROJECTDATA 1",title="select a file")
     my_label=Label(top,text=file_open).grid(row=0,column=0)
     my_image=ImageTk.PhotoImage(Image.open(file_open))
     my_image_label=Label(top,image=my_image).grid(row=1,column=0)
     
# button inside the second window
     button_exit=Button(top,text="Exit",padx=45,pady=20,command=top.destroy,font=('italic',20,'bold')).grid(row=3,column=0)
     
      button_prediction=Button(top,text="predict",padx=45,pady=20,font=('italic',20,'bold'),command=predict_img).grid(row=2,column=0)


# button inside the first window
button1=Button(window,text="click me",padx=30,pady=20,font=('italic',20,'bold'),command=open_file).grid(row=3,column=0)

label5=Label(window,text="                                                      ").grid(row=4,column=0)
button_quit=Button(text="Exit",padx=45,pady=20,command=window.destroy,font=('italic',20,'bold')).grid(row=5,column=0)


#predict output function
def predict_img():
      top1=Toplevel()
      top1.title("prediction window")
      top1.geometry("746x500")
      global test_img
      my_image_label=Label(top1,image=my_image).grid(row=0,column=0)
      from tensorflow.keras.models import load_model
      Detection=load_model('Plant_Disease_Detection.h5')
      from tensorflow.keras.preprocessing import image
      import matplotlib.pyplot as plt
      import numpy as np
      import cv2
      test_img=image.load_img(file_open,target_size=(48,48))
      test_img=image.img_to_array(test_img)
      test_img=np.expand_dims(test_img,axis=0)
      result=Detection.predict(test_img)
      a=result.argmax()
      classes=train_generator.class_indices
      category=[]
      for i in classes:
           category.append(i)
      for i in range(len(classes)):
            if(i==a):
                 output=category[i]
      output=Label(top1,text=output).grid(row=1,column=0)

window.mainloop()

Output

window1inside datawindow2window3

Screenshots

First screenshot show first window,second show data folder inside the specified path,third screenshot show second window and fourth screenshot show the third window. 

Note

As we know we already get their output but to make our project more attractive we use Graphical User Interface(gui). Firstly we install pillow library for opening, manipulating and saving many different images file format.

command

#pip install pillow or

#conda install pillow

Note

Now we importing library tkinter,filedialog,ImageTk,Image.After importing library we create window and give the size of the window.Now we give 3 label (label1,label2,label3).inside label1 we give window name,text and use grid function for showing the label1 result on window. Same apporach use in label2 and label3.

we create button on window (button1,button_quit),and label5 use space between two button. Inside button1 we give parameter like window name, text ,size(padx,pady),font ,and command.command is use because when we click on button it perform related action.

After click on button it perform action so we define function which name should be same as command name we use inside Button parameter.

we define second window inside open_file() function.we give title,window size.Now we use askopenfilename method which exist inside filedialog. we give parameter like initialdir(path where your data store) and title and if you want specific filetypes then we also give this parameter(filetypes = (("all files"," *.* "),("mp4 files","*.mp4"))). Then we use label so that selected file are exist and visible on window. now we select image from given path using ImageTk.PhotoImage function() and after that we use label as we earlier use. inside second window we make two button (exit and predict). inside button_predict we give parameter and command for perform action. inside open_file function we declare global my_image,and global file_open so that we can use it anywhere in the code.

Now we predict second function predict_image().inside this function we define third window,their size,title.then we load train model so that our project predict right output. after this process we use these simple library matplotlib,cv2,numpy. now we load image in test_img variable from file_open and should give size of image same as we earlier give.we convert this image into array format so that electronic device can understand easily. after this we use argmax function() on result. after this process we divide data into specific classes and use loop for target output. for print this output we use label  and at last we window.mainloop() so that our all windows can visible otherwise window will be created but not visible.

3.3k questions

7.1k answers

395 comments

4.6k users

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...