Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
341 views

Project Documentation

This document is a project report submitted by Yogeshwar Khandagre to the Department of Computer Applications at Hindustan Institute of Technology and Science for the degree of Master of Computer Applications. The project report describes the development of a cotton leaf recognition and disease prediction webapp that uses convolutional neural networks to identify diseases in cotton plant leaves from images. The system was able to accurately recognize cotton plant diseases from images with an accuracy of 98.89%.

Uploaded by

yog khandagre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
341 views

Project Documentation

This document is a project report submitted by Yogeshwar Khandagre to the Department of Computer Applications at Hindustan Institute of Technology and Science for the degree of Master of Computer Applications. The project report describes the development of a cotton leaf recognition and disease prediction webapp that uses convolutional neural networks to identify diseases in cotton plant leaves from images. The system was able to accurately recognize cotton plant diseases from images with an accuracy of 98.89%.

Uploaded by

yog khandagre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

COTTON LEAF RECOGNITION AND DISEASE

PREDICTION WEBAPP
A PROJECT REPORT-PHASE-II (CAA3786)

Submitted
by

Yogeshwar Khandagre
(18251026)

in partial fulfillment for the award of the degree


of

MASTER OF COMPUTER APPLICATIONS

DEPARTMENT OF COMPUTER APPLICATIONS


SCHOOL OF COMPUTING SCIENCES
HINDUSTAN INSTITUTE OF TECHNOLOGY AND SCIENCE
PADUR, CHENNAI - 603 103

APRIL 2021

i
HINDUSTAN INSTITUTE OF TECHNOLOGY AND
SCIENCE, PADUR, CHENNAI - 603 103

BONAFIDE CERTIFICATE

Certified that this project report titled “COTTON LEAF RECOGNITION AND

DISEASE PREDICTION WEBAPP” is the bonafide work of “YOGESHWAR

KHANDAGRE(18251026)” who carried out the project work under my

supervision. Certified further that to the best of my knowledge the work reported

here does not form part of any other project / research work on the basis of which a

degree or award was conferred on an earlier occasion on this or any other

candidate.

SIGNATURE SIGNATURE

HEAD OF THE DEPARTMENT SUPERVISOR


Dr. Angelina Geetha Mrs. Sherin Eliyas

Department of Computer Applications Designation


School of Computing Science Department of Computer Applications
Hindustan Institute of Technology and School of Computing Science
Science, Padur Hindustan Institute of Technology and
Science, Padur

INTERNAL EXAMINER EXTERNAL EXAMINER

Name: Name:

The Project Phase II Viva-Voce Examination is held on

ii
ACKNOWLEDGEMENT
First and foremost I would like to thank the Lord Almighty for His presence and immense

blessings throughout the project work.

It’s a matter of pride and privilege for me to express my deep gratitude to the management of

HITS for providing me the necessary facilities and support.

I am highly elated in expressing my sincere and abundant respect to the Vice Chancellor Dr. S.

N. Sridhara & Pro Vice Chancellor Dr. R. W. Alexander Jesudasan for giving me this

opportunity to bring out and implement my ideas in this project.

I wish to express my heartfelt gratitude to Dr. Angelina Geetha, Head of the Department of

Computer Applications for much of her valuable support encouragement in carrying out this

work.

I wish to sincere thanks to Mr. Sanju Rajan, Assistant Professor, Project Co-ordinator,

Department of Computer Applications for valuable guidance and continuous support to

successful completion of the Project work.

I would like to thank my internal guide NAME, for continually guiding and actively

participating in my project, giving valuable suggestions to complete the project work.

I would like to thank all the technical and teaching staff of the Computer Applications

Department, who extended directly or indirectly all support.

Last, but not the least, I am deeply indebted to my parents who have been the greatest support

while I worked day and night for the project to make it a success.

iii
ABSTRACT

Cotton plant is one of the cash crops in India. As most part of the Indian financial system is
dependent on agriculture production. Agriculture is one of the important professions in many
countries including India. For more profit its intense care is necessary. The taxonomy and
identification of crop infection got much importance in technical as well as economic in the
Agricultural Industry. While keeping track of diseases in plants with the help of specialists can be
very costly in agriculture region. There is a need for a system which can automatically detect the
diseases as it can bring revolution in monitoring large fields of crop and then plant leaves can be
taken cure as soon as possible after detection of disease. The aim of the proposed system is to
develop an application which recognizes cotton leaf diseases. Our Goal Is build a website where we
can upload an image of any cotton plant leaf and this website it will tell you information about which
decease it is on plant and how we can treat plant decease. Cotton farmer need to upload the image
and then with the help of image processing we can get a digitized color image of a diseased leaf and
then we can proceed with applying CNN to predict cotton leaf disease. Many researchers are using
machine learning for early detections of cotton plant disease. Convolution neural network (CNN) is
a deep feed forward artificial neural network. This algorithm is little faster as compared to other
classification algorithms. In this paper, CNN is used for classification of the diseased portion of
cotton plant images. Deep learning is the modern technique used for image processing. Particularly
Convolutional Neural Networks (CNNs), is used for automatic identification of cotton Plant disease.
Disease in cotton can interfere with the production of cotton and makes a distress to the country’s
economy. To manage the disease in cotton, an accurate diagnosis is essential. In this paper, to
diagnosis the disease in cotton a research was carried out to automatically identify the cotton plant
disease using Convolutional Neural Networks. Dataset with around 1100, images for three diseases
such as Bacterial Blight, Anthracnose, and Leafhopper are collected from cotton field. Convolutional
Neural Networks is used to for both recognition and classification of three cotton disease images
captured from farmer’s field. The experimental result showed affirmative output of approximately
98.89 % accuracy of recognition of cotton plant disease using python programming.

iv
TABLE OF CONTENT

CHAPTER TITLE PAGE


NO. NO.
ACKNOWLEDGEMENT III

ABSTRACT IV

LIST OF FIGURES VIII

LIST OF ABBREVIATIONS IX

1 INTRODUCTION 1
1.1 Introduction TO
6
1.2 Motivation for the work
1.3 Objective of the work
1.4 Project Scope & Limitations

1.5 Methodologies of Problem solving


2 LITERATURE SURVEY 6
2.1 Introduction TO
12

2.2 Literature Survey

v
3 SYSTEM ANALYSIS
13
3.1 Introduction
3.2 Existing system TO

3.2.1 Drawbacks 16
3.3PRESENT SCENARIO
3.4Proposed System
3.4.1 Advantages
3.5 System Architecture

4 SYSTEM DESIGN AND IMPLEMENTATION 16

4.1 System Design To


4.2 Mathematical model 28
4.3 Data flow diagram
4.4 UML diagram
4.5 Functional requirement
5 PERFORMANCE ANALYSIS 28

5.1 Introduction To
5.2 Performance Measures
35
5.3 Performance Analysis

6 FUTURE ENHANCEMENT AND CONCLUSION 35

6.1 Future Work To


6.2 Conclusion
39

7 PROJECT
IMPLEMENTATION 40

vi
7 7.1 Overview of project modules
40
7.2 Tools and Technology
7.3 Algorithm Detail’s
7.4 Algorithm to
7.5Code Implementation
7.6 Software Interface 70
7.7 Software working

8 REFERENCES
71

vii
LIST OF FIGURES

FIGURE NO. TITLE PAGE NO.

1 System architecture 16

2 System design 18

3 Venn diagram 23

4 State chart 24

5 Content level DFD 25

6 DFD level 1 25

7 DFD level 2 26

8 Use case diagram 26

9 Component diagram 27

10 Deployment diagram 27

11 Model accuracy 32

viii
LIST OF ABBREVIATIONS

S. NO. TITLE ABBREVIATIONS


1. CNN CONVOLUTIONAL NURAL
NETWORK
2. IG IMAGE SEGMENTATION

3. ANN ARTIFICIAL NURAL


NETWORK
4. SVM SUPPORT VECTOR MACHINE

5. IP IMAGE PREPROCESSING

6. HTML HYPERTEXT MARKUP


LANGUAGE

7. CSS CASCADING STYLE SHEET

1
INTRODUCTION

1.1 Introduction
In India most of the land is used for agriculture purpose. It is also the back support for Indian
farmer’s financial condition. In recent days, huge amount of loss in quality and quantity of
cotton yield due to different diseases affecting the plant There are various diseases which
obstruct the growth of crops in fields which may cause huge loss in the quality of products.
Nowadays image processing is used a lot for detecting such diseases, Pests like the germ,
fungus, and microorganisms are main cause of the disease to crops due to failure in excellence
and extent of production. It is huge loss to the farmer.
This paper is based on Artificial Intelligence system especially Deep learning. As Farmer, we
know Farmer can’t solve Farm’s complex and even small problems due to lack of perfect
education. So as AI enthusiastic we decided to solve this problem using the latest technology
like AI. In which implements Convolutional Neural Network to detect cotton leaf diseases. Cnn
is easy to use for discover infection created by Bacteria and environmental effects. In early
stage Disease detection is challenging task for farmers where physical presence is a must.
Disease detection and recognition is the very important. There are various algorithms in image
processing for disease recognition by image classification like KNN, SVM, Random Forest,
Artificial Neural Network and CNN.

