0% found this document useful (0 votes)
12 views

Report Final copy

This project report presents an innovative agricultural monitoring system that utilizes IoT technology and image processing to enhance crop health and irrigation management. The system employs various sensors for real-time data collection and integrates machine learning for early disease detection, aiming to improve agricultural productivity and sustainability. By automating control mechanisms and providing actionable insights, the project seeks to revolutionize traditional farming practices.

Uploaded by

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

Report Final copy

This project report presents an innovative agricultural monitoring system that utilizes IoT technology and image processing to enhance crop health and irrigation management. The system employs various sensors for real-time data collection and integrates machine learning for early disease detection, aiming to improve agricultural productivity and sustainability. By automating control mechanisms and providing actionable insights, the project seeks to revolutionize traditional farming practices.

Uploaded by

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

PLANT HEALTH MONITORING AND CROP

IRRIGATION SYSTEM USING IMAGE


PROCESSING AND IOT

A MINI PROJECT - II
REPORT

Submitted by

LOGITH. S (2102109)
PAVAN PRABHU. S. K (2102138)
RAGHUNATH. R (2102146)

in partial fulfillment for the award of

the degreeof

BACHELOR OF
ENGINEERING
in

ELECTRONICS AND COMMUNICATION


ENGINEERING

SRI RAMAKRISHNA ENGINEERING COLLEGE


[Educational Service: SNR Sons Charitable Trust]
[Autonomous Institution, Reaccredited by NAAC with ‘A+’
Grade] [Approved by AICTE and Permanently Affiliated to Anna
University, Chennai]
[ISO 9001:2015 Certified and All Eligible Programmes
Accredited by NBA]VATTAMALAIPALAYAM, N.G.G.O.
COLONY POST, COIMBATORE – 641 022

ANNA UNIVERSITY: CHENNAI - 600025

MAY - 2024
SRI RAMAKRISHNA ENGINEERING
COLLEGE
COIMBATORE – 641 022

BONAFIDE CERTIFICATE

20EC280 - MINI PROJECT II

Certified that this 20EC280 - Mini Project II Report “PLANT


HEALTH MONITORING AND CROP IRRIGATION
SYSTEM USING IMAGE PROCESSING AND IOT” is the
bonafide work of LOGITH. S (71812102109), PAVAN
PRABHU. S. K (71812102138), RAGHUNATH. R
(71812102146) who carried out the project under my supervision.

SIGNATURE SIGNATURE
Dr. A. VIJAY, Dr. M. JAGADEESWARI, M.E.,
Ph.D.,
Assistant Professor Professor
Supervisor Head of the Department
Department of ECE Department of ECE
Sri Ramakrishna Engineering College Sri Ramakrishna Engineering College
Coimbatore - 641022 Coimbatore - 641022

Submitted for the Mini Project Viva-Voce Presentation held on

INTERNAL EXAMINER EXTERNAL EXAMINER

ii
Acknowledgment

We put forth our hearts and soul to thank the almighty for
being with us all through this technical adventure.

We express our heartfelt thanks to our esteemed Managing


Trustee, Sri.D. Lakshmi Narayanaswamy, B.Tech., MBA., and
Joint Managing Trustee Thiru. R. Sundar, B.A, MBA., for their
invaluable support.

We thank our Principal, Dr. N.R. Alamelu, B.E. (Hons.), M.E.,


Ph.D., Sri Ramakrishna Engineering College, Coimbatore, for her
benevolent patronage in carrying out this project.

We express our sincere respect and gratitude to our Professor &


Head Dr. M .Jagadeeswari, M.E., Ph.D., Department, Electronics
and Communication Engineering for her continuous encouragement
and motivation throughout the project.

We are indebted to our Mini Project Coordinator Mr. M


Selvaganesh, Assistant Professor and our Supervisor, Dr. A. Vijay,
Associate Professor for providing encouragement and guiding us
throughout this project with enthusiasm and enabling us to complete it
within the stipulated time.

We extend our thanks to all the teaching, and non-teaching


faculty membersof our department and other departments, friends, and
family members for their support in carrying out the mini-project
successfully.
iii
ABSTRACT

This project endeavors to establish an agricultural monitoring

system leveraging low-cost sensors and IoT technology. Employing

a Node MCU microcontroller alongside a DHT11 sensor for

temperature and humidity monitoring, and a soil moisture sensor, the

system facilitates real-time data collection transmitted to the cloud

for analysis. In adverse conditions, an automatic control mechanism

activates a motor and fan to mitigate unfavorable effects.

Furthermore, advanced functionality integrates an ESP32-CAM

module for leaf disease detection using Convolutional Neural

Networks (CNN). Capturing images of plant leaves, the system

processes them for disease identification, aiding in timely

intervention. Overall, this integrated system offers real-time

environmental monitoring, automated control, and early disease

detection, thereby enhancing agricultural productivity and efficiency.

This innovative project not only enhances agricultural productivity

and efficiency but also contributes to sustainability and food

security. By integrating cutting-edge technology with traditional

farming practices, it empowers farmers with actionable insights for

optimized crop management, leading to improved yields and reduced

environmental impact.
iv
TABLE OF CONTENTS

CHAPTER TITLE PAGE


NO. NO.

ABSTRACT iv
LIST OF FIGURES vii
LIST OF ABBREVIATIONS vi
ii
1 INTRODUCTION 1
1.1 PROJECT OVERVIEW 2
1.2 ARTIFICIAL INTELLIGENCE 3
1.3 DEEP LEARNING 4
1.4 CONVOLUTIONAL NEURAL NETWORK 5
1.5 EMBEDDED SYSTEMS 6
2 LITERATURE SURVEY 2
2.1 INTRODUCTION 9
2.2 BACKGROUND 10
2.3 SUMMARY 14
3 METHODOLOGY AND WORKING PRINCIPLE 15
3.1 PROPOSED METHOD 15
3.2 BLOCK DIAGRAM 16

4 HARDWARE DESCRIPTION 17
4.1 DHT 11 17
4.2 NODEMCU 22
4.3 MOISTURE SENSOR 24

v
5 IMPACT AND UNIQUENESS OF THE 30
PRODUCT

6 EXPERIMENTAL RESULTS 37
6.1 LEAF DISEASE DETECTION 37
6.2 TREATMENT DATA 38
6.3 TEMPERATURE SENSING 39
6.4 HUMIDITY SENSING 40
6.5 MOISTURE SENSING 40
7 CONCLUSION AND FUTURE SCOPE 42
7.1 CONCLUSION 42
7.2 FUTURE SCOPE 43

