You are on page 1of 36

AIRep: AI and IoT based Animal Recognition and Repelling

System for Smart Farming


Abstract
Agriculture automation has been on the rise leveraging, among others, Deep Neural Networks

(DNN) and IoT for the development and deployment of many controlling, monitoring and

tracking applications at a fine-grained level. In this rapidly evolving scenario, managing the

relationship with the elements external to the agriculture ecosystem, such as wildlife, is a

relevant open issue. One of the main concerns of today's farmers is protecting crops from

wild animals’ attacks. There are different traditional approaches to address this problem

which can be lethal (e.g., shooting, trapping) and non-lethal (e.g., scarecrow, chemical

repellents, organic substances, mesh, or electric fences). Nevertheless, some of the traditional

methods have environmental pollution effects on both humans and ungulates, while others

are very expensive with high maintenance costs, with limited reliability and limited

effectiveness. In this project, we develop a system, that combines AI Computer Vision using

DCNN for detecting and recognizing animal species, and specific ultrasound emission (i.e.,

different for each species) for repelling them. The new system requires communication,

computation and storage capabilities, and therefore designed and developed an infrastructure

that integrates ad-hoc IoT devices, Edge and Cloud Computing. The edge computing device

activates the camera, then executes its DCNN software to identify the target, and if an animal

is detected, it sends back a message to the Animal Repelling Device including the type of

ultrasound to be generated according to the category of the animal. The ``activity'' message is

also transmitted from the repellent device via LoRa to the LoRa gateway, which then

forwards the packet to the TTN server.


CHAPTER 1
INTRODUCTION
Agriculture has seen many revolutions, whether the domestication of animals and plants a
few thousand years ago, the systematic use of crop rotations and other improvements in
farming practice a few hundred years ago, or the “green revolution” with systematic breeding
and the widespread use of man-made fertilizers and pesticides a few decades ago.

Figure 1.1. Agriculture and ICT innovation


Agriculture is undergoing a fourth revolution triggered by the exponentially increasing use of
information and communication technology (ICT) in agriculture. Autonomous, robotic
vehicles have been developed for farming purposes, such as mechanical weeding, application
of fertilizer, or harvesting of fruits. The development of unmanned aerial vehicles with
autonomous flight control, together with the development of lightweight and powerful
hyperspectral snapshot cameras that can be used to calculate biomass development and
fertilization status of crops, opens the field for sophisticated farm management advice.
Moreover, decision-tree models are available now that allow farmers to differentiate between
plant diseases based on optical information. Virtual fence technologies allow cattle herd
management based on remote-sensing signals and sensors or actuators attached to the
livestock.
Taken together, these technical improvements constitute a technical revolution that will
generate disruptive changes in agricultural practices. This trend holds for farming not only in
developed countries but also in developing countries, where deployments in ICT (e.g., use of
mobile phones, access to the Internet) are being adopted at a rapid pace and could become the
game-changers in the future (e.g., in the form of seasonal drought forecasts, climate-smart
agriculture).
1.1. Smart Farming
Smart farming is a management concept focused on providing the agricultural industry with
the infrastructure to leverage advanced technology – including big data, the cloud and the
internet of things (IoT) – for tracking, monitoring, automating and analysing operations.

Figure 1. 2. Smart Farming


Also known as precision agriculture, smart farming is software-managed and sensor-
monitored. Smart farming is growing in importance due to the combination of the expanding
global population, the increasing demand for higher crop yield, the need to use natural
resources efficiently, the rising use and sophistication of information and communication
technology and the increasing need for climate-smart agriculture.
1.1.1. Smart farming technologies
The intelligent farm includes the use of technology such as:
 Sensors for soil scanning and water, light, humidity and temperature management.
 Telecommunications technologies such as advanced networking and GPS.
 Hardware and software for specialized applications and for enabling IoT-based
solutions, robotics and automation.
 Data analytics tools for decision making and prediction. Data collection is a
significant part of smart farming as the quantity of data available from crop yields,
soil-mapping, climate change, fertilizer applications, weather data, machinery and
animal health continues to escalate.
 Satellites and drones for gathering data around the clock for an entire field. This