1.2 Motivation for the work

We all know many Farmer can’t solve Farm’s complex and even small problems due to lack of
perfect education. The goal of this application is to develop a system which recognizes crop

2
diseases. Our Goal Is build a website where we can upload an image of any cotton plant leaf
and this website it will tell you information about which decease it is on plant and how we can
treat plant decease. A cotton leaves disease is a portion of leaves with an abnormal growth due
to infections, fungus. Cotton leaves diseases at their early stages can be cured very easily;
otherwise they begin to spread to other parts of the body and may be deadly. An early detection
of cotton leaves disease is essential for such patients. Due to the high cost involved in various
dermatology testing procedures for every patient, an automated system is required to give better
solution for cotton leaves disease diagnoses through inspection of image. System provide visual
to help the doctors to further diagnose and prescribe the correct prescription and medication. In
this system, an innovative approach for automatic identification of cotton leaves disease is
proposed. To improve the quality of cotton leaves disease images, image processing is used
with Edge detection, Binary, and Noise filter. The efficacy of the proposed work has been
verified by measuring the entropy of the resultant images obtained for different cotton leaves
diseases.

1.3 Objectives
There is need of automated and expert systems which is capable to provide comprehensive and
up-to-date information and consultation in interactive and user-friendly manner. It provides
cotton leaves disease identification and suggestion according to disease type. Image processing-
based system has been developed to fulfil the following objectives:
To apply deep learning techniques to detect diseases found on the cotton leaf.
 To predict different diseases to give remedies to farmer.
 To study biotic, abiotic and environmental causes of leaf diseases.
 To make a communication channel between customer and service providers.

1.4 Project Scope & Limitations

This application is implemented only for Cotton leaves diseases. Following points are
considered as

3
 The proposed system is used to identify the different diseases of cotton leaf.
 The proposed system will be help to increase in productivity of cotton.
 The proposed system will require less manpower because of Detection and prediction of
diseases by system.

1.5 Methodologies of Problem solving


The steps involved in image processing are as follows,

A. IMAGE PREPROCESSING

Image pre-processing is the process of capturing or generating digital image using image
sensors. It can be considered as a simple process in which an image in digital form is given.
It is also used to remove noise or other object removal from the image. This stage involves
pre-processing such as scaling. Image scaling is applied because it reduces the pixel size. So,
it requires less time for further accessing.

B. IMAGE SEGMENTATION

Image segmentation is the process of partitioning or dividing an image into its constituents’
parts or objects. Segmentation is done to recognise the objects from an image. If it makes
more accurate there will be successful recognition. There are number of algorithms available
for segmentation procedures. It is used in wide applications such as traffic image, health care,
image processing, etc. The various techniques used for segmentation like edge based, neural
based, threshold based, cluster based. For this method frequently used and efficient is cluster
based method. In cluster-based method there many types of clustering such as K-means
clustering, Fuzzy C-means clustering, Subtractive clustering mountain clustering. One of the
most used algorithm is K-means clustering. It is so because it is simple and computationally
faster than the other. Segmentation plays a major role in medical field and image processing
field. So detected images are segmented using different technique and output be used for next
process i.e. feature extraction.

1) CNN

4
CNN itself is a technique of classifying images as a part of deep learning. In which we apply
single neural network to the full image.

i. Accepts a volume of sizeW1×H1×D1

ii. Requires four hyper parameters:

 Number of filters K

 Their spatial extent F

 The stride S

 The amount of zero padding P

iii. Produces a volume of size W2×H2×D2 where:

a. W2=(W1-F+2P)/S+1

b. H2=(H1−F+2P)/S+1(i.e. width and height are computed equally by symmetry)

c. D2=K.

iv. With parameter sharing, it introduces F*F*D1 weights per filter, for a total of (F*F*D1)*K
weights and K biases. In the output volume, the dth depth slice (of size W2*H2) is the result of
performing a valid convolution of the dth filter over the input volume with a stride of S, and then
offset by dth bias.

v. A common setting of the hyper parameters is F=3, S=1,P=1

5
Fig.1 Flow of system
The first stage is image processing. Original image may contain some unwanted noise;it becomes
necessary to filter the image to remove the noise. Then by using image transformation (Cropping),
the representation of an image into something that is more meaningful and easier to analyse. The
specific areas of leaf disease are precisely divided, and the identification accuracy is improved
through processed image. The next stage is feature extraction, in which the image texture features
and colour features of the skin disease are further extracted. In texture feature extraction, CNN
algorithm is used to find the mathematical parameters. Thisstage is to identify the various types of
skin diseases according to obtained features based onCNN.

6
LITERATURE SURVEY

2.1 Introdection
In recent year, limited number of works has been done related to cotton disease
classification, cotton stage Identification using deep learning models.
Looking into the current situations of computerized skin disease diagnosis systems, there are
few solutions available which are still under research developments. Certain limitations and
drawbacks are identified in those hence this solution tries to overcome the existing problems
with different approach.
A literature survey conducted based on the factors like diseases examined, features and
classifier model considered in the study and the classification accuracy achieved.

2.2 Literature Survey

2.2.1 Objective of First Paper: Rice Disease detection Pattern Recognition Techniques. Published
in 11th International Conference on Computer and Information Technology
Gist of Paper: The point of this paper is to depict a product model framework for the
discovery of malady in rice plant based on different pictures of the rice plants. Pictures of the
tainted piece of the rice plant are taken utilizing computerized camera. With the end goal to
identify the abandoned piece of the plant different procedures like picture division, picture
developing and so forth. By utilizing neural system the tainted piece of the leaf is grouped.
Picture preparing and delicate processing procedures are joined on infected plant.

Procedures embraced in paper:

 Preparing & design examination strategies of images

 Binary cutoff methods

 Border layout calculation using eight-availability strategy

 Self-organizing map(SOM)

7
In this examination paper, the diseased part of the rice plant leaf is identified with the help of
the self-organizing map. Testing is done using four different images of the crop. Infected
region is extracted using neural networks pattern recognition techniques.

By utilizing effective example acknowledgment procedures, the framework will have the
capacity to do the opportune finding of the field issue and the proposal will assist the
ranchers with taking the suitable measure to build the nature of the harvest .It won't just
decrease the improvement cost later on yet in addition spare the earth too.

2.2.2 Objective of Second Paper: Detection of plant leaf diseases using image segmentation

and soft computing techniques. Published in Information Processing in agriculture.


Gist of Paper: This paper monitor the crop growth using the image segmentation techniques.
Noise filtering is done and features are extracted and then image is further classified to detect
the diseased part. Strategies/Methodology embraced in paper:

 Support Vector Machine (SVM)

 Artificial Neural Network (ANN)

 Dispersion method

 Self-sorting out element Using image segmentation techniques and machine learning
algorithms the information for ripening stages of crop and infected part recognition is made.
There were a few issues for doing extraction of vague shading pixels from the foundation of
the picture.

 Neural arrange don't permit better division of the grape leaf illness pixels.

 The framework will show programmed determination ability with extremely successful
execution for the further agrarian item investigation/review framework improvement.

2.2.3 Objective of Third Paper: Remote Area Plant diseases detection using Image Processing.
Published in IOSR Journal of Electronics and Communication Engineering.

8
Gist of Paper: Infected part in the plant can be detected with help of color, and other
changing properties by using classification algorithm.

Strategy/Methodology embraced in paper:

 Segmentation

 RGB

 Color transformation

 Image acquisition

 classification

Different pixel information is extracted and Green leaves pixel and diseased leaf pixel are
compared by finding the ratio of pixel corresponding to the healthy leaf to the pixel
corresponding to the infected leaf. Background is remove and different region of the images
are formatted after the image acquisition.

 Using image segmentation to extract the image feature is best. But important thing is the
level of the results which derived using are how much reliable.

 Results exhibited intriguing enhancement in the forecast framework. It is possibly a


promising option in contrast to existing expectation models.

 Further these approaches are scalable and can be modified as per the requirements

2.2.4 Objective of Fourth Paper: Image processing for smart farming: Detection of disease.
Published in IEEE second International Conference.

Gist of Paper: The point of this paper is to separate the various diseases in the different parts
and then apply the suitable algorithm and to design the approaches in order to detect the
diseases using artificial neural network. Two database of the image is used one for training
and other for the testing.

Strategy/Methodology embraced in paper

 Image Segmentations

 ML calculations 18

9
 Support vector machines

 Artificial Neural Networks

All the disease of the apple and grapes are correctly identified using digital image processing
and machine learning neural networks. Results gets improved when contrasted with the
discriminative models. Machine Learning approaches are adaptable and furthermore can give
secluded methodology to the information investigation particularly for the new area of 'plant
pressure examination'. It will likewise help in the quality revelation process and in addition
the presentation of novel determinations conventions for the complex aggressive attributes
like biotic and abiotic stress and yield.