REFERENCES 46
APPENDIX 47

vi
CHAPTER 1

INTRODUCTION

This innovative project aims to develop an advanced


agricultural monitoring system leveraging low-cost sensors and IoT
technology. By utilizing a Node MCU microcontroller alongside
specialized sensors for temperature, humidity, soil moisture, and leaf
disease detection, the system promises to revolutionize traditional
farming practices. Through real-time data collection, cloud-based
analysis, and automated control mechanisms, it seeks to enhance
environmental monitoring, mitigate adverse conditions, and enable
early intervention against potential crop diseases. With a focus on
bolstering agricultural productivity, sustainability, and efficiency, this
project stands poised to make significant strides in shaping the future
of farming and food security.
Integrating IoT devices, cloud computing, and machine
learning, this project advances agricultural monitoring. Using
NodeMCU and sensors, it collects real-time data on temperature,
humidity, soil moisture, and leaf health. The system autonomously
responds to unfavorable conditions, activating a motor and fan.
Integrated ESP32-CAM module aids in early disease detection
through leaf imaging and CNN analysis. Empowering farmers with
actionable insights, it optimizes resource use, mitigates risks, and
enhances productivity and sustainability. Future iterations may
explore additional sensors and collaborations to further refine and

1
adapt the system for diverse agricultural settings, fostering continuous
improvement in farm efficiency and profitability.

1.1 PROJECT OVERVIEW

This agricultural project focuses on three main objectives


to revolutionize farming practices and boost agricultural
productivity:
1. Environmental Monitoring: The system utilizes sensors to track
vital environmental factors like temperature, humidity, and soil
moisture levels in real-time. This data enables farmers to make
informed decisions about resource management and optimize crop
growth conditions.
2. Disease Detection: Using advanced imaging technology and
machine learning, the project implements a system for early
detection and prevention of plant diseases. By analyzing images of
plant leaves, it identifies common diseases, allowing farmers to take
timely action and protect crop health.
3. Automated Control: The project integrates automated
control mechanisms to respond to environmental changes. For
example, when sensors detect unfavorable conditions, such as high
temperatures or low moisture levels, the system can activate
irrigation or adjust ventilation to maintain optimal growing
conditions.

By combining these elements into an integrated system, the


project aims to empower farmers with tools and insights to enhance

2
agricultural practices, minimize risks, and improve overall farm
efficiency and sustainability.

Moreover, exploring the integration of drone technology for


aerial monitoring and crop surveillance could provide additional
insights into crop health and field conditions. Implementing smart
irrigation systems based on soil moisture data can optimize water
usage and enhance resource efficiency. These enhancements would
further enhance the effectiveness and sustainability of the
agricultural monitoring system.

1.2 ARTIFICIAL INTELLIGENCE

Fig 1.1 Artificial Intelligence

Artificial intelligence (AI) encompasses the replication of


human intelligence processes through machine systems, particularly
computer systems, enabling them to emulate human behavior. Its
applications span various fields, including Computer Vision, Natural
Language Processing, Robotics, and Speech Recognition. AI offers
several advantages, such as enhancing customer experience,
expediting time to market, facilitating the development of

3
sophisticated products, optimizing costs, boosting employee
productivity, and improving operational efficiency.

Machine Learning (ML) operates as a subset of AI, designed


to independently reason, engage in social interactions, acquire new
knowledge from provided data, and adapt and refine its capabilities
through experience. While training times may be longer for Deep
Learning (DL) methods compared to traditional ML methods, DL
often compensates with higher accuracy rates. Additionally, DL's
automated processes reduce the necessity for extensive domain
knowledge to achieve desired outcomes, contrasting with ML
approaches.

1.3 DEEP LEARNING

Deep Learning, a component of machine learning, takes cues


from the brain's structure and function, employing artificial neural
networks. It excels in hierarchically representing complex data, with
each level building upon simpler concepts. One such example is the
Convolutional Neural Network (CNN), commonly utilized for
disease diagnosis. Its advantages include its capacity to handle vast
datasets and solve end-to-end problems. However, Deep Learning
necessitates high-end computing resources and entails lengthier
training times, although it provides faster testing capabilities.

Deep Learning has some advantages such as:


 Works on Large amount of Dataset

4
 Heavily dependent on High-end Machine
 Solves the problem end to end
 Takes longer time to train
 Less time to test the data
Additionally, Deep Learning's adaptability extends to various
domains, including image recognition, natural language processing,
and autonomous driving. Its ability to extract intricate patterns from
data makes it invaluable for tasks requiring complex decision-making,
further solidifying its role in advancing technological innovation and
problem-solving.
1.4 CONVOLUTIONAL NEURAL NETWORK
In the realm of deep learning, Convolutional Neural Networks
(CNNs) represent a subclass of deep neural networks, primarily
tailored for visual data analysis. CNNs find extensive application in
tasks such as image and video recognition, recommendation systems,
image classification, segmentation, medical imaging, natural language
processing, brain-computer interfaces, and financial time series
analysis. The term "convolutional neural network" derives from its
utilization of convolution, a mathematical operation, indicating its
specialized nature compared to conventional neural networks
employing matrix multiplication in their layers.

Fig 1.2 Convolutional Neural Network

5
A Convolutional Neural Network (CNN) comprises an input
layer, hidden layers, and an output layer. In a feed-forward neural
network, intermediate layers are termed "hidden" as their inputs and
outputs are obscured by the activation function and final
convolution. Within a CNN, the hidden layers consist of
convolutional layers, typically incorporating operations like
multiplication or dot products. The activation function commonly
used is ReLU. Following the convolutional layers, additional
components may encompass pooling layers, fully connected layers,
and normalization layers.

Compared to its predecessors, Convolutional Neural Networks


(CNNs) possess the ability to automatically detect significant
features without human supervision, making them computationally
efficient. CNNs leverage local spatial coherence in input data,
particularly images, allowing for fewer weights through parameter
sharing. This convolutional process enables them to efficiently
extract relevant information, particularly suited for tasks like image
processing, classification, and segmentation. As a dominant method
in computer vision, CNNs are increasingly applied across various
domains, including radiology, due to their effectiveness in handling
auto-correlated data.

1.5 EMBEDDED SYSTEMS

Embedded systems serve as the cornerstone of contemporary


technology, harmoniously integrating hardware and software to

6
execute specific tasks. Despite their ubiquitous presence and
understated nature, these systems play a pivotal role in powering a
myriad of devices and applications integral to our everyday routines.
Embedded systems engineering lies at the core of this intricate
network, merging hardware design, software development, and real-
time computing to produce compact, effective, and tailored
computing solutions.