information is forwarded to IT systems for tracking and analysis to give an “eye in the
field” or “eye in the barn” that makes remote monitoring possible.
The combination of these technologies facilitates machine-to-machine (M2M) derived data.
This data feeds into a decision support system so that farmers can see what is happening at a
more granular level than in the past. For example, by precisely measuring variations within a
field and adapting the strategy accordingly, farmers can greatly increase the effectiveness of
pesticides and fertilizers and use them more judiciously. Similarly, smart farming techniques,
help farmers better monitor the needs of individual animals and adjust their nutrition to
prevent disease and enhance herd health.
1.1.2. Benefits of smart farming
By making farming more connected and intelligent, precision agriculture helps reduce overall
costs and improve the quality and quantity of products, the sustainability of agriculture and
the experience for the consumer. Increasing control over production leads to better cost
management and waste reduction. The ability to trace anomalies in crop growth or livestock
health, for instance, helps eliminate the risk of losing yields. Additionally, automation boosts
efficiency. With smart devices, multiple processes can be activated at the same time, and
automated services enhance product quality and volume by better controlling production
processes. Smart farming systems also enable careful management of the demand forecast
and delivery of goods to market just in time to reduce waste. Precision agriculture is focused
on managing the supply of land and, based on its condition, concentrating on the right
growing parameters – for example, moisture, fertilizer or material content – to provide
production for the right crop that is in demand. The types of precision farming systems
implemented depend on the use of software for the management of the business. Control
systems manage sensor input, delivering remote information for supply and decision support,
in addition to the automation of machines and equipment for responding to emerging issues
and production support.
1.2. Problem Identified
Most farmers have challenges related to crop damage due to wildlife pests. Animal intrusion
is a major threat to the productivity of the crops, which affects food security and reduces the
profit to the farmers. Organic farmers have additional challenges because they cannot use
chemical controls which are sometimes the most effective and efficient options. A need has
been identified for alternative pest control appropriate for traditional and organic farmers.
Three types of animal intrusion you might find include animal tracks, crop damage and
animal scat or faeces. In the case of animal tracks, only one instance of tracks in the field
carries a relatively low risk. On the other hand, sporadic or widespread animal tracks carry a
moderate risk, and a no-harvest buffer zone may need to be created around nearby crops.
Crop damage, such as bite marks or trampled plants, is riskier than animal tracks. Sporadic
evidence, such as a few observations of trampled plants throughout the field, is moderately
risky. Widespread crop damage is a high risk and indicates significant evidence of
contamination. Marking and avoiding harvest around high-risk areas of crop damage is a
good strategy to reduce the potential for contamination. Risks associated with faecal matter
in the field are the highest. For even just one instance of faecal matter, the risk of
contamination is moderate. Widespread evidence of faecal contamination is very high risk
and would justify marking the contaminated area and creating a no-harvest buffer zone
around the area where significant faeces was found. Animal activity on the farm can be a
huge risk to food safety when growing fruits and vegetables, which is why preharvest wildlife
scouting is so important. Existing methods like fencing can be an effective deterrent, but it
may not be practical for larger farms; however, small portions of fencing may direct animals
around high value or sensitive crops to other areas and electric fences are no longer efficient
in solving such conflicts, to protect their crops from getting damaged because of animal
intrusions, farmers have been using electric fences around their fields and areas where the
fencing don’t prove efficient, farmers prefer to stay up all night and guard their fields from
animal intrusions. Nuisance permits may be another option, but check with local Department
of Environmental Conservation (DEC) or the National Resources Conservation Service
(NRCS) before choosing this method. Practices like these have done more harm than good
for us and in extreme cases, it has even costed lives of both man and animals. so, we decided
to come up with a smarter solution that could protect the crops from animal intrusions
without causing any harm to the wildlife. To solve this conflict by using technology such as
IoT and Deep learning, which is called AIoT (Artificial Intelligence for the Infrastructure of
Internet of Things).

1.3. Scope of the Project


The product has been iterated over a period of time. Some of the innovative ways in which
this product stands out are:
1. Usage of a combination of Camera Vision to detect intrusion of any animal entering the
farm
2. Usage of the electrical signal to trigger an alarm that repels the detected animal away.
3. Solar-powered set-up
4. Since animals tend to get acquainted to the recurring sounds and lights in their
surroundings, ordinary alarming systems will work in the beginning but its effectiveness will
decrease sharply with time. To overcome this shortcoming, AniRep uses permutations and
combinations of Vision and sound patterns that changes every time an intrusion is detected.
This delays habituation in animals. As our system is deployed in rural areas, where energy
efficiency is essential, we evaluated some HW and SW architectural alternatives for the
design and implementation of the AI embedded Edge computing components to be added to
our system.
1.4. Objective
The main aim of the current work is to develop a device to protect crops from damage by
wild animals by diverting them from the farms, without harming them physically. The
objective of the project is to design, deployment and assessment of an intelligent smart
agriculture repelling and monitoring IoT system based on embedded edge AI, to detect and
recognize the animals, as well as generate ultrasonic signals tailored to each species of the
animals.
Untamed life checking and investigation are in dynamic research fields since last numerous
decades. This work mainly concentrates on creature identification from common scenes
gained by camera and intimates the farmland owner and also stored the images in the camera
trap database. This camera trap database is utilized to track the animals which enter into the
farm land and damaging the crops.

2. Problem Definition

As human and livestock population has increased immensely, forest encroachment has been
effected, which paved a floor to grazing activities, cultivation of wastelands and
deforestation. Due to such human disturbances and habitat loss the wild animals have been
affected to a great extent, some became endangered, some extinct, and those who survived,
learnt to live in man designed habitat successfully. For many years, the natural habitats of the
country have been altered because of human. .Most of the highlands and some of the
lowlands have been modified into agricultural and pastoral land. This has led to
encroachment into wildlife habitats. The constriction of wildlife habitats resulted in severe
competition for natural resources between wild animals and the local communities. This in
turn resulted in wildlife human conflict. These animals enter human settlement and their
fields for food and causes damage to agriculture and horticulture crops. Until recently, there
has been little attention given to vertebrate species that damage crops, particularly crops of
small-scale farmers in tropical and sub-tropical regions. Birds are also recognized as
significant pests. The main damage is caused by their feeding activities. Herbivorous and
omnivorous species of birds damage the agriculture. The solution to the above problem is
detecting the animals and repellent them(animals) based on AI and IOT. The process flow is
admin add the user details and animals details in the system then if the system detect the
animals, then the system sends the message or notification to the farmer or user and also it
including the type of ultrasound to be generated according to the category of the animal is
used for repellent the animal.

3. Modules List
1. Animal Repellent Web Dashboard
2. Animal Recognition
3. Repellent
4. Monitoring and Visualizing
5. Notification
6. Performance Analysis

3.1 Modules Description