2.2.5 Objective of the fifth paper: A digital image processing based algorithm which detect and
recognize the plant diseases and various symptoms. Bio system Engineering Volume 102,
Issue 1, January 2009, pp. 9-21. Gist of the paper: The idea purposed here is to process and
analyze the colored images to identify the affected area and various visible symptoms of the
diseases Strategy/Methodology embraced in paper

 Acquisition and Preprocessing

 Pixel contrast enhancement

 Segmentation

 Classification The purposed methodology is applied to twenty different kind of images


result is made on the basis of white and black colors in the resulting image. Black color is
used for represent the symptom of disease and which for unaffected region. The results are
also compared with the 19 binary images in which one represented the disease region and
zero represented the not diseased part. Some variation were there in both the results.
2.2.6 Objective of sixth paper: Plant disease detection using image processing. 2015 international
conference on the computing communication control and automation.

Gist of the paper: the paper provides different types image processing techniques which can
directly be implemented in MATLAB for preprocessing of the image and also brief about the
image segmentation and image classification. For the feature extraction the paper provide

10
algorithmic methods which can easily calculate shape and color oriented features.
Strategies/Methodologies embraced in paper:

 Image preprocessing

 Image enhancement

 SVM classification

 Semantic networks

 K means clustering

 Neural network based classifier

The feature extraction and the image segmentation algorithm used in this paper are efficient
with very high accuracy. Different disease are identified with very high precision rate and
accuracy. Clustering algorithm approach is also very much efficient fast, the clustering
algorithm segment the image in the different clusters in very short span of time . For small
dataset of image the algorithm used in this paper are very effective. But if the dataset size
gets larger then there may come some sort of distortion in the accuracy of the above
approach.
2.2.7 Objective of the seventh paper: Smart Farming: Pomegranate Disease Detection Using Image
Processing‖ Second International Symposium on Computer Vision and the Internet 2015.

Gist of the paper: The paper provides the image processing techniques and the algorithm
which help the farmers to successfully identify the disease in pomegranate. Image acquisition
and image processing of the input image is done using the filter commands in the MATLAB
by pixel values of the input image gets more clarified and the disease which is present in the
pomegranate is successfully detected.
The approach also provide user two different options that is with intent search and without I
ntent search. Strategies/Methodologies adopted

 Image preprocessing

 Feature extraction

 Morphology

11
 Color Coherence Vector (CCV)

 Clustering

 Training and classification

 Intent search

Remote area farmer can also identify the disease in the pomegranate crop as this algorithm
gives user option with and without intent. It let the user to upload the image in the system for
further processing. This approach is very affective. Also experimental readings shows that
the algorithm has eighty two percent accuracy considering average of both case. In almost
every case pomegranate disease is identified. Web base approach is also very fast and there is
no distortion occur in communication of images in transition of images in this approach.
Pixel values remain maintained and cleared.

12
3. SYSTEM ANALYSIS
3.1 Introduction

the model for cotton plant disease recognition using deep CNN .system classifies the leaf
image using image classification algorithm CNN. A Convolutional Neural Network
(ConvNet/CNN) is a Deep Learning algorithm which can take in an input image, assign
importance (learnable weights and biases) to various aspects/objects in the image and be able to
differentiate one from the other. The pre-processing required in a ConvNet is much lower as
compared to other classification algorithms. While in primitive methods filters are hand-
engineered, with enough training, ConvNets have the ability to learn these filters/characteristics.
The whole process of training a model for plant disease detection using CNN in-depth is
described in detail. The complete process is divided into several required sections in the steps
below:

A. Project Description:
The model for plant disease recognition using deep learning CNN . The complete process is
divided into some stages, Appropriate datasets are required at all stages of object recognition
research, starting from training phase to evaluating the performance of recognition algorithms.
Images of the infected plants are captured by digital camera and processed using image growing
,image segmentation techniques to detect infected parts of the plants.

a. Image Acquisition:
In image processing, it is defined as the action of retrieving an image from some source, In
this phase, raw image is taken as input from the user and converted into equivalent gray scale
image. Also the image is resized into size of 128*128.
b. convolutional Layers:
Convolutional layers apply a convolution operation to the input, passing the result to the
next layer. A convolution converts all the pixels in its receptive field into a single value. .The
final output of the convolutional layer is a vector. After the alteration of captured image, the
processed image further passes through three different hidden layer in which feature
extraction, pooling and flattening layer are also performed.

13
c. Disease Prediction:
After applying CNN, using Softmax layer the leaf image is predicted with disease which is
gaining highest probability of occurrence.

3.2 PRESENT SCENARIO


Plant diseases cause periodic outbreak of diseases which leads to large scale death and
famine. It is estimated that the outbreak of helminthosporiose of rice in north eastern India in
1943 caused a heavy loss of food grains and death of a million people. Since the effects of
plant diseases were devastating, some of the crop cultivation has been abandoned. It is
estimated that 2007 plant disease losses in Georgia (USA) is approximately $653.06 million
(Jean, 2009). In India no estimation has been made but it is more than USA because the
preventive steps taken to protect our crops are not even one-tenth of that in USA.

The naked eye observation of experts is the main approach adopted in practice for detection
and identification of plant diseases. But, this requires continuous monitoring of experts which
might be prohibitively expensive in large farms. Further, in some developing countries,
farmers may have to go long distances to contact experts, this makes consulting experts too
expensive and time consuming and moreover farmers are unaware of non-native diseases.

3.3 Existing system

In recent year, limited number of works has been done related to cotton disease , but
those works was not for local Farmers, local Farmer can’t understand those work because of
lack of perfect education. and some more existing problem is such as-

Drawbacks
• Existing system is not user-friendly for farmers.

• Recognizing Cotton leaf diseases accuracy is not accurate.

• Need high definition images.

• Need massive storage is required for this system to work effectively.

14
3.4 PROPOSED SYSTEM
In the proposed system at first the images are acquired from the farmer. The images are received
from the farmer via the Android Application developed exclusively for the service of the farmer. The
images are uploaded by the farmer by choosing the appropriate image of the leaf or the stem
preferably from the Choose File option. On uploading a image the farmer receives a ID which has to
be used later by him to check the pesticides for the affected disease. The image uploaded by the
farmer is processed . Then image-processing techniques are applied to the acquired images to extract
useful features that are necessary for further analysis. After that, several analytical techniques are
used to classify the images according to the specific problem at hand. The disease type is detected and
displayed .The affected area is also displayed to identify the severity of the disease. The pesticides for
the detected disease and the amount to be given to the plant are entered into the database. The farmer
in order to see the details has to click another button in the app which is View Message. On entering
the ID which was previously displayed to the farmer the farmer can view the details that were
uploaded.. Cambridge Institute Of Technology 2015-2016 Page 7 Automatic detection of plant
diseases is an important research topic as it may prove benefits in monitoring large fields of crops,
and thus automatically detect the diseases from the symptoms that appear on the plant leaves. This
enables machine vision that is to provide image based automatic inspection, process control and robot
guidance. Comparatively, visual identification is labor intensive, less accurate and can be done only
in small areas.

• The aim of the proposed system is to develop an application which recognizes cotton leaf
diseases. Our Goal Is build a website where we can upload an image of any cotton plant leaf
and this website it will tell you information about disease. Cotton farmer need to upload the
image and then with the help of image processing we can get a digitized color image of a
diseased leaf and then we can proceed with applying CNN to predict cotton leaf disease.

3.4.1 ADVANTAGE
• Developing a user-friendly web-based system for farmers.
• Recognizing Cotton leaf diseases accurately from input images.

• High accuracy

15
3.5 System architecture

System architecture

16
4. SYSTEM DESIGN AND IMPLEMENTATION

4.1 System Design

Farming is one of the important professions in many countries including India. Indian
financial system is dependent on agriculture production,the keen attention to the concern of
food production is necessary.While keeping track of diseases in plants by specialists becomes
costly and cannot be affordable by average farmers. There is a need for a system which can
automatically detect the diseases and can tell about what pesticides to use so that appropriate
remedy can be taken after detection of diseases. The aim of the proposed system is to
develop an application which recognizes cotton leaf diseases. With help of image processing
we can get a digitized color image of a diseased leaf and then we can proceed with applying
CNN (Convolutional Neural Network) to predict cotton leaf disease. System which
implements Convolutional Neural Network to detect cotton leaf diseases. It offers more
capable ways to detect infection created by bacteria and environmental effects. Disease
detection in early stages it very challenging task for farmer but once the disease is detected
he can take prior steps to cure them. There are various algorithms in image processing for
disease recognition
by image classification like KNN, SVM, Random Forest, Artificial Neural Network and
CNN. Previously image classification algorithms like face recognition need to pay attention
at where the face is located in an image this major problem is overcome by CNN as well as
features of an image are deeply processed at each layer. Every disease on crop has different
features which are extracted at each layer of the convolution network. The goal of this
application is to develop a system which detects crop diseases. In this proposed system the
user has to upload an image on the system,Image processing starts with the digitized color
image of the diseased leaf. Finally by applying the CNN plant disease can be predicted.