Fig 1.3 Embedded Systems

An embedded system is distinguished by its incorporation into


a broader system, typically tailored for specific functions or tasks. In
contrast to general-purpose computers, embedded systems are
specialized for executing predetermined functions, often with strict
performance and reliability criteria. They are utilized across various
sectors, including consumer electronics, automotive systems,
medical devices, and industrial automation.

The prevalence of embedded systems becomes evident


through our interactions with the diverse array of devices in our
environment. Whether it's the smart thermostat managing our home

7
climate or the sophisticated control systems in vehicles, these
systems function quietly, processing inputs, gathering data, and
carrying out tasks with exceptional efficiency.

Creating embedded systems requires a meticulous equilibrium


between hardware and software aspects. Hardware elements are
customized to align with the application's precise needs, prioritizing
factors like energy efficiency, compactness, and computational
speed. Meanwhile, software aspects frequently entail the utilization
of specialized operating systems or real-time operating systems
(RTOS) to guarantee accurate timing and swift responsiveness.

Embedded systems stand as essential components within


modern technology, seamlessly melding hardware and software to
fulfill specialized functions across various domains With ongoing
advancements in both hardware and software technologies, the
horizon holds promise for continued innovation, paving the way for
even more sophisticated embedded systems that further enhance our
interconnected world.

8
CHAPTER 2

LITERATURE SURVEY

This literature review delves into ten research papers


exploring advancements in agricultural technology. These papers
delve into topics such as precision farming techniques, automated
monitoring systems for environmental conditions, and the
integration of machine learning algorithms for crop disease
detection and management. By examining these studies, we aim to
gain insights into the latest innovations aimed at enhancing
agricultural productivity, sustainability, and efficiency.

2.1 INTRODUCTION

This project spearheads the development of an integrated


agricultural monitoring system, harnessing IoT, sensors, and
machine learning. It marks a transformative step in farming
practices, granting farmers real-time insights into environmental
conditions and crop health. Through seamless integration of
hardware and software, it pledges to elevate decision-making,
amplify productivity, and nurture sustainability in the agricultural
sector.

By diligently monitoring soil moisture levels and promptly


identifying crop diseases, this innovative system not only optimizes

9
resource allocation but also minimizes environmental footprint,
heralding a new era of precision agriculture.

2.2 BACKGROUND

1. Title: Leaf Disease Detection and Classification based on


Machine Learning
Authors: Sandeep Kumar, KMVV Prasad, A. Srilekha, T. Suman,B.
Pranav Rao, J. Naga Vamshi Krishna
Publication: 2020 International Conference on Smart Technologies
in Computing Electrical and Electronics (ICSTCEE)

Detecting diseases in plants is a critical aspect of ensuring


agricultural productivity and economic stability. Given the
prevalence of plant infections and their significant impact on crop
health, the task of identifying these diseases holds paramount
importance in the agricultural sector. However, the continuous
monitoring required to detect diseased leaves entails substantial
human effort and is time-consuming. To streamline this process,
there is a pressing need for automated strategies that can
effectively monitor plant health. By implementing programmed
algorithms for disease detection, the burden on human resources
can be alleviated, and the time required for monitoring
significantly reduced.

Automated disease detection systems offer a promising


solution to this challenge, as they can efficiently analyze plant

10
health parameters and identify signs of disease with greater
accuracy. By leveraging advanced algorithms, these systems can
distinguish between healthy and diseased leaves more precisely
than traditional methods. This not only enhances the effectiveness
of disease management efforts but also contributes to the overall
sustainability of agricultural practices. Thus, the development and
implementation of such automated detection systems represent a
significant step forward in ensuring the health and productivity of
crops, ultimately benefiting both farmers and the
broader agricultural industry, enhancing disease detection accuracy
significantly.

2. Title: Leaf Disease Detection Using Deep Learning


Authors: Teenu Sahasra M, Sai Kumari S, Sai Meghana S,P. Rama
Devi,
Publication: 2021 Second International Conference on Electronics
and Sustainable Communication Systems (ICESC)

The agricultural sector heavily influences overall


productivity, with plant diseases posing common challenges.
Detecting these diseases has become increasingly feasible,
prompting heightened attention in surveilling expansive crop
fields. Farmers face significant hurdles in navigating various
disease management principles, underscoring the need for efficient
detection methods. Employing mechanized techniques for disease
detection streamlines surveillance efforts, enhancing plant health
and overall production quality. Early detection of symptoms on
plant leaves is crucial, and this paper explores algorithms for
11
image segmentation and automated disease classification methods
to aid in disease detection.

3. Title: Leaf Disease Detection Using Machine Learning Algorithm


Authors: T. Priyaradhikadevi, R. Mohan, T. Ragupathi, S.
Prasanna,
K. Madhan, R. Ananthi
Publication: 2023 Eighth International Conference on Science
Technology Engineering and Mathematics (ICONSTEM)

Agriculture holds immense significance in the development of


countries like India, particularly in rural livelihoods where it
contributes around 58% of the total. However, plant diseases pose a
significant threat to crop production, impacting both quality and
productivity and potentially leading to food supply crises. Therefore,
accurately classifying plant diseases is crucial for the agricultural
sector. This system employs image processing and machine learning
algorithms for early detection and classification of plant leaf diseases.
Utilizing the Plant Village dataset, which includes various plant leaves
such as apple, corn, grape, and tomato categorized into healthy and
diseased states, texture and shape features are extracted and classified
using decision tree and Gradient Boosting algorithms. The system's
performance is evaluated based on accuracy parameters, utilizing
innovative technology for accurate classification.

12
4. Title: Plant Leaf Disease Detection using Machine Learning
Authors: Kethsy Prabavathy, Mokara Bharath, Kambam
Sanjayratnam,
N. Sri Sai Rahul Reddy, M. Sasidhar Reddy

Publication: 2023 2nd International Conference on Applied


Artificial Intelligence and Computing (ICAAIC)

Detecting diseases in plant leaves is essential for modern


agriculture to ensure optimal crop yield and quality. This study presents
a novel approach to disease detection using machine learning
techniques. The methodology comprises three main stages, involving
classification with five models: KNN, SVM, Decision Trees, Random
Forest, and CNN. Images are pre-processed to remove unwanted
features and resized to a standardized 256x256 pixels. A pre-trained
CNN model extracts relevant features, which are then used to train the
classification models. Model performance is evaluated using various
metrics to assess effectiveness and accuracy. This methodology aims to
offer a dependable diagnosis of plant diseases, enabling timely
intervention for healthy crop growth. Experimental results demonstrate
high accuracy, low complexity, and ease of identification, indicating
the effectiveness of the proposed system in early disease detection and
diagnosis for improved crop yield.