1. Animal Repellent Web Dashboard
This system works in real time to detect the animals in the fields. The system enables the
farmer to have a real time view of his fields from any place via internet and even provides
manual buzzer controls if the need arises to use them. Thus, the farmer is in effective control
of the system and can manually sound the buzzer if needed. This system is economical as
compared to many of the existing solutions like electric fences, brick walls and manual
supervision of the fields. This system is very effective in driving off the animals from the
fields and keeping them away. It accurately determines the presence of animals in the fields
and sounds the buzzer. It does not sound the buzzer due to the presence of a human being or
due to some random motion. The ultrasonic buzzer is very effective against animals and
causes no noise pollution. This system is totally harmless and doesn’t injure animals in any
way. It also doesn’t cause any harm to humans. Also, this system has a very low power
requirement thus reducing the hazards of electric shocks.
2. Animal Recognition
2.1. Training Phase
This module begins by annotation of animal dataset. These templates then become the
reference for evaluating and registering the templates for the other poses: tilting up/down,
moving closer/further, and turning left/right.
2.1.1Animal Image Acquisition
ANIMAL-10N dataset contains 5 pairs of confusing animals with a total of 55,000 images.
The 5 pairs are as following: (cat, lynx), (jaguar, cheetah), (wolf, coyote), (chimpanzee,
orangutan), (hamster, guinea pig). The images are crawled from several online search engines
including Bing and Google using the predefined labels as the search keyword.
2.1.1.1. Frame Extraction
Frames are extracted from video input. The video must be divided into sequence of images
which are further processed. The speed at which a video must be divided into images depends
on the implementation of individuals. From we can say that, mostly 20-30 frames are taken
per second which are sent to the next phases.
2.1.2. Pre-processing
Animal Image pre-processing are the steps taken to format images before they are used by
model training and inference. The steps to be taken are:
 Read image
 RGB to Grey Scale conversion
 Resize image
Original size (360, 480, 3) — (width, height, no. RGB channels)
Resized (220, 220, 3)
 Remove noise (Denoise)
smooth our image to remove unwanted noise. We do this using gaussian blur.
 Binarization
Image binarization is the process of taking a grayscale image and converting it to black-and-
white, essentially reducing the information contained within the image from 256 shades of
grey to 2: black and white, a binary image.
2.1.3. Animal Detection
Therefore, in this module, Region Proposal Network (RPN) generates RoIs by sliding
windows on the feature map through anchors with different scales and different aspect ratios.
Animal detection and segmentation method based on improved RPN. RPN is used to
generate RoIs, and RoI Align faithfully preserves the exact spatial locations. These are
responsible for providing a predefined set of bounding boxes of different sizes and ratios that
are going to be used for reference when first predicting object locations for the RPN.
2.1.4. Feature Extraction
After the animal detection, animal image is given as input to the feature extraction module to
find the key features that will be used for classification. With each pose, the animal
information including shape, size, position, face, mouth and eye is automatically extracted
and is then used to calculate the effects of the variation using its relation to the frontal animal
templates.
2.1.5. Animal Classification
DCNN algorithms were implemented to automatically detect and reject improper animal
images during the classification process. This will ensure proper training and therefore the
best possible performance
3. Animal Identification
After capturing the animal image from the Farm Camera, the image is given to animal
detection module. This module detects the image regions which are likely to be human. After
the animal detection using Region Proposal Network (RPN), animal image is given as input
to the feature extraction module to find the key features that will be used for classification.
The module composes a very short feature vector that is well enough to represent the animal
image.
3.1 Prediction
In this module the matching process is done with trained classified result and test Live
Camera Captured Classified file. Hamming Distance is used to calculate the difference
according to the result the prediction accuracy will be displayed. Here, it is done with DCNN
with the help of a pattern classifier, the extracted features of animal image are compared with
the ones stored in the animal database. The animal image is then classified as animal type. If
the animal is found corresponding repellent module is called.
4. Repellent
Camera detecting the presence of animals then it enables repeller module to repelling them
through the generation of ultrasounds, which has recently been proven as an alternative,
effective method for protecting crops against predicted animals. Animals generally have a
sound sensitive threshold that is far higher than humans. They can hear sounds having lower
frequencies with respect to the human ear. For instance, while the audible range for humans
is from 64Hz - 23KHz, the corresponding range of goats, sheep, domestic pigs, dogs and cats
is 78Hz - 37KHz, 10Hz - 30KHz, 42Hz - 40.5KHz 67Hz - 45KHz and 45Hz - 64KHz
respectively.
5. Monitoring and Visualizing
The system works in real time detect the animals in the field, in addition the farmers can
access the view of their fields remotely. Type of animal and also the count can be given. The
animal recognition module will share the data over the cloud regularly through a Wi-Fi
connection. The cloud setup will consist of a private cloud instance running on a machine.
The data shared will be used to analyse the patterns and responses of wild animals. The
farmer can visualize the errors if any, resolve them, and achieve better results.
6. Notification
The email and sms notification consisting of captured image is notified to the user regarding
the detected motion in this phase. The email is sent to registered email id and sms is sent to
the Telegram account of the user to the registered number.
7. Performance Analysis
In this module we able to find the performance of our system using SENSITIVITY,
SPECIFICITY AND ACCURACY of Data in the datasets are divided into two classes not
pedestrian (the negative class) and pedestrian (the positive class). Sensitivity, specificity, and
accuracy are calculated using the True positive (TP), true negative (TN), false negative (FN),
and false positive (FP). TP is the number of positive cases that are classified as positive. FP is
the number of negative cases that are classified as positive. TN is the number of negative
cases classified as negative and FN is the number of positive cases classified as negative.