In this section, the architecture of the proposed system designed for Image processing,
Feature extraction, classification of cotton leaf diseases images, disease detection, and
Pesticides, remedy, precautions suggestion etc. The system will help significantly in the
detection of different types of disease for cotton plant. The whole architecture can be divided

17
into several modules comprising of pre-processing, feature extraction, and classification. The
block diagram of the system is shown in figure below.

System design

18
Image capture & Uploading:

Image is processed for detect cotton leaf disease. Achieve accuracy in disease detection and
classification is overwhelming task. Image quality may effect on efficiency of classifier
result. As constraints of project specify that image quality should be high, image should be in
proper format, no any special effects are applied on image. We can upload existing image or
capture and upload image.

Pre-processing: Achieving high performance of cotton leaf disease detection system


requires overcoming some major difficulties. Such as creating a database and unifying image
dimensions. In the following section, the technique used in image pre-processing is
explained.
 Edge detection
There are many ways to perform edge detection. However, the most may be grouped into two
categories, gradient and Laplacian. The gradient method detects the edges by looking for the
maximum and minimum in the first derivative of the image. The Laplacian method searches
for zero crossings in the second derivative of the image to find edges.
 Binary
This step illustrates the use of the binary threshold image filter. This filter is used to
transform an image into a binary image by changing the pixel values according to the rule
illustrated. The user defines two thresholds—Upper and Lower—and two intensity values—
Inside and Outside. For each pixel in the input image, the value of the pixel is compared with
the lower and upper thresholds. If the pixel value is inside the range defined by [Lower,
Upper] the output pixel is assigned the Inside_Value. Otherwise the output pixels are
assigned to the Outside_Value. Thresholding is commonly applied as the last operation of a
segmentation pipeline.

 Noise filter
Image noise is an unavoidable side-effect occurring as a result of image capture, more simply

19
understood as inaudible, yet inevitable fluctuations. In a digital camera, if the light which enters
the lens misaligns with the sensors, it will create image noise. Even if noise is not so obviously
visible in a picture, some kind of image noise is bound to exist. Every type of electronic device
receives and transmits some noise and sends it on to what it is creating.

Crop Image: To resolve the problem of different image sizes in the database an input image
is either increase or decrease in size. Standard size of the image will get the same number of
features from all images. Moreover, resizing the image reduces processing time and thus
increases system performance.

Feature Extraction: In this step we have to point out highlighted data from the query image.
Features are extracted in the form of colour and texture of image. Disease is detected based on
colour and texture threshold calculated. These features are being compared with sample image,
for further classification.We proposed feature extraction from a trained convolutional neural
network. It is the easiest and robust approach for comparing query and trained sample. Here K-
means algorithm is used for feature extraction.
Classification: Classification is a computer vision method. After extracting features, the role of
classification is to classify the image using CNN. Firstly CNN trainclassifier using extracted
features from the training set for processing. While execution of system CNN classify the query
image in one of the class of disease based on minimum distance between query image and
sample image.

Result: Result computed from above stages are contain disease type or disease name. According
to disease name following contains are included in result.
 Disease name
 Pesticides and their cost
 Remedies over disease
 Precautions

4.2 Mathematical Model

20
The process of expressing system in mathematical terms, expression, and equation is defined
as mathematical modelling. Physicists, engineers, statisticians, operations research analysts and
economists use mathematical models most extensively. A mathematical model is a description
of a system using mathematical concepts and language. Mathematical models are used not only
in the natural sciences and engineering disciplines but also in the social sciences. Mathematical
models can take many forms, including but not limited to dynamical system, statistical systems,
differential equations or game theoretic models. A model may help to explain a system and to
study the effects of different components, and to make predictions about behaviour.
Mathematical models can take many forms, including but not limited to dynamical system,
statistical systems, differential equations or game theoretic models.

4.2.1 Set Theory Set theory is the mathematical theory of well-determined collections called
sets, which contain members or elements of the set. Set theory is the branch of mathemati1cal
logic that studies sets, which are collections of elements. Pure set theory deals exclusively with
sets, so the only sets under consideration are those whose members are also sets. Although any
type of object can be collected into a set, set theory is applied most often to objects that are
relevant to mathematics. The theory of the hereditarily-finite sets, namely those finite sets whose
elements are also finite sets, the elements of which are also finite, and so on, is formally
equivalent to arithmetic. If we have a set we say that some objects belong (or do not belong) to
this set, are (or are not) in the set. We say also that sets consist of their elements. So, the essence
of set theory is the study of infinite sets.

System Description:

Let S be the system of skin disease detection


S having sets of parameter I,R,P,O.
Set S= {{ I } , { R } ,{ P } ,{ O }}
Where,
S is Cotton Leaves Disease Detection System
I is set of all inputs giving to system.

21
R is set of rule that drives your input set.
P is set of all processes which formulated on I and R.
O is set of output expected from system.

Inputs (I) :{I1,I2,I3 }


Where,
I1 = Image uploading.
I2 = Feature extraction parameter
I3 = Disease symptoms
I4 = Disease Sample with labelling

Rules (R): {R1,R2,R3,R4}


Where,
R1 = Uploaded image should beproper.
R2 = Disease symptoms are defined properly.

R3 = Client must be provide the crop/plant leaf for detection.

R4 = Internet/network connectivity is must for to accessing the Portal.

Processes (P) :{P1,P2,P3}


Where,
P1 = Image Uploading
P2 = Image Pre-Processing.
P3 = Feature Extraction according to symptoms.
P4 = Disease Classification
P5 = Result display

22
Output (O):{O1,O2,O3 }
Where,
O1 = Disease Prediction.
O2 = Pesticides Recommendation with Cost of suggested Pesticides
O3 = Inform Farmer via SMS..

Venn diagram:

Fig.3: Venn diagram for system

State Chart Diagram:

According to system the tuples are represented as follows:

23
Where,
 q0= Uploading Image
 q1= Image Preprocessing
 q2= Image cropping
 q3= Feature Extraction
 q4= Classification of cotton leaf disease
 q5= Disease classification result
 q6 = Result including Precaution, Remedies, Pesticides.

State Chart Diagram:

Fig.4: State diagram of system

4.3 Data Flow Diagrams


Context level DFD

24
Fig.5Context level DFD

DFD Level 1

Fig.6 DFD Level1

DFD Level 2

25
Fig.7DFD level

4.4UML Diagrams
Use case diagram

Fig.8 Use case diagra

26
Component diagram

Fig.9 Component diagram


Deployment diagram

Fig.10 Deployment Diagram

27
4.6 FUNCTIONAL REQUIREMENTS
Functional requirements define the internal workings of the software: that is, the technical
details, data manipulation and processing and other specific functionality that show how the
use cases are to be satisfied. They are supported by non-functional requirements, which
impose constraints on the design or implementation.Identifying the amount of fertilization
required for Rice Crops using Image Processing system to increase the yield Dept. of CSE,
Cambridge Institute Of Technology 2015-2016

SOFTWARE REQUIREMENTS
Language : python ,html css
OS : Windows 10 (64 bit)
IDE : google colab,dive,spark

HARDWARE REQUIREMENTS

Processor : Above 1.5GHZ


Hard Disk : 1000GB
RAM : 6GB

NON-FUNCTIONAL REQUIREMENTS
Non-functional requirements are requirements which specify criteria that can be used to judge the
operation of a system, rather than specific behaviors. This should be contrasted with functional
requirements that specify specific behavior or functions. Typical non-functional requirements are
reliability, scalability, and cost. Non-functional requirements are often called the ilities of a system.
Other terms for non-functional requirements are "constraints", "quality attributes" and "quality of
service requirements".

28
5. PERFORMANCE ANALYSIS
5.1Introduction
The purposed algorithm is made to run for each individual image. In our solution we have
covered four different type of diseases which are Alternaria Alternata, Anthracnose, Bacterial
blight, Cercospora leaf spot. Given below figures shows the detected disease for input image
from a particular disease dataset

5.2 Performance Measures


The whole process of performance is depend on training a model for plant disease detection
using CNN in-depth is described in detail. The complete process is divided into several required
sections in the steps below-

Dataset: Appropriate data sets are required for all phases of object recognition research, from
the training phase to testing the effectiveness of visual algorithms. All data collected from the
database were downloaded from the Internet, searched for diseases and plant names from various
sources. The dataset will be classified into diseased leaves and healthy leaves. The dataset will
be trained by using a Deep Learning model (Convolutional Neural Network). Therefore, a deep
neural network can be trained to separate adjacent leaves. The next step was to enrich the
database with additional images. The main purpose of the research presented to train the network
is to study the features that distinguish one category from the other. Therefore, when you use
multiple additional images, the network's ability to read relevant features is increased.