13
2.3 SUMMARY

The literature reviews examined various aspects of


agricultural technology, highlighting the critical role of advanced
systems in enhancing productivity and sustainability. From disease
detection in plants to precision farming techniques, these studies
underscored the importance of leveraging technology to address
challenges in agriculture. Automated monitoring systems and
machine learning algorithms offer promising solutions for early
disease detection and efficient resource management, ultimately
contributing to improved crop yields and farm profitability. By
integrating IoT, sensors, and image processing techniques, these
systems empower farmers with real-time insights into
environmental conditions and crop health, enabling timely
interventions and informed decision-making. The findings
emphasize the transformative potential of technology in
revolutionizing agricultural practices and ensuring food security
for a growing population.

14
CHAPTER 3

METHODOLOGY AND WORKING PRINCIPLE

Our aim is to propose a smart irrigation system that


integrates moisture detection, and leaf disease detection.

3.1 PROPOSED METHOD

The proposed system aims to overcome the shortcomings of


current methods by integrating cutting-edge technologies such as IoT
devices, cloud computing, and machine learning algorithms. Through
the deployment of sensors like the DHT11 for temperature and
humidity monitoring, a moisture sensor for soil moisture measurement,
and an ESP32-CAM module for leaf disease detection, real-time data
collection and analysis are enabled. This data is transmitted to a cloud-
based platform for storage, analysis, and visualization, granting farmers
access to actionable insights from anywhere, at any time. Moreover, an
automated control mechanism is incorporated to respond to adverse
conditions by activating a motor and fan for temperature and humidity
regulation. In essence, the proposed system offers an improved,
dependable, and user-friendly solution for agricultural monitoring and
management, empowering farmers to enhance crop yields, reduce
losses, and promote sustainability

15
3.2 BLOCK DIAGRAM

Fig 3.1 Block Diagram

The block diagram of the project illustrates the interconnected


components and their functions. At the core of the system is the
NodeMCU, serving as the central processing unit and communication hub.
Connected to the NodeMCU are the humidity sensor, moisture sensor, and
temperature sensor. The humidity sensor measures the moisture content in
the air. Meanwhile, the moisture sensor detects soil moisture levels. Lastly,
the temperature sensor captures ambient temperature readings, aiding in
climate monitoring. Together, these sensors gather vital environmental
data, which the NodeMCU processes and analyzes. Through wireless
communication protocols, such as Wi-Fi or Bluetooth, the NodeMCU can
transmit this data to a central monitoring system or user interface for
further analysis and action. This block diagram encapsulates
comprehensive environmental monitoring and control.

16
CHAPTER 4
HARDWARE DESCRIPTION
4.1 DHT 11

Embedded within the DHT11, there exists both a humidity sensing


component and a thermistor. The humidity sensing component
comprises two electrodes separated by a moisture-holding substrate. As
water vapor is absorbed by the substrate, ions are released, leading to
an increase in conductivity between the electrodes. Consequently, the
resistance between the electrodes changes proportionally to the relative
humidity levels. Higher relative humidity results in decreased
resistance, whereas lower relative humidity leads to increased
resistance, facilitating accurate humidity measurement.

Fig 4.1 DHT 11

17
The DHT11 also integrates an NTC/thermistor for temperature
measurement. A thermistor, characterized as a thermal resistor, exhibits
a significant change in resistance in response to temperature variations.
Specifically, the term "NTC" denotes "Negative Temperature
Coefficient," indicating that the resistance decreases as the temperature
rises.

Fig 4.2 NTC Thermistor

Situated on the opposite side, there is a compact PCB housing an 8-bit


SOIC-14 packaged IC. This integrated circuit is responsible for
measuring and processing the analog signal, utilizing stored
calibration coefficients, performing analog-to-digital conversion, and
generating a digital output containing temperature and humidity data.

Fig 4.3 DHT 11 Top View

18
DHT 11 SENSOR OVERVIEW
The core component of the module is the DHT11 digital
Temperature and humidity sensor, produced by AOSONG. The
DHT11 sensor is capable of measuring temperatures ranging from 0°C
to 50°C with an accuracy of ±2.0°C, and humidity levels from 20% to
80% with an accuracy of 5%.

It's important to note that the DHT11 operates at a sampling rate


of 1Hz, allowing for new data retrieval every second. Additionally,
the module is equipped with all necessary supporting circuitry,
eliminating the need for additional components and ensuring seamless
functionality out of the box.

19
Typically, DHT11 sensors necessitate an external pull-up resistor
of 10KΩ between VCC and the Out pin to facilitate effective
communication with the Arduino. However, the module includes a
built-in pull-up resistor, eliminating the need for additional
installation. Additionally, the module features a decoupling capacitor
designed to filter noise present on the power supply.

Fig 4.4 DHT 11 Pin Configuration

20
The VCC pin serves as the power supply for the sensor, with a
recommended voltage of 5V, although it can operate within a range of
3.3 V to 5.5V. When using a 5V power supply, the sensor can be
positioned up to 20 meters away. However, with a 3.3V supply voltage,
the cable length should not exceed 1 meter to avoid voltage drop errors.
The Out pin facilitates communication between the sensor and the
Arduino, while the GND pin should be connected to the Arduino's ground.
When wiring the DHT11 module to the Arduino, connect the VCC pin to
the Arduino's 5V output, the GND pin to ground, and the Out pin to digital
pin #8

Fig 4.5 Circuit Diagram

21
4.2 NODEMCU (ESP8266)

Fig 4.6 NodeMCU

The Atmel AVR® core integrates a diverse instruction set with


32 general-purpose working registers. These registers directly interface
with the Arithmetic Logic Unit (ALU), enabling simultaneous access to
two independent registers in a single clock cycle. This architecture
enhances code efficiency while delivering throughputs up to ten times
faster than traditional CISC microcontrollers. The ESP8266/P offers a
comprehensive feature set, including 32Kbytes of In-System
Programmable Flash with Read-While-Write capabilities, 1Kbytes of
EEPROM, 2Kbytes of SRAM, 23 general-purpose I/O lines, and a
Real-Time Counter (RTC).
Additionally, it features three flexible Timer/Counters with
compare modes and PWM, 1 serial programmable USART, and a byte-
oriented 2-wire Serial Interface (I2C). Other functionalities include a 6-
channel 10-bit ADC (8 channels in TQFP and QFN/MLF packages), a
programmable Watchdog Timer with internal Oscillator, an SPI serial
port, and six software-selectable power-saving modes, enabling rapid
startup and minimal power consumption. The QTouch® library
22
facilitates the integration of capacitive touch buttons, sliders, and
wheels functionality into AVR microcontrollers, utilizing patented
charge-transfer signal acquisition for robust sensing. The device is
crafted using Atmel’s high-density non-volatile memory technology,
with On-chip ISP Flash enabling In-System reprogramming through
various interfaces, enhancing efficiency for users.