4. System Analysis
4.1 Existing System
Wild animals are a special challenge for farmers throughout the world. Animals such as deer,
wild boars, rabbits, moles, elephants, monkeys, and many others may cause serious damage
to crops. They can damage the plants by feeding on plant parts or simply by running over the
field and trampling over the crops. Therefore, wild animals may easily cause significant yield
losses and provoke additional financial problems. Another aspect to consider is that wild
animal crop protection requires a particularly cautious approach. In other words, while
utilizing his crop production, every farmer should be aware and take into consideration the
fact that animals are living beings and need to be protected from any potential suffering.
Farmers Traditional Approach
There are different existing approaches to address this problem which can be lethal (e.g.,
shooting, trapping) and non-lethal (e.g., scarecrow, chemical repellents, organic substances,
mesh, or electric fences), firecrackers, bright lights, fire, beating drums, and dogs. Non-
chemical control of pocket gophers. 22 rimfire rifle or a shotgun can be used to dispatch
woodchucks. Some motion-activated water sprayers have been developed that spray birds
when they break the motion-detecting
1. Agricultural fences
Fencing is a popular wild animal protection practice for that can last for many years.
Agricultural fences are quite an effective wild animal protection technology. However,
utilizing fences as a practice is often regulated. Some local and state entities may restrict or
prevent the use of certain types of fences. Therefore, before deciding on a suitable fence, it's
important to check local law regulations. The quality of fencing depends on the material and
structure. Depending on how it is made and what it is made of, some permanent fences can
last up to 30 years. Farmers usually use one of the following types of fences:
 Wire fences
constructed of metal wires woven together forming a physical barrier. The fences
are effective, long lasting, and require relatively little maintenance. However, they are
expensive and recommended only for the protection of high-value crops.
 Plastic fences
polypropylene fences are generally less expensive and easier to install and repair than other
types. Additionally, these fences are widely acceptable and meet various regulations. Their
disadvantage includes their short lifespan (up to 10 years) and questionable effectiveness in
areas with a higher possibility of wild animal crop damage.
 

Figure 3.1. Wire and Plastic Fence


 Electric fences
These are constructed to inflict an electric shock to animals that come in contact with the
fence, thus preventing animals from crossing the fence. These fences are long lasting and an
effective crop protection measure. Costs vary depending on specific type and size of an area.
Before purchasing electric fences, it's very important to make sure they are allowed for use in
the specific area, and for protection against endangered animal species. Additionally, it's
recommended that electric fences are marked with a warning sign to prevent any possible
human contact.
 

Figure 3.2. Electric Fences


2. Natural Repellents
Some farmers prefer using natural protection measures instead of mechanical or chemical
protective practices. There are various ways to protect crops from wild animals, including:
 Smoke
In some areas farmers burn elephant dung or other materials that smolder and create heavy
smoke
 Fish or garlic natural emulsion; repels rabbits and deer
 Beehive fencing
 For instance, elephants are repelled by the sound of honey bees; this practice is beneficial as
it serves as an extra source of income
 Chili peppers
The chemical Capsaicin makes chili peppers hot; an excellent repellent against elephants,
monkeys, squirrels, and some other wild animals; farmers who plant chili peppers will also
benefit from an extra source of income
 Lavender, soybean, peas, and beans are excellent repellents against rabbits and are
also an additional source of income
 Egg based repellent; homemade repellent against deer
 Castor oil natural repellent that keeps away burrowing animals such as moles
 
Figure 3.3. Beehive fence
3. Chemical repellents; active substances such as Anthraquinone, Butanethiol, and Methyl
Anthranilate can be used to keep wild animals away from crops
4. Biophysical barriers; fences made of bamboo sticks, coconut tree bunches, or some other
available shrubs; low-cost practice but also low efficiency in protecting crops against wild
animals
5. Electronic repellents; effective, long lasting, and eco-friendly method for crop protection
that repels animals without harming them. Farmers use one of the following two types of
electronic repellents:

Figure 3.4. Ultrasonic Electric Animal Repellent


 Ultrasonic electronic repellent - silent to humans, high-frequency sound waves repel
wild animals
 Sonic electronic repellent - audible noise that scares animals

Disadvantages
 Its disadvantages include the potential for the entire fence to be disabled due to a
break in the conducting wire, shorting out if the conducting wire contacts any non-
electrified component that may make up the rest of the fence, power failure, or forced
disconnection due to the risk of fires starting by dry vegetation touching an electrified
wire.
 Other disadvantages can be lack of visibility and the potential to shock an
unsuspecting human passer-by who might accidentally touch or brush the fence
 Bee fence disadvantages are that it is only restricted to elephants and humans can also
become targets of the bees
 Percentage of all intrusions in the detection area that was detected was relatively low
 Sensor Failure
 Expensive

4.2. Proposed System


As human and livestock population has increased immensely, forest encroachment has been
effected, which paved a floor to grazing activities, cultivation of wastelands and
deforestation. Due to such human disturbances and habitat loss the wild animals have been
affected to a great extent, some became endangered, some extinct, and those who survived,
learnt to live in man designed habitat successfully. The increasing rate of decrease in forests
and encroaching agriculture land is leading to an up rise in animal invasion of fields which
has leads to a drastic change in farmers perception towards them. The harmony between a
farmer and wild animals seems to be a impossible thing . AI Computer Vision based DCNN
for detecting animal species, and specific ultrasound emission (i.e., different for each species)
for repelling them. design, deployment and assessment of an intelligent smart agriculture
repelling and monitoring IoT system based on embedded edge AI, to detect and recognize the
different kinds of animal, as well as generate ultrasonic signals tailored to each species of the
animal. The product has been iterated over a period of time. Some of the innovative ways in
which this product stands out are:
1. Usage of a combination of Camera Vision to detect intrusion of any animal entering the
farm
2. Usage of the electrical signal to trigger an alarm that repels the detected animal away.
3. Solar-powered set-up
4. Since animals tend to get acquainted to the recurring sounds and lights in their
surroundings. This combined technology used can help farmers and agronomists in their
decision making and management process.