Image Pre-processing and Labelling: In order to get a better feature output, the final images
intended for use as a deep neural network configuration database will be processed to determine
consistency. In addition, the process of image editing involves cutting all the images using
machine learning, making a square around the leaves, to highlight the area of interest (cotton
plant leaves). During the data collection phase, images with minimal editing and size less than
500px are not considered valid image data. Additionally, only images where the interest region
has the highest resolution are marked as eligible for the dataset. It was ensured that the pictures
contained all the details needed to learn the feature. Dataset images were scaled to reduce

29
training time, which was automatically calculated by text in Python, using the Open CV
framework. Many resources can be found by searching across the Internet, but their suitability is
often unreliable. In an effort to ensure the accuracy of the classrooms in the database, which was
initially collected by keyword search, agricultural experts examined leaf images and labeled all
images with the appropriate stem of the disease. As is well known, it is important to use
accurately classified images for training and validation data. Only then can a suitable and reliable
acquisition model be developed. At this stage, duplicate images that were left after the initial
collection and collection of images were removed from the database.

Neural Network Training: It is proposed to train a deep convolutional neural network to model
image separation from the dataset. There are several in-depth study frameworks, such as the
Python Theano Library and the Lua Extensive Electronic Library, Torch7. In addition, there is
Caffe, an in-depth source learning framework developed by BVLC that contains a CaffeNet
reference model. CaffeNet is a deep CNN with multiple layers that continuously integrates
features from input images. Specifically, the network consists of eight reading layers and five
specification versions and three fully integrated layers. The construction of CaffeNet is
considered a start, but has been redesigned to support our 15 sectors. The final layer was changed
and the softmax layer extraction was made a parameter according to the needs of the presented
lesson. The convolutional layer is an important basis for building a convolutional neural
network. Layer parameters contain a set of readable characters that have a small reception field
but extend to the full depth of the input volume. Each convolutional layer contains maps of equal
size, 𝑀𝑥 and and, with a kernel of size 𝐾𝑥, and 𝐾𝑦 is moved to a specific region of the input
image. The 𝑥 and y.

30
sketch elements define how many pixels the filter / kernel skips on 𝑥- and 𝑦- pathways between subsequent
interactions. The size of the output map can be defined as: where indicates the layer. Each map in layer 𝐿
is connected to most 𝑀 −1 maps in layer 𝐿 −1. Rectified Linear Units (ReLU) are defined as: Deep CNN
with ReLUs trains several times faster. This method is used for the extraction of the entire convolutional and
fully connected layer. Apart from the output, standard installation is not required; is used after ReLU
disconnection after the first and second convolutional layers because it lowers the top-1 and top-5 values. At
CNN, neurons inside the latent layer are separated into ―feature maps.‖ The neurons within the feature map
share the same weight and bias. Neurons within a map element search for the same feature. These neurons are
different because they are connected to different neurons in the lower layer. So in the first hidden layer, the
neurons within the feature map will be linked to different regions of the input image. The hidden layer is
separated by feature maps where each neuron in the feature map looks at the same element but at different
image capture locations. Basically, a feature map is the result of applying convolution to an entire image. The
features of each layer are displayed in a separate block, where visibility represents the strongest performance
of a given feature map, from the first convolutional layer, where the elements from individual pixels to the
simple lines, in the fifth convolutional layer where layered features and parts of the leaves are displayed.
Another important layer of CNN is the integration layer, which is a type of offline reduction. The
functionality of the pools provides a kind of translation flexibility; it works independently across the input
depth slide and makes its size geographically. Excessive blending is used to benefit the reduction of excessive

31
excess. And in favor of reducing overeating, the quit layer is applied to the first two layers that are fully
connected. But the failure to drop out of school is that it increases training time by 2-3 times compared to a
normal neural network of direct construction. Bazesian performance tests have also proven that ReLUs and
school dropouts have the effects of collaboration, which means that they are beneficial when used together.
CNN's advancement refers to their ability to study medium image rep.

5.3 Performance Analysis

The results training with the whole database containing both original and augmented images. As
it is known that convolutional networks are able to learn features when trained on larger datasets,
results achieved when trained with only original images will not be explored.

After fine-tuning the parameters of the network, an overall accuracy of 96.3% was achieved,
after the 100th training iteration (95.8% without fine-tuning). Even after the 30th training
iteration high accuracy results were achieved with exceedingly reduced loss, but after the 60th
iteration, the balance in accuracy and loss was carried out in high accuracy.

the trained model was tested on each class individually. Test was performed on every image
from the validation set. The results are displayed to emphasize how many images from total of
each class are accurately predicted. Figure 8 illustrates trained model’s prediction results
separated for every class.

Models gives more than 98% accuracy on training and validation daa set in just 500 epochs. In
more epochs accuracy can increase.

32
There are many methods in automated or computer vision plant disease detection and
classification process, but still, this research field is lacking. In addition, there are still no
commercial solutions on the market, except those dealing with plant species recognition
based on the leaves images. IN this system, a new approach of using deep learning method
was explored in order to automatically classify and detect plant diseases from leaf images.
New plant disease image database was created, containing more than 1,100 original images
taken from the available Internet sources and extended to more than 30,000 using appropriate
transformations. The experimental results achieved precision between 91% and 98%, for
separate class tests. The final overall accuracy of the trained model was 96.3%. Fine-tuning
has not shown significant changes in the overall accuracy, but augmentation process had
greater influence to achieve respectable results.

33
6. FUTURE ENHANCEMENT AND CONCLUSION

6.1 Future Work

The future work will be including many more. Starting from the user interface; we can
improve user interface from user’s feedback. Another improvement would be to increase the
number of images in the data-set for the better learning of the system since the efficiency
classification algorithm increase with bigger data-sets. The data-set can also be made from
the input image given by the users. The images can be stored in a database that when labelled
correctly and be used for supervised learning or unsupervised learning when used without
labels. Also, currently the system has been trained on only a few diseases that can be
increased to many more in the future as and when the data-set of the particular disease is
available. Same work can be carried out for identification of diseases on other type crops like
Orange, Citrus, Wheat, Corn, Maize, etc.
Web based image processing techniques can be implemented. In this user is provide with two
modes with and without internet. In case of web base processing remote area users can
upload image in system and whole image system techniques and classification algorithm will
we implemented in the cloud itself. Real time monitoring of the data is there using the cloud
platform.
Further we are planning to transform the project from prototype to a complete end use
product. This can be done using Tensor Flow library function in Python IDE with high
processors (recommended using NVIDIA). The end product would be accurately predicting
disease/pest attacks along with identifying them. Larger set of data would be provided for
training network. The whole algorithm would be developed using Tensor Flow for better
processing. OpenCV is used for Image analytics similar to Image Processing Toolbox in
MATLAB. Therefore, the farmer has to just take a snap of the leaf, upload it to the cloud
where the back end processing will do predict/detect analysis and give corrective measures
for preventing and eliminating external hosts.

34
6.2 Conclusion

we have completed Image classification, Image Categories, Feature Extraction, and Training
Data. The whole development of algorithm is done in MATLAB tool. We have used several
toolboxes like Statistics and Machine Learning toolbox, Neural Network Toolbox and Image
Processing Toolbox. The outputs as of now are the training data in form of image categories,
image classification using K-Means clustering and moisture content along with predicting of
withstanding. The algorithm is done with training data and classification of given image
dataset. The test input image is compared with the trained data for detection and prediction
analysis. We are using Unsupervised Learning for precise accuracy. For example, let’s take
trained data of Indian Rice plants and test input as African Rice plant. The accuracy would be
low because the slight difference in appearance. Hence, we are focussing on Unsupervised
Learning. The example would get 99% accuracy using Fuzzy C-Means algorithm. The name
itself tells the data might be Fuzzy but we will be getting precise accuracy. Therefore, we are
avoiding using Supervised Learning techniques.
The data mining techniques are playing a significant role in the agriculture industry and other
industries. Data mining algorithm are easy implement, we can solve complex problems using
these techniques. Using image techniques and data mining algorithms we successfully
identified the affected area in the plant leaf. Various features of the image are extracted with
their numeric values. The algorithm used here is very much efficient and best case time space
complexities are achieved. For ninety percentage of images average clustering and
processing time is less then twenty seconds. Average accuracy of ninety plus percentage is
achieved in every query image of the dataset.

35
7. PROJECT IMPLEMENTATION

7.1 Overview of Project Modules


In recent days, agriculturalists face many problems because of the disease that affected on
plants. Due to the crop disease, Year productivity of farmers gets lower. Manual monitoring
of plant disease tends to require tremendous amount of work and also require the excessive
processing time. Hence, the method used in this paper is image processing. The steps that are
implemented here is image acquisition, segmentation, feature extraction and classification of
plant diseases..
7.2 Tools and Technologies Used
Image processing
Image Processing means processing digital image by means of a digital computer. We can
also say that it is a use of computer algorithms, in order to get enhanced image either to
extract some useful information.