PIN DIAGRAM OF ESP8266

The ESP8266/P is accompanied by a comprehensive set of


program and system development tools, comprising C Compilers,
Macro Assemblers, and Program Debugger/Simulators, as well as In-
Circuit Emulators and Evaluation kits. Additionally, a pin diagram of
the ESP8266 is provided below, for efficient understanding of the
controller.

Fig 4.7 NodeMCU Pin


Configuration

23
FEATURES OF ESP8266:

Some features of ESP8266 include:


1. Integrated Wi-Fi connectivity.
2. Low power consumption.
3. Built-in TCP/IP protocol stack.
4. Support for a variety of network protocols.
5. On-board flash memory for program storage.
6. GPIO pins for interfacing with external devices.
7. Real-time operating system (RTOS) for multitasking capabilities.
8. Support for firmware updates over-the-air (OTA).
9. Low cost and compact size.
10. Easy integration with Arduino IDE for programming.

4.3 MOISTURE SENSOR

The functionality of the soil moisture sensor revolves around a pair


of probes engineered to gauge the volumetric water content within soil
samples. By facilitating the passage of current, these probes enable the
sensor to measure resistance values, serving as a proxy for moisture
levels. Elevated moisture content correlates with increased soil
conductivity, translating to decreased resistance readings. Conversely, in
drier conditions, soil conductivity diminishes, leading to heightened
resistance values and lower moisture readings. This intricate interplay
between conductivity and resistance forms the basis for accurate moisture
assessment in soil samples.

24
Fig 4.8 Humidity Sensor

To utilize the sensor in analog mode, we'll interface with its analog
output. The FC-28 soil moisture sensor outputs values ranging from 0 to
1023. Since moisture levels are measured as a percentage, we'll map these
values to the range of 0 to 100. Subsequently, we'll display these mapped
values on the serial monitor for monitoring and analysis.

POWER SUPPLY
TRANSFORMER

A center-tapped transformer, also known as a two-phase three-wire


transformer, is commonly employed in rectifier circuits. When digital
projects necessitate interaction with AC mains, a transformer is utilized to
step-down the voltage (typically to 24V or 12V) before converting it to
DC through a rectifier circuit. Compared to a bridge rectifier, a center-
tapped transformer exhibits twice the peak inverse voltage, making it a

25
preferred choice for full-wave rectifier circuits.

The functioning and principles of a center-tapped transformer


closely resemble those of a standard secondary transformer. Induced
primary voltage (I1 and I3) generates in the primary coil, transferring to
the secondary coil through magnetic induction. Within the secondary coil
of a center-tapped transformer, an additional wire (T2) positioned at its
center maintains a consistently zero voltage. By combining this zero
potential wire (T2) with either T1 or T2, a voltage of 12V AC is obtained.
Ignoring this wire and considering the voltage across T1 and T2 yields a
voltage of 24V AC. This unique attribute facilitates the operation of a full-
wave rectifier.

Fig 4.9 Transformer

RECTIFIER CIRCUIT:

In the domain of rectifier circuits, the conversion of sinusoidal AC


voltage into pulsating DC is a fundamental process. However, the
resultant pulsating DC voltage contains unwanted AC elements,

26
including supply frequency components and harmonics known as ripples.
These ripples are most pronounced in single-phase half-wave rectifiers,
diminishing in single-phase full-wave rectifiers, and further attenuating in
3-phase rectifier circuits. Such supplies prove inadequate for driving
complex electronic circuits, necessitating a smoother and more stable DC
voltage output.

To achieve this, the rectifier output must pass through a


meticulously designed filter circuit, which excises AC components while
permitting only the DC component to pass. This filter, composed of
capacitors, resistors, and inductors, functions as a conduit for a steady DC
voltage output, thereby enhancing the overall operational efficiency of the
circuit. This process ensures that the output is stable, reliable, and suitable
for a wide range of electronic applications.

The inductor is employed to selectively permit DC components


to pass while impeding AC signals, leveraging its inherent property.
Conversely, capacitors are utilized to block DC and facilitate the passage
of AC signals. Various combinations of these components and their
functionalities are elaborated below. In a series inductor filter, depicted in
the circuit diagram of a full-wave rectifier, the inductor (L) is positioned
in series between the rectifier circuit and the load. This arrangement
capitalizes on the inductor's ability to resist changes in current flow,
thereby exhibiting high impedance to ripples while presenting minimal
impedance to the desired DC components.

Consequently, the ripple components are effectively eradicated.


As the rectifier output current surpasses a specific threshold, energy
accumulates in the form of a magnetic field within the inductor,
subsequently releasing this stored energy when the output current dips
27
below the average level. Therefore, abrupt fluctuations in current within
the circuit are mitigated by integrating the inductor in series between the
rectifier and the load. The accompanying waveform illustrates the
utilization of the inductor in the circuit.

In the circuit, for the zero-frequency DC voltage, the choke


resistance Ri connected in series with the load resistance RL forms a
voltage divider circuit, determining the DC voltage across the load as Vdc
= RL/(Ri + RL). This Vdc represents the output from a full-wave rectifier.
Considering that the value of Ri is significantly smaller compared to RL,
the impact of higher harmonic voltages can be disregarded, thanks to the
enhanced filtering of the higher harmonic components. This is attributed
to the fact that as the frequency increases, the reactance of the inductor
also rises. Notably, a reduction in the load resistance or an increase in the
load current results in a decrease in the ripple amount in the circuit.

Hence, the series inductor filter finds primary application in


scenarios characterized by high load current or minimal load resistance.
However, a basic series inductor filter alone may not suffice. Opting for
an LC filter, comprising both a shunt capacitor (C) and a series inductor
(L), proves more effective. Shunt Capacitor Filter, as the name implies,
involves the use of a high-value capacitor positioned across the load
impedance to serve as the filter.

When positioned across a rectifier, the capacitor undergoes


charging and stores energy throughout the conduction phase. During non-
conduction periods of the rectifier, this stored energy is discharged back
to the load. Consequently, this energy storage and release mechanism
prolongs the duration of current flow through the load resistor, resulting in
a substantial reduction in ripples. As a result, for ripple components with a
28
frequency of 'f' megahertz, the capacitor 'C' exhibits minimal impedance.