Advantages
 Wide area surveillance
 Accurate and Fast prediction
 Cost effectiveness of available Crop protection systems.
 Easy to use and with less maintenance.
 Robust and reliable system.
 Complete security or full proof system.
 Less or no labor requirement.
 Easily adaptable by the farmers
 Remote Monitor
 Low energy consumption
 Warns and tracks
 Fully automated system
 Integra table with third-party cameras

5. SYSTEM SPECIFICATION
5.1. Hardware specification
 Processors: Intel® Core™ i5 processor 4300M at 2.60 GHz or 2.59 GHz (1
socket, 2 cores, 2 threads per core), 8 GB of DRAM
 Disk space: 320 GB
 Operating systems: Windows® 10, macOS*, and Linux*
5.2. Software specification
 PHP 5 & Python 3.2
 MySQL
 WAMP Server 2.0
 Fkask
 Embedded C
 Arduino IDE

Chapter 6
SOFTWARE DESCRIPTION
Python 3.7.4
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL). This
tutorial gives enough understanding on Python programming language.
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
The Python Package Index (PyPI) hosts thousands of third-party modules for Python. Both
Python's standard library and the community-contributed modules allow for endless
possibilities.
The most basic use case for Python is as a scripting and automation language. Python isn’t
just a replacement for shell scripts or batch files; it is also used to automate interactions with
web browsers or application GUIs or to do system provisioning and configuration in tools
such as Ansible and Salt. But scripting and automation represent only the tip of the iceberg
with Python.
General application programming with Python
You can create both command-line and cross-platform GUI applications with Python and
deploy them as self-contained executables. Python doesn’t have the native ability to generate
a standalone binary from a script, but third-party packages like cx_Freeze and PyInstaller can
be used to accomplish that.
Data science and machine learning with Python
Sophisticated data analysis has become one of fastest-moving areas of IT and one of Python’s
star use cases. The vast majority of the libraries used for data science or machine learning
have Python interfaces, making the language the most popular high-level command interface
to for machine learning libraries and other numerical algorithms.
Web services and RESTful APIs in Python
Python’s native libraries and third-party web frameworks provide fast and convenient ways to
create everything from simple REST APIs in a few lines of code to full-blown, data-driven
sites. Python’s latest versions have strong support for asynchronous operations, letting sites
handle tens of thousands of requests per second with the right libraries.
Metaprogramming and code generation in Python
In Python, everything in the language is an object, including Python modules and libraries
themselves. This lets Python work as a highly efficient code generator, making it possible to
write applications that manipulate their own functions and have the kind of extensibility that
would be difficult or impossible to pull off in other languages.
Python can also be used to drive code-generation systems, such as LLVM, to efficiently
create code in other languages.
“Glue code” in Python
Python is often described as a “glue language,” meaning it can let disparate code (typically
libraries with C language interfaces) interoperate. Its use in data science and machine
learning is in this vein, but that’s just one incarnation of the general idea. If you have
applications or program domains that you would like to hitch up, but cannot talk to each other
directly, you can use Python to connect them.
Python 2 vs. Python 3
Python is available in two versions, which are different enough to trip up many new users.
Python 2.x, the older “legacy” branch, will continue to be supported (that is, receive official
updates) through 2020, and it might persist unofficially after that. Python 3.x, the current and
future incarnation of the language, has many useful and important features not found in
Python 2.x, such as new syntax features (e.g., the “walrus operator”), better concurrency
controls, and a more efficient interpreter.
Python 3 adoption was slowed for the longest time by the relative lack of third-party library
support. Many Python libraries supported only Python 2, making it difficult to switch. But
over the last couple of years, the number of libraries supporting only Python 2 has
dwindled; all of the most popular libraries are now compatible with both Python 2 and
Python 3. Today, Python 3 is the best choice for new projects; there is no reason to pick
Python 2 unless you have no choice. If you are stuck with Python 2, you have various
strategies at your disposal.
Python’s libraries
The success of Python rests on a rich ecosystem of first- and third-party software. Python
benefits from both a strong standard library and a generous assortment of easily obtained and
readily used libraries from third-party developers. Python has been enriched by decades of
expansion and contribution.
Python’s standard library provides modules for common programming tasks—math, string
handling, file and directory access, networking, asynchronous operations, threading,
multiprocessors management, and so on. But it also includes modules that manage common,
high-level programming tasks needed by modern applications: reading and writing structured
file formats like JSON and XML, manipulating compressed files, working with internet
protocols and data formats (webpages, URLs, email). Most any external code that exposes a
C-compatible foreign function interface can be accessed with Python’s ctypes module.
The default Python distribution also provides a rudimentary, but useful, cross-platform GUI
library via Tkinter, and an embedded copy of the SQLite 3 database.
The thousands of third-party libraries, available through the Python Package Index (PyPI),
constitute the strongest showcase for Python’s popularity and versatility.
For example:
The Beautiful Soup library provides an all-in-one toolbox for scraping HTML—even tricky,
broken HTML—and extracting data from it.
Requests makes working with HTTP requests at scale painless and simple.
Frameworks like Flask and Django allow rapid development of web services that encompass
both simple and advanced use cases.
Multiple cloud services can be managed through Python’s object model using Apache
Libcloud.
NumPy, Pandas, and Matplotlib accelerate math and statistical operations, and make it easy
to create visualizations of data.
Python’s compromises
Like C#, Java, and Go, Python has garbage-collected memory management, meaning the
programmer doesn’t have to implement code to track and release objects. Normally, garbage
collection happens automatically in the background, but if that poses a performance problem,
you can trigger it manually or disable it entirely, or declare whole regions of objects exempt
from garbage collection as a performance enhancement.
An important aspect of Python is its dynamism. Everything in the language, including
functions and modules themselves, are handled as objects. This comes at the expense of
speed (more on that later), but makes it far easier to write high-level code. Developers can
perform complex object manipulations with only a few instructions, and even treat parts of an
application as abstractions that can be altered if needed.
Python’s use of significant whitespace has been cited as both one of Python’s best and worst
attributes. The indentation on the second line below isn’t just for readability; it is part of
Python’s syntax. Python interpreters will reject programs that don’t use proper indentation to
indicate control flow.
Syntactical white space might cause noses to wrinkle, and some people do reject Python for
this reason. But strict indentation rules are far less obtrusive in practice than they might seem
in theory, even with the most minimal of code editors, and the result is code that is cleaner
and more readable.
Another potential turnoff, especially for those coming from languages like C or Java, is how
Python handles variable typing. By default, Python uses dynamic or “duck” typing—great for
quick coding, but potentially problematic in large code bases. That said, Python has recently
added support for optional compile-time type hinting, so projects that might benefit from
static typing can use it.
The Apache Web Server
In addition to PHP, MySQL, JavaScript, and CSS, there’s actually a fifth hero in the dynamic
Web: the web server. In the case of this book, that means the Apache web server. We’ve
discussed a little of what a web server does during the HTTP server/client exchange, but it
actually does much more behind the scenes. For example, Apache doesn’t serve up just
HTML files—it handles a wide range of files, from images and Flash files to MP3 audio files,
RSS (Really Simple Syndication) feeds, and more. Each element a web client encounters in
an HTML page is also requested from the server, which then serves it up. But these objects
don’t have to be static files, such as GIF images. They can all be generated by programs such
as PHP scripts. That’s right: PHP can even create images and other files for you, either on the
fly or in advance to serve up later. To do this, you normally have modules either precompiled
into Apache or PHP or called up at runtime. One such module is the GD library (short for
Graphics Draw), which PHP uses to create and handle graphics.
Apache also supports a huge range of modules of its own. In addition to the PHP module, the
most important for your purposes as a web programmer are the modules that handle security.
Other examples are the Rewrite module, which enables the web server to handle a varying
range of URL types and rewrite them to its own internal requirements, and the Proxy module,
which you can use to serve up often-requested pages from a cache to ease the load on the
server. Later in the book, you’ll see how to actually use some of these modules to enhance
the features provided by the core technologies we cover. About Open Source Whether or not
being open source is the reason these technologies are so popular has often been debated, but
PHP, MySQL, and Apache are the three most commonly used tools in their categories. What
can be said, though, is that being open source means that they have been developed in the
community by teams of programmers writing the features they themselves want and need,
with the original code available for all to see and change. Bugs can be found and security
breaches can be prevented before they happen. There’s another benefit: all these programs are
free to use. There’s no worrying about having to purchase additional licenses if you have to
scale up your website and add more servers. And you don’t need to check the budget before
deciding whether to upgrade to the latest versions of these products.
What Is a WAMP, MAMP, or LAMP?
WAMP, MAMP, and LAMP are abbreviations for “Windows, Apache, MySQL, and PHP,”
“Mac, Apache, MySQL, and PHP,” and “Linux, Apache, MySQL, and PHP,” 13 www.it-
ebooks.info respectively. These abbreviations describe a fully functioning setup used for
developing dynamic Internet web pages. WAMPs, MAMPs, and LAMPs come in the form of
a package that binds the bundled programs together so that you don’t have to install and set
them up separately. This means you can simply download and install a single program and
follow a few easy prompts to get your web development server up and running in the quickest
time with the minimum hassle. During installation, several default settings are created for
you. The security configurations of such an installation will not be as tight as on a production
web server, because it is optimized for local use. For these reasons, you should never install
such a setup as a production server. However, for developing and testing websites and
applications, one of these installations should be entirely sufficient.
Using an IDE
As good as dedicated program editors can be for your programming productivity, their utility
pales into insignificance when compared to Integrated Developing Environments (IDEs),
which offer many additional features such as in-editor debugging and program testing, as
well as function descriptions and much more.
Web Framework
Web Application Framework or simply Web Framework represents a collection of libraries
and modules that enables a web application developer to write applications without having to
bother about low-level details such as protocols, thread management etc.
Flask
Flask is a web framework. This means flask provides you with tools, libraries and
technologies that allow you to build a web application. This web application can be some
web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial
website.
Flask is often referred to as a micro framework. It aims to keep the core of an application
simple yet extensible. Flask does not have built-in abstraction layer for database handling,
nor does it have formed a validation support. Instead, Flask supports the extensions to add
such functionality to the application.  Although Flask is rather young compared to
most Python frameworks, it holds a great promise and has already gained popularity among
Python web developers. Let’s take a closer look into Flask, so-called “micro” framework for
Python.
Flask was designed to be easy to use and extend. The idea behind Flask is to build a solid
foundation for web applications of different complexity. From then on you are free to plug in
any extensions you think you need. Also, you are free to build your own modules. Flask is
great for all kinds of projects. It's especially good for prototyping.
Flask is part of the categories of the micro-framework. Micro-framework is normally
framework with little to no dependencies to external libraries. This has pros and cons. Pros
would be that the framework is light, there are little dependency to update and watch for
security bugs, cons is that some time you will have to do more work by yourself or increase
yourself the list of dependencies by adding plugins. In the case of Flask, its dependencies are:
 WSGI
Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web
application development. WSGI is a specification for a universal interface between the web
server and the web applications.
 Werkzeug