Image processing mainly include the following steps:

 Importing the image via image acquisition tools;


 Analyzing and manipulating the image;
 Output in which result can be altered image or a report which is based on analyzing that
image.

Image processing steps

1. Acquisition– It could be as simple as being given an image which is in digital form.


The main work involves:
a) Scaling
b) Color conversion (RGB to Gray or vice-versa)

2. Image enhancement – It is amongst the simplest and most appealing in areas of Image
Processing it is also used to extract some hidden details from an image and is subjective.

36
3. image restoration – It also deals with appealing of an image but it is objective
(Restoration is based on mathematical or probabilistic model or image degradation).

4. color image processing– It deals with pseudocolor and full color image processing
color models are applicable to digital image processing.

5. wavelets and multi-resolution processing– It is foundation of representing images in


various degrees.

6. Image compression-It involves in developing some functions to perform this operation.


It mainly deals with image size or resolution.

7. Morphological processing-It deals with tools for extracting image components that are
useful in the representation & description of shape.

8. Segmentation procedure-It includes partitioning an image into its constituent parts or


objects. Autonomous segmentation is the most difficult task in Image Processing.

9. Representation & description-It follows output of segmentation stage, choosing a


representation is only the part of solution for transforming raw data into processed data.

10. Object detection and recognition-It is a process that assigns a label to an object based
on its descriptor.

7.3Algorithm Details

7.3.1 K- means

A peculiarity of the k-means algorithm is that it is sensitive to the local structure of the data. It
works in following step.

37
 Load the data

 Initialize colour and texture feature to 0

 For each image in the data

 Calculate the distance between the query image and the current image from the data.

 Add the distance and the index of the example to an ordered collection

 Sort the ordered collection of distances and indices from smallest to largest (in ascending order)
by the distances

 Pick the first K entries from the sorted collection

 Get the labels of the selected K entries

 If regression, return the mean of the K labels

 If features match , return the mode of the K labels

The popular classification technique k-means clustering was used here to classify Ssamples into
K clusters. The members of each clustershould have the minimum distance by their calculating
mean value. The clustering is achieved by: calculating minimum distance between query image
and sample image.Using the feature values extracted from image,the k-means clustering can be
demonstrated. In this example, k = 4 (cotton leaf disease)and each cluster consists of five
members. K-means algorithm started working by estimating all the distances between each pixel
of image. The smallest distance was selected for classification. Similarly all other clusters are
form. Then, a point that had not been assigned to the first cluster was selected and its four
closest unused neighbours were assigned to the second cluster. This was repeated until all the
points were assigned to the four clusters. The most successful clustering was achieved when
maximum number of features were got used. The poor classification accuracy is explained by
the fact that only few features were used. The k-means clustering algorithm has been employed

38
for multiple cotton leaves disease classification.

7.3.2 CNN

The proposed system classifies the leaf image using image classification algorithm CNN. It can
automatically detect and recognize diseases based on extracted features at each convolution
layer. The system used image processing technique for disease detection. The user needs to
upload the cotton plant leaf image. The system can pre-process the uploaded image and then
apply CNN technique. By using CNN technique system can test the image with trained dataset
and extract the features.
 Image Acquisition: In this phase, raw image is taken as input from the user and converted
into equivalent gray scale image. Also the image is resized into size of 128*128.
 Convolutional Layers: After the alteration of captured image, the processed image further
passes through three different hidden layer in which feature extraction, pooling and
flattening layer are also performed.
 Disease Prediction: After applying CNN, using Softmax layer the leaf image is predicted
with disease which is gaining highest probability of occurrence.

7.4 Algorithm

Traditional feature learning methods rely on semantic labels of images as supervision. They
usually assume that the tags are evenly exclusive and thus do not point out towards the
complication of labels. The learned features endow explicit semantic relations with words. We
also develop a novel cross-model feature that can both represent visual and textual contents.
CNN itself is a technique of classifying images as a part of deep learning. In which we apply
single neural network to the full image.
 Accepts a volume of size W1H1D1
 Requires four hyper parameters:
 Number of filters K
 Their spatial extent F

39
 The stride SThe amount of zero padding P
 Produces a volume of size W2H2D2 where:3
 W2=(W1-F+2P)/S+1
 H2=(H1F+2P)/S+1(i.e. width and height are computed equally by symmetry)
 D2=K
 With parameter sharing, it introduces F*F*D1 weights per filter, for a total of (F*F*D1)*K
weights and K biases. In the output volume, the dth depth slice (of size W2*H2) is the result
of performing a valid convolution of the dth filter over the input volume with a stride of S,
and then offset by dth bias.
 A common setting of the hyper parameters is F=3, S=1,P=1

However, there are common conventions and rules of thumb that motivate these hyper
parameters.

40
7.5 COAD IMPLEMENTATION

Tools / IDE
I used Jupyter NoteBook (Google Colab) for model training. used spyder for model
deployment on the local system. To use Jupyter NoteBook and Spyder, just install anaconda.

Software Requirments
Python == 3.7.7
TensorFlow == 2.1.0
Keras == 2.4.3
NumPy == 1.18.5
Flask == 1.1.2
Install above packages using below command in anaconda prompt

pip install tensorflow==2.1.0


pip install Keras==2.4.3
pip install numpy==1.18.5
pip install flask==1.1.2

41
Cotton Plant Disease Prediction WEB App

## Project: Cotton Plant Disease Prediction & Get Cure AI App - IAIP

#import libraries
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
import matplotlib.pyplot as plt

keras.__version__

train_data_path = "/content/drive/My Drive/My ML Project /DL Project/CNN/cotton


plant disease prediction/data/train"
validation_data_path = "/content/drive/My Drive/My ML Project /DL
Project/CNN/cotton plant disease prediction/data/val"

def plotImages(images_arr):
fig, axes = plt.subplots(1, 5, figsize=(20, 20))
axes = axes.flatten()
for img, ax in zip(images_arr, axes):
ax.imshow(img)
plt.tight_layout()
plt.show()

# this is the augmentation configuration we will use for training


# It generate more images using below parameters
training_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,

42
fill_mode='nearest')

# this is a generator that will read pictures found in


# at train_data_path, and indefinitely generate
# batches of augmented image data
training_data = training_datagen.flow_from_directory(train_data_path, # this is
the target directory
target_size=(150, 150), # all images will
be resized to 150x150
batch_size=32,
class_mode='binary') # since we use
binary_crossentropy loss, we need binary labels

training_data.class_indices

# this is the augmentation configuration we will use for validation:


# only rescaling
valid_datagen = ImageDataGenerator(rescale=1./255)

# this is a similar generator, for validation data


valid_data = valid_datagen.flow_from_directory(validation_data_path,
target_size=(150,150),
batch_size=32,
class_mode='binary')

images = [training_data[0][0][0] for i in range(5)]


plotImages(images)

model_path = '/content/drive/My Drive/My ML Project /DL Project/CNN/cotton plant


disease prediction/v3_red_cott_dis.h5'
checkpoint = ModelCheckpoint(model_path, monitor='val_accuracy', verbose=1,
save_best_only=True, mode='max')
callbacks_list = [checkpoint]

43
#Building cnn model
cnn_model = keras.models.Sequential([
keras.layers.Conv2D(filters=32,
kernel_size=3, input_shape=[150, 150, 3]),
keras.layers.MaxPooling2D(pool_size=(2,2)),
keras.layers.Conv2D(filters=64,
kernel_size=3),
keras.layers.MaxPooling2D(pool_size=(2,2)),
keras.layers.Conv2D(filters=128,
kernel_size=3),
keras.layers.MaxPooling2D(pool_size=(2,2)),

keras.layers.Conv2D(filters=256,
kernel_size=3),
keras.layers.MaxPooling2D(pool_size=(2,2)),

keras.layers.Dropout(0.5),

keras.layers.Flatten(), # neural network


beulding
keras.layers.Dense(units=128,
activation='relu'), # input layers
keras.layers.Dropout(0.1),

keras.layers.Dense(units=256,
activation='relu'),
keras.layers.Dropout(0.25),

keras.layers.Dense(units=4,
activation='softmax') # output layer
])

# compile cnn model