Expressed as: Shunt Capacitor Impedance = 1/(2 * f * C), this


impedance allows only the DC components of the input signal, along with
a few residual ripple components, to pass through the load resistance,
RLoad. Meanwhile, the substantial ripple current components are diverted
through the capacitor, C. Now, let's delve into the operation of both Half-
wave and Full-wave rectifiers with Capacitor filters, analyzing their
filtered waveform, ripple factor, advantages, and disadvantages in depth.

29
CHAPTER 5
IMPACT AND UNIQUENESS OF THE PRODUCT

IMPACT OF THE PRODUCT


This project, focused on developing an advanced agricultural
monitoring system, carries significant implications for the agricultural
sector and beyond. Firstly, by integrating IoT devices, cloud
computing, and machine learning algorithms, the system revolutionizes
traditional farming practices, enhancing productivity, efficiency, and
sustainability. With real-time data collection and analysis capabilities,
farmers gain invaluable insights into crop health, soil conditions, and
environmental factors, enabling timely interventions to optimize yields
and minimize losses.

Moreover, the system's ability to detect and diagnose plant


diseases early on is a game-changer for crop management. By
leveraging image processing and machine learning techniques, the
system can swiftly identify signs of disease or stress in plants, allowing
farmers to take proactive measures such as targeted pesticide
application or crop rotation. This not only improves crop health but also
reduces the reliance on chemical inputs, promoting eco-friendly
farming practices.

Furthermore, the implementation of automated control


mechanisms, such as regulating temperature and humidity, mitigates
the risk of environmental fluctuations affecting crop growth. By
maintaining optimal growing conditions, the system ensures consistent
yields and quality, contributing to food security and stability in
agricultural supply chains.
30
Beyond agriculture, the technologies and methodologies
employed

in this project have broader implications for environmental monitoring,


resource management, and sustainable development. By harnessing the
power of IoT, cloud computing, and machine learning, similar systems
could be deployed in various domains to address complex challenges
and drive positive change. Overall, this project's impact extends far
beyond the agricultural sector, offering transformative solutions for a
more sustainable future.

Economic Empowerment: By improving crop yields and quality,


the agricultural monitoring system can enhance the livelihoods of
farmers, especially smallholders who rely on agriculture for income.
Increased productivity and reduced losses translate to higher incomes
and improved economic stability for farming communities.

Food Safety and Quality: Through early detection of diseases


and pests, the system contributes to ensuring food safety and quality.
By identifying and addressing potential threats to crop health, it helps
maintain high standards for agricultural products, meeting consumer
demands for safe and nutritious food.

Resource Efficiency: By providing real-time insights into soil


moisture, temperature, and other environmental factors, the system
promotes resource efficiency in agriculture. Farmers can optimize water
usage, minimize fertilizer and pesticide application, and reduce waste,
leading to more sustainable farming practices.

31
Climate Resilience: In the face of climate change and
increasingly unpredictable weather patterns, the adaptive capabilities of
the monitoring

system are invaluable. Farmers can better anticipate and respond to


climate-related challenges, such as droughts, floods, or extreme
temperatures, enhancing resilience and mitigating risks to agricultural
production.

Data-driven Decision Making: The system's data analytics


capabilities enable evidence-based decision-making at both the farm
and policy levels. By aggregating and analyzing large volumes of
agricultural data, stakeholders can identify trends, patterns, and best
practices, informing strategic interventions and policy formulation for
the entire agricultural sector.
By highlighting these additional aspects, the impact of the
agricultural monitoring system can be more comprehensively
understood, emphasizing its role in driving positive change across
multiple dimensions of society and the environment.

UNIQUENESS OF THE PRODUCT

The uniqueness of this agricultural monitoring system lies in its


integration of cutting-edge technology with the specific needs and
challenges of the agricultural sector. Here's a detailed discussion on its
uniqueness:

32
Tailored Solutions: Unlike generic monitoring systems, this
product is specifically designed for the agricultural context. It
addresses the unique requirements of farmers, such as soil moisture
management, pest detection, and crop health monitoring, providing
tailored solutions that directly contribute to improved agricultural
outcomes.

Advanced Sensor Technology: The system utilizes advanced


sensor technology to collect real-time data on various environmental
parameters critical to crop growth. These sensors are designed to be
robust and accurate, providing reliable measurements even in harsh
agricultural conditions, thus ensuring the accuracy and effectiveness of
the monitoring process.

IoT Integration: One of the key features that set this product
apart is its integration with Internet of Things (IoT) technology. By
connecting sensors, data processing units, and communication devices
through IoT networks, the system enables seamless data collection,
transmission, and analysis, empowering farmers with actionable
insights in real-time.

Data Analytics Capabilities: Another unique aspect of this


product is its sophisticated data analytics capabilities. The system
employs advanced algorithms and machine learning techniques to
analyze the collected data and generate valuable insights. This includes
predictive analytics for early detection of crop diseases, optimization of
irrigation schedules, and personalized recommendations for pest
management strategies.

33
User-friendly Interface: Despite its technological complexity,
the system boasts a user-friendly interface that is accessible to farmers
of all levels of technical proficiency. The interface is intuitive and easy
to navigate, allowing farmers to interact with the system effortlessly
and make informed decisions based on the insights provided.

Scalability and Flexibility: The modular design of the system


allows for scalability and flexibility, accommodating farms of various
sizes and configurations. Whether it's a small-scale family farm or a
large commercial operation, the system can be customized and scaled
up or down to meet the specific needs and budget constraints of
different users.

Support Services: In addition to the product itself, the company


provides comprehensive support services to users, including installation
assistance, training programs, and ongoing technical support. This
ensures that farmers are equipped with the knowledge and resources
needed to maximize the benefits of the system and overcome any
challenges they may encounter.

Overall, the unique combination of tailored solutions, advanced


technology, user-friendly design, and comprehensive support services
makes this agricultural monitoring system stand out as a game-changer
in the industry, offering unparalleled value to farmers and stakeholders
across the agricultural value chain.

34
SUMMARY

This agricultural monitoring system represents a pioneering


solution that integrates cutting-edge technology with the specific needs
of the agricultural sector. It offers a comprehensive suite of features
tailored to address the unique challenges faced by farmers, including
soil moisture management, pest detection, and crop health monitoring.
The system leverages advanced sensor technology to collect real-time
data on key environmental parameters critical to crop growth, ensuring
accuracy and reliability even in harsh agricultural conditions. Through
its integration with Internet of Things (IoT) technology, the system
enables seamless data collection, transmission, and analysis,
empowering farmers with actionable insights in real time.