It is a WSGI toolkit, which implements requests, response objects, and other utility functions.
This enables building a web framework on top of it. The Flask framework uses Werkzeug as
one of its bases.
 Jinja2
Jinja2 is a popular templating engine for Python. A web templating system combines a
template with a certain data source to render dynamic web pages.
 built-in development server and fast debugger
 integrated support for unit testing
 RESTful request dispatching
 Jinja2 templating
 support for secure cookies (client-side sessions)
 WSGI 1.0 compliant
 Unicode based
Plus, Flask gives you so much more CONTROL on the development stage of your project.
It follows the principles of minimalism and lets you decide how you will build your
application.
 Flask has a lightweight and modular design, so it easy to transform it to the web
framework you need with a few extensions without weighing it down
 ORM-agnostic: you can plug in your favorite ORM e.g., SQL Alchemy.
 Basic foundation API is nicely shaped and coherent.
 Flask documentation is comprehensive, full of examples and well structured. You
can even try out some sample application to really get a feel of Flask.
 It is super easy to deploy Flask in production (Flask is 100% WSGI 1.0
compliant”)
 HTTP request handling functionality
 High Flexibility
To sum up, Flask is one of the most polished and feature-rich micro frameworks available.
Still young, Flask has a thriving community, first-class extensions, and an elegant API.
Flask comes with all the benefits of fast templates, strong WSGI features, thorough unit
testability at the web application and library level, extensive documentation. So next time
you are starting a new project where you need some good features and a vast number of
extensions, definitely check out Flask.