44
cnn_model.compile(optimizer = Adam(lr=0.0001),
loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# train cnn model


history = cnn_model.fit(training_data,
epochs=500,
verbose=1,
validation_data= valid_data,
callbacks=callbacks_list) # time start 16.06

# summarize history for accuracy


plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

history.history

45
Open Spyder and create a new project then create folders and files according to below
hierarchy of the project.

APP.PY

#Import necessary libraries


from flask import Flask, render_template, request

import numpy as np
import os

from keras.preprocessing.image import load_img


from keras.preprocessing.image import img_to_array
from keras.models import load_model

#load model
model =load_model("model/v3_pred_cott_dis.h5")

46
print('@@ Model loaded')

def pred_cot_dieas(cott_plant):
test_image = load_img(cott_plant, target_size = (150, 150)) # load image
print("@@ Got Image for prediction")

test_image = img_to_array(test_image)/255 # convert image to np array and


normalize
test_image = np.expand_dims(test_image, axis = 0) # change dimention 3D to 4D

result = model.predict(test_image).round(3) # predict diseased palnt or not


print('@@ Raw result = ', result)

pred = np.argmax(result) # get the index of max value

if pred == 0:
return "Healthy Cotton Plant", 'healthy_plant_leaf.html' # if index 0 burned
leaf
elif pred == 1:
return 'Diseased Cotton Plant', 'disease_plant.html' # # if index 1
elif pred == 2:
return 'Healthy Cotton Plant', 'healthy_plant.html' # if index 2 fresh
leaf
else:
return "Healthy Cotton Plant", 'healthy_plant.html' # if index 3

#------------>>pred_cot_dieas<<--end

# Create flask instance


app = Flask(__name__)

# render index.html page

47
@app.route("/", methods=['GET', 'POST'])
def home():
return render_template('index.html')

# get input image from client then predict class and render respective .html
page for solution
@app.route("/predict", methods = ['GET','POST'])
def predict():
if request.method == 'POST':
file = request.files['image'] # fet input
filename = file.filename
print("@@ Input posted = ", filename)

file_path = os.path.join('static/user uploaded', filename)


file.save(file_path)

print("@@ Predicting class......")


pred, output_page = pred_cot_dieas(cott_plant=file_path)

return render_template(output_page, pred_output = pred, user_image =


file_path)

# For local system & cloud


if __name__ == "__main__":
app.run(threaded=False)

48
INDEX.HTML

<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">

<!-- Bootstrap CSS -->


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-
JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous">
<link
href="https://fonts.googleapis.com/css2?family=Rowdies:wght@700&display=swap"
rel="stylesheet">

<title>COTTON PLANT DISEASE PREDICTION</title>

<style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;

.carousel-inner img {
height: 70vh;
}

49
form {
display: flex;
height: 85vh;
justify-content: center;
align-items: center;
margin-top: 50px;
width: 60%;
text-align: center;
margin: auto;
}

.details h2 {

position: relative;
top: 100px;
margin: auto;
color: rgb(18, 231, 231);
font-size: 3rem;
}

label:hover {
transform: scale(1.03);
}

.details h2 {
/* margin-bottom: 300px; */
position: relative;
top: 100px;
margin: auto;
color: rgb(18, 231, 231);
font-size: 3rem;

.gallery-h1 h1 {

50
background-color: rgb(44, 43, 43);
color: white;
padding: 20px;
border-radius: 15px;

.details h1 {
color: white;
padding: 20px;
border-radius: 15px;
background-color: rgb(45, 47, 49);
}

.upload {

font-size: 20px;
background-color: rgb(255, 252, 252);
border-radius: 20px;
outline: none;
width: 315px;
color: rgb(0, 0, 0);
border: 3px solid rgb(45, 47, 49);

::-webkit-file-upload-button {
color: white;
padding: 20px;
border: 2px solid rgb(129, 129, 129);
background-color: rgb(129, 129, 129);
border-radius: 15px;

::-webkit-file-upload-button:hover {

51
border-radius: 20px;
border: 2px solid rgb(177, 174, 174);

input[type="submit"] {
position: absolute;
margin-top: 150px;
padding: 15px 35px;
background-color: white;
border-radius: 15px;
color: black;
font-size: 1.5rem;
border: 4px solid rgb(31, 185, 190);
}

.carousel-caption {
background: rgba(24, 25, 26, 0.5);
border-radius: 10px;
}

.carousel-caption h3 {

font-family: 'Rowdies', cursive;


color: yellow;
text-transform: uppercase;
margin-bottom: 10px;

.carousel-caption p {
padding: 7px;

52
.img-thumbnail {
height: 300px;
}

.Content-h5 {

padding: 15px;
background-color: rgb(153, 156, 150);
color: white;
border-radius: 15px;
margin-bottom: 25px;
}

@media only screen and (max-width: 325px) {


body {
font-size: x-small;
}
}
</style>

</head>

<body>

<header>
<div class="container-fluid">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0"
class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"
class=""></li>
<li data-target="#myCarousel" data-slide-to="2"
class=""></li>

53
</ol>
<div class="carousel-inner">
<div class="carousel-item active ">
<img src="/static/images/img1.jpg" class="d-block w-100"
alt="...">

<div class="container">
<div class="container background-img3">
<div class="carousel-caption">

<h3>Cotton
Plant Disease Prediction AI App</h3>
<p>
Many veterans said that Deep Learning
and AI is a threat to our world, but if we
use it properly, we can do many good
things today, we will see a small example
of this in which we will be in cotton
farming
Find out about the disease
</p>

</div>
</div>
</div>
</div>

<div class="carousel-item">
<img src="/static/images/img2.jpg" class="d-block w-100"
alt="...">
<div class="container">
<div class="carousel-caption">
<h3> औ
</h3>
<p>
ई Deep Learning and AI

54

आ example

</p>

</div>
</div>
</div>

<div class="carousel-item">
<img src="/static/images/img3.jpg" class="d-block w-100"
alt="...">
<div class="container">
<div class="container ">
<div class="carousel-caption">
<h3>
आ </h3>

<p>

(Deep Learning) आ

(Artificial Intelligence) आ ,

आ आ ,

आ आ आ .

.
</p>

</div>
</div>
</div>
</div>
</div>

55
<a class="carousel-control-prev" href="#myCarousel"
role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-
hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#myCarousel"
role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-
hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</header>

<section>

<div class="container-fluid details">


<h1 class="text-center mt-5 ">Predict Cotton Crop Disease & Get
Cure</h1>

<h2 class="text-center mt-4 mb-4" style="font-size: 2rem;">

</h2>
<form action="/predict" method="post" enctype="multipart/form-data"
onsubmit="showloading()">

<input type="file" name="image" class="upload">


<input type="submit" value="Predict">

</form>
</div>
</section>

<section style="margin-bottom: 100px;">

56
<div class="container gallery-h1">

<h1 class="text-center mt-4 mb-4">Photo Gallery</h1>

<hr class="mt-2 mb-5">

<div class="row text-center text-lg-left">

<div class="col-lg-4 col-md-4 col-6 col-12">


<a href="#" class="d-block mb-4 h-100">
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery1.jpg" alt="">
</a>
</div>
<div class="col-lg-4 col-md-4 col-6 col-12">
<a href="#" class="d-block mb-4 h-100">
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery2.jpg" alt="">
</a>
</div>

<div class="col-lg-4 col-md-4 col-6 col-12">


<a href="#" class="d-block mb-4 h-100">
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery3.jpg" alt="">
</a>
</div>
<div class="col-lg-4 col-md-4 col-6 col-12">
<a href="#" class="d-block mb-4 h-100">
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery4.jpg" alt="">
</a>
</div>
<div class="col-lg-4 col-md-4 col-6 col-12">
<a href="#" class="d-block mb-4 h-100">

57
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery5.jpg" alt="">
</a>
</div>
<div class="col-lg-4 col-md-4 col-6 col-12">
<a href="#" class="d-block mb-4 h-100">
<img class="img-fluid img-thumbnail"
src="/static/images/Gallery6.jpg" alt="">
</a>
</div>

</div>

</div>

</section>

<section>
<div class="container Content-h5">

<h5 style="font-size: 1rem;" class="text-center my-3 contents">


Delivery Contact:
IndianAIProduction.business@gmail.com</h5>

</div>
</section>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-
9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"

58
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-
B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>

</body>

</html>

59
Healthy plant.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"
integrity="sha384-
VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX"
crossorigin="anonymous">

<title>COTTON PLANT DISEASE PREDICTION</title>

<style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}

.border img {
border-radius: 15px;
border: 2px solid black;
}
</style>
</head>

<body>

<div>
<img src="/static/images/cotton palnt banner.png" class="w3-border w3-

60
padding" alt="Indian AI Production"
style="width:100%">
</div>

<div class="container my-2">


<div class="row mb-5">

<div class="col-sm" style="margin-bottom: 23px;">


<span class="border border-primary">
<img src="{{ user_image }}" alt="User Image" class="img-
thumbnail">

</span>
</div>

<div class="col-sm">

<div>
<h1 style="padding: 15px; background-color: rgb(153, 156,
150); color: white;"
class="text-center mb-5 content-h1 rounded">
{{pred_output}} </h1>
</div>
<div class="details">

<h5>

There is no disease on the cotton Plant.</br></br>


ई </br></br>

आ . </br></br>

ઉ ર ર .</br></br>

ಮರದ ಮ ದ ರ ..</br></br>

..</br></br>
</h5>
</div>

61
</div>
</div>

</div>
</body>

</html>

62
heathy_plant_leaf.html

<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">

<!-- Bootstrap CSS -->


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"
integrity="sha384-
VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX"
crossorigin="anonymous">

<title>COTTON PLANT DISEASE PREDICTION</title>

<style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}

.card-style {
background-color: #dcdcdc;

.content {
padding: 15px;
color: white;

63
background-color: rgb(153, 156, 150);
/* font-size: 1rem; */
}

@media (max-width: 430px) and (min-width: 200px) {

.contents {
font-size: 0.6rem;
color: chartreuse;
}

.content-h1 {

font-size: 1rem;
}
}

.border img {
border-radius: 15px;
border: 2px solid black;
}
</style>
</head>

<body>

<div>
<img src="/static/images/cotton palnt banner.png" class="w3-border w3-
padding" alt="yogkhandagre444@gmailcom "
style="width:100%">
</div>

<div class="container my-2">


<div class="row mb-5">

64
<div class="col-sm" style="margin-bottom: 23px;">
<span class="border border-primary">
<img src="{{ user_image }}" alt="User Image" class="img-
thumbnail">
<!-- <img src="{{pred_output}}" alt="User Image" class="img-
thumbnail"> -->

</span>
</div>

<div class="col-sm">

<div>
<h1 style="padding: 15px; background-color: rgb(153, 156,
150); color: white;"
class="text-center mb-5 content-h1 rounded">
{{pred_output}} </h1>
</div>

<h2>Disease Name / / / ર / ರ ದ ರ

/ : </span></h2>
<h3 style="line-height: 100%;">Attack of Leaf Sucking and
Chewing Pests <br> , <br>

<br>

ಮ ದ <br>

</h3>
<hr class="w-100 mx-auto ">
</div>
</div>

<h1> Solution for Disease / / / ર ઉ /

ರ ರ ರ / : </h1>
<p><strong>Use any one Systemic Insecticide, which contain<i> Flonicamid

65
50%/ Thiamethoxam 25% WG / Imidacloprid
17.8 Sl / Acetamiprid 20% SP.</i></strong></p>
<p></p>
<p> , ५०% /

25% WG /

१७.८

/ २०% </p>

<p> , ५०% /

25% WG /

१७.८

/ २०% .</p>

<p> એ ર ઉ ર, 50% /

25% WG / ર
17.8
એ એ / એ ર 20% એ .</p>

<p> ಮ 50% / ಮ ಮ 25% WG / ಮ ರ 17.8

/ ಮ ರ 20% ದರ

ದ .</p>

<p> 50% / 25% WG / 17.8 /

20%

ఒ .</p>
</div>

<section>

<div class="container">
<h1 style="padding: 15px; background-color: rgb(153, 156, 150);
color: white;"
class="text-center my-3 content-h1">
Recommended Products</h1>

66
</div>

<div class="container">

<div class="card-columns">
<div class="card ">
<div class="card-body text-center card-style">
<img style="border-radius: 10px;" class="img-fluid"
src="/static/images/preet.png" alt="">
<h3 class="card-text">Dose: 60-80 gm/Acre</h3>
</div>
</div>
<div class="card">
<div class="card-body text-center card-style">
<img style="border-radius: 10px;" class="img-fluid"
src="/static/images/ulala.png" alt="">
<h3 class="card-text">Dose: 25-40 gm/Acre</h3>
</div>
</div>
<div class="card ">
<div class="card-body text-center card-style">
<img style="border-radius: 10px" class="img-fluid"
src="/static/images/victor.png" alt="">
<h3 class="card-text">Dose: 60-80 gm/Acre</h3>
</div>
</div>
<div class="card ">
<div class="card-body text-center card-style">
<img style="border-radius: 10px;" class="img-fluid"
src="/static/images/confidor.png" alt="">
<h3 class="card-text">Dose: 25-35 ml/Acre</h3>
</div>
</div>
<div class="card ">
<div class="card-body text-center card-style">
<img style="border-radius: 10px;" class="img-fluid"

67
src="/static/images/panama.png" alt="">
<h3 class="card-text">Dose: 60-80 gm/Acre</h3>
</div>
</div>
<div class="card ">
<div class="card-body text-center card-style">
<img style="border-radius: 10px;" class="img-fluid"
src="/static/images/actara.png" alt="">
<h3 class="card-text">Dose: 60-80 gm/Acre</h3>
</div>
</div>

</div>

<!-- <div class="container-fluid contents"> -->


<h5 style="padding: 15px; background-color: rgb(153, 156, 150);
color: white;"
class="text-center my-3 contents">
Delivery Contact:
Yogkhandagre444@gmail.com</h5>
<!-- </div> -->
</div>

</section>

</body>

</html>

68
7.6 SOFTWARE INTERFACE DESIGN

69
7.7 SOFTWARE WORKING SCREENSHOT

. a. Diseased cotton plant output

b. Healthy cotton plant output

70
8. REFERENCES

1. P. Rothe and R. Kshirsagar, ―Adaptive neuro-fuzzy inference system for recognition of cotton leaf
diseases,‖ in Computational Intelligence on Power, Energy and Controls with their impact on
Humanity (CIPECH), 2014 Innovative Applications of. IEEE, 2014, pp. 12–17.

2. A.-K. Mahlein, T. Rumpf, P. Welke et al., ―Development of spectral indices for detecting and
identifying plant diseases,‖ Remote Sensing of Environment, vol. 128, pp. 21–30, 2013.View
at: Publisher Site | Google Scholar.

3. A.-K. Mahlein, T. Rumpf, P. Welke et al., ―Development of spectral indices for detecting and
identifying plant diseases,‖ Remote Sensing of Environment, vol. 128, pp. 21–30, 2013. View at
Publisher · View at Google Scholar · View at Scopus.

4. S.Raj Kumar , S.Sowrirajan,‖ Automatic Leaf Disease Detection and Classification using Hybrid
Features and Supervised Classifier‖, International Journal of Advanced Research in Electrical,
Electronics and Instrumentation Engineering, vol. 5, Issue 6,2016..

5. M. Francis and C. Deisy, "Disease Detection and Classification in Agricultural Plants Using
Convolutional Neural Networks — A Visual Understanding," 2019 6th International Conference on
Signal Processing and Integrated Networks (SPIN), Noida, India, 2019

6. ]Chaudhari Vaishnavi, Gondkar Sayali, Shivarkar Pooja,‖Survey on detection and prediction of leaf
diseases using CNN‖, Indian Journal of Automation and Artificial Intelligence, Volume 6(10), 2019.

7. Patil Tushar, Palambe Shubham, Tawale Gauri ,Patil Rajashree2sanchika Bajpai, ―Cotton Leaf
Disease Identification Using Pattern Recognition Techniques‖, Multidisciplinary Journal of Research
in Engineering and Technology, Volume 5, Issue 1,Pg.1-7,2018.

8. W. Xiuqing, W. Haiyan, and Y. Shifeng, ―Plant disease detection based on near-field acoustic
holography,‖ Transactions of the Chinese Society for Agricultural Machinery, vol. 2, article 43,
2014.View at: Google Scholar.

9. R. Sarkar, A. Pramanik,‖ Segmentation of Plant Disease Spots Using Automatic SRG Algorithm: A
Look Up Table Approach‖, 2015 International Conference on Advances in Computer Engineering
and Applications (ICACEA) IMS Engineering College, Ghaziabad, India.

71
10. K. Jagan Mohan, M. Balasubramanian, ―Detection and Recognition of Diseases from Paddy Plant
Leaf Images‖, International Journal of Computer Applications (0975 – 8887) Volume 144 – No.12,
2016.

11. [11] Sladojevic and Srdjan, et al,‖Deep neural networks based recognition of plant diseases
by leaf image classification.‖Computational intelligence and neuroscience 2016 (2016).

12. [12] Baquero, D., Molina, J., Gily, R., Bojacáy, C., Franco, H., & Gómez, A. F., An image retrieval
system for tomato disease assessment. Symposium on Image, Signal Processing and Artificial Vision
(STSIVA), XIX, pp. 1-5, 2014

13. [13] J. F. Molina, R. Gil, C. Bojacá, G. Díaz and H. Franco, "Color and size image dataset
normalization protocol for natural image classification: A case study in tomato crop pathologies,"
Symposium of Signals, Images and Artificial Vision - 2013: STSIVA - 2013, Bogota, pp. 1-5, 2013.

14. [14] Baquero, D., Molina, J., Gily, R., Bojacáy, C., Franco, H., & Gómez, A. F., An image retrieval
system for tomato disease assessment. Symposium on Image, Signal Processing and Artificial Vision
(STSIVA), XIX, pp. 1-5, 2014

15. [15] F. D. Smedt, I. Billauws, T. Goedeme, ―Neural networks and Low-Cost optical filters for
plant segmentation,‖ International Journal of Computer Systems and Industrial
Management Applications, vol. 3, pp. 804-811, 2011

72
73

You might also like