One of the standout features of this system is its sophisticated


data analytics capabilities, which utilize advanced algorithms and
machine learning techniques to analyze collected data and generate
valuable insights. These insights include predictive analytics for early
disease detection, optimization of irrigation schedules, and personalized
recommendations for pest management strategies. Despite its
technological complexity, the system boasts a user-friendly interface
that is accessible to farmers of all levels of technical proficiency,
allowing for effortless interaction and decision-making based on the
provided insights.

The modular design of the system allows for scalability and


flexibility, accommodating farms of various sizes and configurations.

35
Additionally, comprehensive support services are provided to
users, including installation assistance, training programs, and ongoing
technical support. Overall, this agricultural monitoring system stands
out as a game-changer in the industry, offering unparalleled value to
farmers and stakeholders across the agricultural value chain. Its unique
combination of tailored solutions, advanced technology, user-friendly
design, and it is a transformative tool for optimizing agricultural
productivity, sustainability, and profitability.

36
CHAPTER 6

EXPERIMENTAL RESULTS

Our project aimed to create an integrated agricultural monitoring


system designed to enhance crop management and productivity. The
system encompasses a range of sensors and technologies tailored to
monitor crucial parameters such as soil moisture, temperature, and
humidity. Additionally, it includes features for pest and disease
detection, as well as remote monitoring and control capabilities.
Throughout the experimental phase, we conducted rigorous testing to
evaluate the performance of each component and assess their
effectiveness in providing accurate and timely data for informed
decision-making in farming practices.

6.1 LEAF DISEASE DETECTION

To identify leaf diseases, we utilized a convolutional neural


network (CNN). Through experimentation, we trained the CNN model
using a dataset comprising images of healthy and diseased plant leaves.
The model effectively distinguished between healthy and infected leaves,
displaying accurate results when presented with new leaf images. This
capability underscores the system's efficacy in detecting and diagnosing
plant diseases, aiding farmers in timely intervention and crop
management decisions.

37
Fig. 7.1 Healthy Leaf

6.2 TREATMENT DATA

The leaf disease detection system represents a groundbreaking


advancement in agricultural technology, offering a multifaceted
approach to combating plant illnesses. Through sophisticated algorithms
and machine learning models, the system swiftly identifies various
diseases affecting plant foliage. Once a disease is detected, the system
leverages a vast database of treatment protocols and agricultural best
practices to provide tailored recommendations for mitigating the ailment.
These recommendations encompass a spectrum of interventions,
including pesticide applications, nutrient adjustments, and environmental
modifications. By delivering precise and timely guidance, the system
empowers farmers to take proactive measures in safeguarding their
crops, thereby ensuring optimal yields and promoting agricultural
sustainability.

38
Fig. 7.2 Diseased Leaf

6.3 TEMPERATURE SENSING

In the realm of agricultural innovation, temperature sensing


emerges as a pivotal aspect in ensuring optimal plant health and
growth. Our project integrates advanced temperature sensing
technology to monitor the ambient temperature surrounding plants with
precision and accuracy. Through strategically placed sensors, we
capture real-time temperature data, which is then transmitted to a
central monitoring system for analysis and interpretation. This data
provides invaluable insights into the thermal conditions experienced by
plants, enabling farmers to make informed decisions regarding
irrigation, shading, and other cultivation practices. By harnessing the
power of temperature sensing, our project equips farmers with the
knowledge needed to optimize growing conditions, mitigate
temperature-related stressors, and ultimately enhance crop quality.
39
6.4 HUMIDITY SENSING

In the agricultural landscape, humidity sensing plays a vital role


in maintaining an optimal environment for plant growth and
development. Our project integrates advanced humidity sensing
technology to monitor and assess the humidity levels in the vicinity of
plants with precision and reliability. Through strategically placed
sensors, real-time humidity data is collected and transmitted to a central
monitoring system for analysis. This data provides valuable insights
into the moisture levels surrounding plants, enabling farmers to adjust
irrigation schedules, ventilation, and other environmental controls as
needed. By leveraging humidity sensing technology, our project
empowers farmers to create conditions conducive to healthy plant
growth, ultimately leading to improved crop yields and quality.

6.5 MOISTURE SENSING

This project introduces a sophisticated water management


system designed to respond dynamically to soil moisture levels.
Utilizing a soil moisture sensor, the system continuously monitors the
moisture content in the soil surrounding the plants. When the sensor
detects low moisture levels, indicating dry soil conditions, it activates a
motor to initiate water flow for irrigation. Conversely, when the sensor
detects high moisture levels, signaling adequately moist soil, the motor
is deactivated to halt water flow.

This intelligent control mechanism ensures precise water


delivery, optimizing plant hydration and resource utilization. Through
40
rigorous simulation, we validate the reliability and efficiency of this
automated water management system, demonstrating its capability to
maintain optimal soil moisture levels for sust9ained plant growth.

Fig 7.3 Temperature,


Humidity and Moisture
Output

41
CHAPTER 7
CONCLUSION AND FUTURE SCOPE

7.1 CONCLUSION

In conclusion, this agricultural monitoring system represents a


significant advancement in the field of precision agriculture, offering
farmers a powerful tool to enhance crop management practices and
optimize yields. Through the integration of advanced sensor
technology, IoT connectivity, and sophisticated data analytics, the
system provides real-time insights into key environmental factors
affecting crop growth, such as soil moisture levels, pest infestations,
and disease outbreaks. By leveraging machine learning algorithms, the
system can predict and prevent potential issues before they impact crop
health, enabling proactive decision-making and resource allocation.

Furthermore, the user-friendly interface and comprehensive


support services ensure that farmers can easily adopt and integrate this
technology into their existing practices, regardless of their technical
expertise. The modular design of the system allows for scalability and
customization to meet the unique needs of individual farms, while
ongoing technical support and training programs ensure that users can
maximize the benefits of the system over time.

Overall, this agricultural monitoring system not only improves


farm productivity and profitability but also promotes sustainability by
optimizing resource usage and minimizing environmental impacts. As
the agricultural industry continues to evolve, innovative solutions like
this will play a crucial role in meeting the challenges of feeding the
population while preserving natural resources for future generations.
42
7.2 FUTURE SCOPE

Looking ahead, there are several avenues for future development


and enhancement of this agricultural monitoring system:

Integration of Additional Sensors: Expanding the range of


sensors to include additional parameters such as air quality, weather
conditions, and nutrient levels can provide a more comprehensive view
of the farming environment. This will enable farmers to make more
informed decisions and further optimize their crop management
practices.