System Architecture
Animal Detection

Activate Repellent Alert Intrude Animal

Update Animal intrusion

DCNN Model
Test Sample

Animal Dataset
DL Model DL Model
Capture Live
Preprocessing
Frame

Segmentation Preprocessing

Feature Extraction Segmentation

Classification Feature Extraction

Animal Not Found Matching Animal Found

Animal Type

Repellent Sound Alert Farmer

Repellent
Farmer

Data Flow Diagram


A data-flow diagram is a way of representing a flow of a data of a process or a system.
The DFD also provides information about the outputs and inputs of each entity and the
process itself. A data-flow diagram has no control flow, there are no decision rules and no
loops. 
The visual representation makes it a good communication tool between User and System
designer. Structure of DFD allows starting from a broad overview and expand it to a
hierarchy of detailed diagrams. DFD has often been used due to the following reasons: ...
Determination of physical system construction requirements.
Data flow Symbols:
Symbol Description

An entity. A source of data or a


destination for data.

A process or task that is


performed by the system.

A data store, a place where


data is held between processes.

A data flow.
LEVEL 0
A level 0 data flow diagram (DFD), also known as a context diagram, shows
a data system as a whole and emphasizes the way it interacts with external entities. This DFD
level 0 example shows how such a system might function within a typical retail business.

LEVEL 1:
A context level DFD is the most basic form of DFD. It aims to show how the
entire system works at a glance. There is only one process in the system and all the data flows
either into or out of this process. Context level DFD's demonstrates the interactions between
the process and external entities.
LEVEL 2:

A level 2 data flow diagram (DFD) offers a more detailed look at the processes that
make up an information system than a level 1 DFD does. It can be used to plan or record the
specific makeup of a system. ... You can then input the particulars of your own system.

UML Diagrams
Use-Case Diagram
Register

Login

Admin

view the profile animal repellent

add the user details and animal


details

user

searching the animals

animals get detected

ultrasound

Notification
Class Diagram

Admin User
Register Login
Login View
View Notification

add the user details and animal details() Login()


Login() View the profile()
View the profile() receive the alert notification()

Animal repellent
search
detected Database
Ultrasound store
Notification Access

searching the animal() Store the data()


animal get detected() Access the data()
to repellent the animal()
sent the alert message to the user()

Activity Diagram
Register

Login

add the user and


animal details

searching the
animals

detecting the
animal

animal get
detected

ultrasound to
repellent the animal

alert message
to the user

Sequence Diagram
Admin Animal user
repellent

Register

Login

Add user details and animal


details
Register

Login

View the profile

searching the animal

animal get detected

Ultrasound for repellent the animal

sent the notification to te user

Collaboration Diagram
UML Diagrams
E-R diagrams