Enhanced Data Analytics: Incorporating advanced data analytics


techniques, such as predictive modeling and machine learning, can help
to identify patterns and trends in the data collected by the system. This
will enable more accurate predictions of crop yields, pest outbreaks,
and disease occurrences, allowing farmers to take proactive measures to
mitigate risks and maximize productivity.

Remote Monitoring and Control: Implementing remote


monitoring and control capabilities will enable farmers to access and
manage the system from anywhere, using mobile devices or web-based
interfaces. This will provide greater flexibility and convenience,
particularly for farmers managing large or geographically dispersed
farms.

Integration with Precision Agriculture Technologies: Integrating


the monitoring system with other precision agriculture technologies,
such as GPS-guided equipment and automated irrigation systems, can
43
further optimize farming operations. This will enable precise and
targeted application of resources, minimizing waste and maximizing
efficiency.

Collaborative Platforms and Knowledge Sharing: Developing


collaborative platforms and knowledge-sharing networks can facilitate
information exchange and collaboration among farmers, researchers,
and agricultural experts. This will enable the collective pooling of
insights, best practices, and solutions to common challenges, fostering
innovation and driving continuous improvement in agricultural
practices.

Scalability and Adaptability: Designing the system to be scalable


and adaptable to different farming contexts and scales will ensure its
relevance and effectiveness across a wide range of agricultural settings.
This includes considerations such as modularity, interoperability, and
compatibility with existing infrastructure and technologies.

By pursuing these avenues for future development, this


agricultural monitoring system can continue to evolve and provide
valuable support to farmers, enabling them to overcome challenges,
improve productivity, and achieve sustainable agricultural practices in
the years to come.

44
Fig 7.1 Project Accuracy

The project's accuracy is paramount in ensuring its effectiveness in


real-world applications. Through meticulous calibration and testing
procedures, we strive to achieve precise measurements and reliable
performance. Calibration involves fine-tuning sensors and actuators to
accurately detect and respond to environmental variables such as
temperature, humidity, and soil moisture. Rigorous testing protocols
validate the system's accuracy under various operating conditions,
ensuring consistent and dependable functionality. Additionally, ongoing
monitoring and feedback mechanisms enable continual refinement and
optimization of the system's accuracy over time. By prioritizing accuracy
throughout the development process, we aim to deliver a robust and
dependable solution for agricultural monitoring and management.

45
REFERENCES

1. Sandeep Kumar, KMVV Prasad, A. Srilekha, T. Suman,B. Pranav Rao,


J. Naga Vamshi Krishna, Leaf Disease Detection and Classification
based on Machine Learning, 2020 International Conference on Smart
Technologies in Computing Electrical and Electronics (ICSTCEE)

2. Teenu Sahasra M, Sai Kumari S, Sai Meghana S,P. Rama Devi, Leaf
Disease Detection Using Deep Learning, 2021 Second International
Conference on Electronics and Sustainable Communication Systems
(ICESC)

3. T. Priyaradhikadevi, R. Mohan, T. Ragupathi, S. Prasanna, K. Madhan,


R. Ananthi, Leaf Disease Detection Using Machine Learning
Algorithm, 2023 Eighth International Conference on Science
Technology Engineering and Mathematics (ICONSTEM)

4. Kethsy Prabavathy, Mokara Bharath, Kambam Sanjayratnam, N. Sri Sai


Rahul Reddy, M. Sasidhar Reddy, Plant Leaf Disease Detection using
Machine Learning, 2023 2nd International Conference on Applied
Artificial Intelligence and Computing (ICAAIC)

46
APPENDIX

import tkinter as tk
from tkinter import filedialog
import cv2
import os
import numpy as np
from keras.models import load_model
import requests
from PIL import Image, ImageTk
import threading
#import serial # Add this import for serial communication

model = load_model('CNN.model')

data_dir = "data"
class_names = os.listdir(data_dir)

# Global variable to indicate when to perform analysis


perform_analysis = False

# Serial communication setup


# Change 'COM5' to the correct port for your NodeMCU

def capture_video():
global perform_analysis
esp32cam_url = "http://192.168.137.37/capture"

47
while True:
# Continuously capture frames from the ESP32-CAM
response = requests.get(esp32cam_url, stream=True)
if response.status_code == 200:
# Decode the image bytes
img_array = np.asarray(bytearray(response.content), dtype=np.uint8)
frame = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

# Display the live video


img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
img = ImageTk.PhotoImage(img)
video_label.config(image=img)
video_label.image = img

# Check if analysis is requested


if perform_analysis:
perform_analysis = False

# Perform analysis on the captured frame


analyze_frame(frame)
else:
print("Failed to capture video from ESP32-CAM")

def analyze_frame(frame):
# Resize the frame for model input
resized_frame = cv2.resize(frame, (100, 100))
resized_frame = np.expand_dims(resized_frame, axis=0)

48
resized_frame = resized_frame / 255.0 # Normalize the image

prediction = model.predict(resized_frame)
predicted_class = np.argmax(prediction)

# Send the value through the serial cable to NodeMCU

if predicted_class == 0:
sol = "Use drip irrigation and avoid overhead irrigation if possible. Water
plants in the morning to allow water on plants to evaporate quickly"
elif predicted_class == 1:
sol = "Healthy"
elif predicted_class == 2:
sol = "Remove and destroy all affected plant parts. For plants growing
under cover, increase ventilation and, if possible, the space between
plants."
elif predicted_class == 3:
sol = "Fungicides are very effective for control of Septoria leaf spot, and
applications are often necessary to supplement the control strategies
previously outlined."
elif predicted_class == 4:
sol = "Products containing chlorothalonil, mancozeb, and copper
oxychloride have been shown to provide good control of target spot in
research."

result_label.config(text=f"Predicted Class: {predicted_class}")


solution_label.config(text=f"Solution: {sol}")

49
def on_q_pressed(event):
global perform_analysis
perform_analysis = True

# Create the Tkinter window


root = tk.Tk()
root.title("Live Video Analysis")

# Label to display the live video


video_label = tk.Label(root)
video_label.pack()

# Label to display the analysis result


result_label = tk.Label(root, text="")
result_label.pack()

solution_label = tk.Label(root, text="")


solution_label.pack()

# Bind the 'q' key to the on_q_pressed function


root.bind('q', on_q_pressed)

# Create a thread for capturing video


video_thread = threading.Thread(target=capture_video)
video_thread.start()

# Start the Tkinter main loop


root.mainloop()

50

You might also like