7. TESTING
PROJECT TESTING
Software testing is a method of assessing the functionality of a software program.
There are many different types of software testing but the two main categories are dynamic
testing and static testing. Dynamic testing is an assessment that is conducted while the
program is executed; static testing, on the other hand, is an examination of the program's code
and associated documentation. Dynamic and static methods are often used together.
It is a complex process of testing the presence of potentially harmful bugs in developed
or developing e-learning software.
In the proposed model, we create a function detect(frame) to resize the image so that we
can call the function at appropriate places. We use try and except method, wherein in try, we
resize the image into 64x64 dimension and expanding the dimension. If the ranges of the
image are greater than one, then we rescale it to range 0 to1 and we predict the output
using ‘predict’ function. Then, to know the class in which the image belongs, we use
predict_classes. Shape not found is printed if there is an Attribute Error i.e. if my testing
data/frame doesn’t match the training set we get this indication.
To know whether the prediction is right or not, initially give a testing image to find
whether it belongs to the appropriate class or not. In the proposed model the class indices are
{boar : ‘0’, elephant: ‘1’, monkey: ‘2’} When a boar image is given to test, the output
will be [0] and if my test image is a goat, then it should return ‘shape not found’. For this,
we have to read the image using imread and call the detect function.
To detect the animals in the image. In order to check the correctness of the model, a
sample image is taken and we create a directory to save all the frames that is created.
Frames are named automatically and then we read each frame using imread and we call the
detect function.to find whether there is an animal in the particular frame. Then, we give the
appropriate sound according to the animal detected by importing playsound. This is
achieved by using else-if case by giving the class indices as condition. In the proposed
model, crackers, high pitch sounds and gun shots were used to drive the particular animal
away. After every image is read from the datasets the space and all the windows are released
at once in order to save memory.

RESULT AND DISCUSSION


Thus, the proposed model will train the image dataset of animals and this model is saved.
The saved model will run on the driver code in order to compare the trained images
with the new test images from the live capture. If anyone of the animals that is trained is
detected during the live capture, a repelling sound is played in order to drive away the
animal with the help of speakers. In order to check the correctness of the model,
different test images are given and their classes are detected.
So, when the boar is detected during capture, we get the audio output (appropriate
repelling sound) as well as the class indices of boar (i.e. {0}).

CONCLUSION
Agricultural farm security is widely needed technology nowadays. In order to accomplish
this, a vision based IoT system is proposed and implemented using Python and OpenCv and
fabricated a AniRep Device to blow out the animals. The implementation of the application
required the design and development of a complex system for intelligent animal repulsion,
which integrates newly developed HW and SW components and allows to recognize the
presence and species of animals in real time and also to avoid crop damages caused by the
animals. Based on the category of the animal detected, the edge computing device executes
its DCNN model to identify the target, and if an animal is detected, it sends back a message
to the Animal Repelling Device including the type of ultrasound to be generated according to
the category of the animal. The ``activity'' message is also transmitted from the repeller
device via LoRa to the LoRa gateway, which then forwards the packet to the TTN server.

FUTURE ENHANCEMENT
Further in the proposed architecture, some image compression techniques can be developed
to reduce the time taken for notification to reach user as described above.
REFERENCES
[1] M. De Clercq, A. Vats, and A. Biel, ``Agriculture 4.0: The future of farming technology,''
in Proc. World Government Summit, Dubai, UAE, 2018, pp. 11-13.
[2] Y. Liu, X. Ma, L. Shu, G. P. Hancke, and A. M. Abu-Mahfouz, ``From industry 4.0 to
agriculture 4.0: Current status, enabling technologies, and research challenges,'' IEEE Trans.
Ind. Informat., vol. 17, no. 6, pp. 432 4334, Jun. 2021.
[3] M. S. Farooq, S. Riaz, A. Abid, K. Abid, and M. A. Naeem, ``A survey on the role of IoT
in agriculture for the implementation of smart farming,'' IEEE Access, vol. 7, pp. 156237-
156271, 2019.
[4] K. Kirkpatrick, ``Technologizing agriculture,'' Commun. ACM, vol. 62, no. 2, pp. 14-16,
Jan. 2019.
[5] A. Farooq, J. Hu, and X. Jia, ``Analysis of spectral bands and spatial resolutions for weed
classification via deep convolutional neural network,'' IEEE Geosci. Remote Sens. Lett., vol.
16, no. 2, pp. 183-187, Feb. 2018.
[6] M. Apollonio, S. Ciuti, L. Pedrotti, and P. Banti, ``Ungulates and their management in
Italy,'' in European Ungulates and Their Management in the 21th Century. Cambridge, U.K.:
Cambridge Univ. Press, 2010, pp. 475-505.
[7] A. Amici, F. Serrani, C. M. Rossi, and R. Primi, ``Increase in crop damage caused by wild
boar (Sus scrofa L.): The `refuge effect,''' Agronomy Sustain. Develop., vol. 32, no. 3, pp.
683-692, Jul. 2012.
[8] S. Giordano, I. Seitanidis, M. Ojo, D. Adami, and F. Vignoli, ``IoT solutions for crop
protection against wild animal attacks,'' in Proc. IEEE Int. Conf. Environ. Eng. (EE), Mar.
2018, pp. 1-5.
[9] M. O. Ojo, D. Adami, and S. Giordano, ``Network performance evaluation of a LoRa-
based IoT system for crop protection against ungulates,'' in Proc. IEEE 25th Int.Workshop
Comput. Aided Modeling Design Commun. Links Netw. (CAMAD), Sep. 2020, pp. 1-6.
[10] H. E. Heefner and R. S. Heffner, ``Auditory perception,'' in Farm Animals and the
Environment, C. Phillips and D. Piggins, Eds. Wallingford, U.K.: CAB International, 1992.
[11] https://www.indiatimes.com/news/india/in-the-battle-between-man-vs-wild-highways-
railway- lines-emerge-as-new-challenges-375504.html
[12] https://adventuresinmachinelearning.com/neural-networks-tutorial/
[13] https://github.com/tensorflow/models
[14]https://digitalcommons.unl.edu/cgi/viewcontent.cgi?
article=2189&context=icwdm_usdanwrc

You might also like