Deep-CNN based Robotic Multi-Class Under-Canopy Weed Control in Precision Farming

Smart weeding systems to perform plant-specific operations can contribute to the sustainability of agriculture and the environment. Despite monumental advances in autonomous robotic technologies for precision weed management in recent years, work on under-canopy weeding in fields is yet to be realized. A prerequisite of such systems is reliable detection and classification of weeds to avoid mistakenly spraying and, thus, damaging the surrounding plants. Real-time multi-class weed identification enables species-specific treatment of weeds and significantly reduces the amount of herbicide use. Here, our first contribution is the first adequately large realistic image dataset \textit{AIWeeds} (one/multiple kinds of weeds in one image), a library of about 10,000 annotated images of flax, and the 14 most common weeds in fields and gardens taken from 20 different locations in North Dakota, California, and Central China. Second, we provide a full pipeline from model training with maximum efficiency to deploying the TensorRT-optimized model onto a single board computer. Based on \textit{AIWeeds} and the pipeline, we present a baseline for classification performance using five benchmark CNN models. Among them, MobileNetV2, with both the shortest inference time and lowest memory consumption, is the qualified candidate for real-time applications. Finally, we deploy MobileNetV2 onto our own compact autonomous robot \textit{SAMBot} for real-time weed detection. The 90\% test accuracy realized in previously unseen scenes in flax fields (with a row spacing of 0.2-0.3 m), with crops and weeds, distortion, blur, and shadows, is a milestone towards precision weed control in the real world. We have publicly released the dataset and code to generate the results at \url{https://github.com/StructuresComp/Multi-class-Weed-Classification}.


I. INTRODUCTION
Herbicides can have negative side-effects on the ecosystem, biodiversity, and human health [1]. Conventional weed control methods indiscriminately spray the entire field, including soil, crops, and weeds, with a single herbicide. This strategy is widely applied as it does not require the users to know the spatial distribution or the type of the weeds. However, overuse of chemicals has led to hundreds of herbicide-resistant species of weed across the world [2]. Reducing the amount of herbicides is a crucial step towards sustainable agriculture. Site-specific weed control can result in 90% savings in herbicide expenditures [3]. Since the worldwide annual sales of pesticides are on the order of a hundred billion dollars [4], the economic impact -in addition to environmental benefits -of precision weed management is overwhelming. The past decade has seen revolutionary advances in mobile robotic platforms for precision agriculture and several commercial entities (Blue River Technology, ecoRobotix, Hitch Robotics, EarthSense, and Naio Technologies) have commercialized various robotic vehicles. Real-time weed control is the primary objective of several of these vehicles, e.g. "See and Spray Machines" of Blue River Technology and TerraSentia of EarthSense. In the context of these ongoing activities in commercial as well as academic [5] sectors, real-time weed detection and classification is a truly enabling technology for robotics. However, * Correspondence should be addressed to khalidjm@seas.ucla.edu three critical challenges -(1) data, (2) training, and (3) real-world deployment -have to be overcome for fully autonomous weed management. While many weed libraries have been released [6][7][8][9][10], what is lacking is a large enough image dataset of realistic fields, including crops and weeds, distortion, shadows, and motion blur. The onboard computing power of agricultural robots can often be limited, especially for row crops (e.g. flaxseed and canola) where the inter-row spacing is small as 0.2-0.3 m. This spacing limits the size of the robot. Existing platforms except for robots from ecoRobotix are suitable only for fields with wide row spacing (≥ 0.4 m) as they use GPS (limited accuracy with crop blocking and size-incompatible with small robots) for navigation and guidance. Moreover, the robot should be able to travel under-canopy once the crop canopy has been established for truly precise weed management. This further restricts the size of the robot as well as the computing capability. Small vehicles to travel under-canopy have been introduced by EarthSense. However, owing to the challenges above, autonomous weed management with small vehicles is yet to be achieved.
To address these issues, we employ our own low-cost (around $500) compact robot, SAMBot, as shown in Fig.  1(a1), to which two cameras are attached 0.2−0.4m above the ground. The customized three-degree-of-freedom gimbal enables the camera to scan an angle between 0 • to 150 • . We employ a mobile Convolutional Neural Network (CNN) for weed classification. We chose this CNN because it is the next-generation of on-device computer vision networks, can predict much faster than other networks, and maintain competitive performance. The net- The cameras on our SAMBot robot performing multi-weed classification to recognize the weed(s) in the view of camera I (shown as the dashed red rectangle) in the flax fields by exploiting the light-weight MobileNetV2 CNN model and executing spraying (continuous white lines); (a2) The predicted weed -Venus mallow (in the small red rectangle) in the view of camera I out of the 16-class AIWeeds (in the blue rectangle) by onboard Jetson Nano (denoted as the filled red dot in (a1)); Snapshots showing the statuses of weeds (b1) before and (b2) after robotic herbicide spraying. Continuous lines in both (b1) and (b2) represent the flax croplines. Note that weed classification is for point spray but not for this dense weed scenario, so (b1) and (b2) are here to validate our robotic spraying system. work utilizes a modified MobileNetV2 [11] architecture (i.e. dropping last two fully-connected layers and adding one global average pooling layer) and its inference is optimized by NVIDIA TensorRT. Using the same pipeline, we also train and run another 4 models with acceptable training speed and accuracy. The contributions of this system paper are as follows: • We release a realistic dataset -AIWeedscontaining 10,000 labeled images with multiple weeds/crops in view, including flax and 14 most common weeds in North Dakota, the middle of China, and California [12]. The images are taken at several stages of weed from 20 different sites in the fields and gardens with variations in illumination, shadows, weather conditions, view perspective and distance, and plant growth stages.
• We demonstrate a multi-class weed classification pipeline for model deployment on GPU boards, even low-end boards such as Jetson Nano/Xavier Nx. Using this pipeline, we study weed classification using 5 modified models: CNN-MobileNetV2 and 4 other more complicated models and compare their performance through various metrics. Researchers can use this study to evaluate their unique situational needs, such as training time and accuracy, and select the appropriate model for their needs.
• We run CNN-MobileNetV2, the only qualified candidate for onboard under-canopy weed classification, on SAMBot (with Jetson Nano) in flax fields and achieve satisfactory experimental results, i.e. accurately detect and spray weeds. This is a milestone for real-time autonomous weeding in realistic fields.
The remainder of this study is arranged as follows. Section II presents the state-of-the-art on weed classification. Section III describes how the dataset is built while Section IV gives details of our multi-class weed classification pipeline. We then show our experimental results of models trained on our dataset and deployed onto the real-time robot system. Finally, the conclusion is drawn in Section VI.

A. Vision-Based Weed Control & Datasets
Image-based [6,13,14], spectrum-based [15,16] and spectral image-based [17,18] methods have been successfully applied to identify weeds from both ground and aerial photography. Spectrum and spectral image-based approaches are ideally suited for highly controlled sitespecific environments where spectrometers can be tailored for consistent acquisition and detection. Nonetheless, it is challenging to incorporate them in harsh field environment and deploy them onto compact vehicles. Vision-based methods, on the other hand, benefit from cheaper and simpler image acquisition under varying illumination conditions. Weed datasets in realistic fields are indispensable for vision-based weed control, but the existing ones [6][7][8][9] only embrace ideal weed images without background, none of which is apt for real field applications. The most realistic one [10] consists of static clear (without motion blur and shadows) images shot from a straight downwards view. Nonetheless, distortion, shadows, and motion blur that always appear during applications increasing technical difficulty are not reflected in [10].

B. Multi-class Classification Using Deep Neural Network
Classical vision-based weed classification methods rely on different features of crop plants and weeds, such as color, leaf shape [19] and size, vein patterns, and so forth [20]. However, in complex natural scenarios with high weed densities where weeds and crop plants overlap and occlude, they cannot perform the task correctly and robustly. In addition, further investigation is needed as to whether they are applicable to actual field conditions. This problem is addressed by recent deep learning models, such as Convolutional Neural Networks (CNNs). CNNs [8,[21][22][23][24] take advantage of a deep hierarchical structure to extract global features of the image and context information (background such as soil), which significantly reduces the error rate of image recognition than the classical algorithms mentioned above. For early-stage wide weed control (around stem elongation but before booting), many current methods for weed detection and classification focus on segmenting images with both RGB and excess green/red or near-infrared [5,21,25] recordings. However, they are powerless in fields with canopies developed and visual occlusion. Performing early-stage weed control will probably destroy or affect the growth of crops and thus the crop yield. As such, under-canopy weed control is a must. [21] and [7] tried semantic segmentation of weeds and crops. Still, segmentation methods [7,21,25] require lots of effort and time because of hand-crafted labeling and are challenging to be run on an embedded computer. As a result, there is a timely need to do under-canopy multi-class weed identification in real fields with CNNs.

C. Under-canopy Weeding with Low-cost Robots
As mentioned above, CNN models have been widely explored by researchers and run on expensive, powerful PCs [7,8,21,25]. However, none of the prior works deployed their model onto a flexible mobile robot that works for under-canopy weeding. Powerful PCs are usually not an option for small economical platforms. Our prior work verified that our low-cost robot platform SAMBot worked autonomously in real fields with narrow row spacing, e.g., flax and canola fields. On SAMBot, NVIDIA Jetson Nano is used as a cost effective ($99) solution that possesses the performance and capabilities to run modern artificial intelligence workloads.
In summary, to the best of our knowledge, this work is the first trial applying lightweight multi-class models to agricultural robots for under-canopy weed control and testing the performance in real flax fields.

III. DATASET COLLECTION
Our first goal is to create a variable and realistic dataset that allows us to step towards the further objective,i.e. to realize and enhance the baseline accuracy of the off-the-shelf CNNs and make it easy to be trained and deployed to facilitate wider use of the dataset. Finally, the deployed model enables SAMBot to detect, identify, and precisely spray weeds during field marching, even when the visual appearance of the plants and background has changed. In this section, we provide details of how we collected images to reflect varying scenes and target variability in realistic fields.
Unlike the aforementioned libraries [6][7][8][9][10], we build a dataset named AIWeeds containing flax and 14 most common weeds in the fields in North Dakota, California, and central China. The image resolution is 1920×1080 or 1280×720 pixels. Table I  A total of more than 10,000 images were taken under different sunlight (from 7 a.m. to 6 p.m.), weather conditions (super bright, sunny, cloudy, and rainy), growth stages (from sprouting to ripening), and varying health conditions (under drought, plant disease, and insect pest infection). On average, 600 images of each target species were taken from at least three different locations. Rotation and scale of the target weed species in the images also vary as they are photographed in situ with unknown orientation. Fig. 2 displays some image samples from our dataset and gives a sense of the variations. These variations in conditions were deliberate in order to significantly increase the generality of AIWeeds. They can, however, influence the foliage color, strength of features, and other noticeable anomalies. This includes the intraspecies variation of the data. As shown in Fig. 2, another variability in our dataset arises from the complex and dynamic target backgrounds. Although our dataset is large, over-fitting might still appear, the main concern of deep neural networks. Later in Section IV, we will describe the image augmentation skills implemented to avoid over-fitting. We also kept this in mind while constructing AIWeeds. We rotated the camera and rendered motion blur during the shot. These confounding factors of heterogeneity in AIWeeds will jointly lead to deeper and more complex models to attain acceptable performance.
In addition, locations subject to dense weed infestations are also populated by other native plants. Since we are unable to process a dataset including all plants, all other non-target species in view must be labeled as negative samples, along with all non-target background images. Unfortunately, this introduces a highly variable class in the dataset that will be difficult to classify consistently. In order to prevent over-fitting, increase the accuracy and robustness of weed classification models despite the disturbance of non-target plants, we include the negative class in AIWeeds (abbreviated as Neg.) in Table  I. The strictness of the collection process will ensure the accuracy and robustness of all classification learning models. Fig. 2 displays a subset of AIWeeds to demonstrate its variety and generality within classes, from which the complexity of the learning problem is evident.

IV. MULTI-CLASS WEED CLASSIFICATION PIPELINE
In this section, we illustrate the pipeline for a multiclass weed classification scheme. To implement and realize our models, we utilized the popular machine learning framework, Tensorflow, and high-level API, Keras. This allowed us to try out various models, such as VGG19, NasenetMobile, ResNet50, InceptionV3, Xception, DenseNet, and MobileNetV2. After testing different models, we concluded that MobileNetV2 provided the best combination of low memory usage and computational time but maintained a respectable level of accuracy. It is, therefore, deployable onto Jetson Nano with limited onboard computation resources.
All models were pretrained to recognize 1,000 object classes in ImageNet, and we slightly modified their architectures to classify 16 classes (14 types of weeds, flax, and negatives) in AIWeeds. Modifications will be illustrated on MobileNetV2 because they are identical for other models. As shown in Fig. 3, the last fully connected layer consisting of 1,000 neurons of ImageNettrained MobileNetV2 is replaced by a 16-neuron fully connected layer. We used MobileNetV2 as a feature extractor and added two layers at the end: a global average pooling (GAP) layer and a fully connected layer that used sigmoid as the activation function. Sigmoid is chosen because the probability of every class presenting in the same view (image) in nature is the same. It allows the output layer to identify the likelihood of an image belonging to each class. The weed with the highest sigmoid-activated neuron probability is thought to appear in the input image. The preprocessing preparation for learning includes image flipping, resizing, and augmentation. First, all images for training, validation, and testing were rotated and resized to 384 × 224, the size closest to the default 224×224 in ImageNet while matching the normal output of the robot's camera and keeping the ratio of our photographs taken to prevent excessive distortion. Next, image augmentation was performed by rotating every image arbitrarily in the range of [−360 • , 360 • ] and then scaling it in the range of [0.5, 1] both horizontally and vertically. After that, each color channel and pixel intensity were both randomly shifted between -25 pixels to 25 pixels to account for the illumination variance. We also randomly scaled pixel intensity within [0.75, 1.25] range and did random perspective transformations on each image to stimulate a wide range of viewing distances and angles. In summary, our image augmentation implementations accounted for variations in rotation, scale, illumination, color, and perspective. Otherwise, the deep neural network models mentioned above, with trainable weights in the order of millions, would dramatically over-fit the images by memorizing the training subsets.
Then, we split the labeled images in AIWeeds into training, validation, and testing sets; these sets contained 60-20-20 percent respectively for k-fold cross validation with k = 5. Stratified random partitioning was executed to ensure even distribution of different weed classes within each subset. A random split of 60% formed the training dataset, while 20% constituted the validation dataset to monitor the training process and minimize over-fitting. The remaining 20% were reserved for testing and never allowed to join any training procedure. Normally, training the models from scratch with our custom dataset cannot guarantee acceptable performance even after a long training time on a computationally powerful platform. As a result, each model was loaded with its corresponding pre-trained weights on ImageNet as initial weights before training through Keras. The weights of the fully-connected layer were initialized by uniform distribution.
Finally, we fine-tuned the layers using our custom built dataset. The standard binary cross-entropy loss function and Adam optimizer were used to train all models. Batches of 32 images were produced for training, which would be aborted if the validation loss did not decrease after 32 epochs. Here, the validation loss refers to the classification error calculated on the validation subset of images. The training was restarted after an abortion by loading the continuously saved model with the smallest running validation loss. After exploration, the initial learning rate was set as 0.0001 and was then successively halved every time the validation loss did not decrease after 16 epochs. The learning rate would be reduced to 0.5 × 10 −4 when the training restarted after an abortion. The validation and testing results of all models will be given in Section V B.
Experiments demonstrated that only MobileNetV2 could be deployed and run on hardware-limited SAMBot (with Jetson Nano) with/without structure optimization by TensorRT, while other complicated models are not deployable even with TensorRT speedup. We used Ten-sorRT to optimize the inference time that delivers low latency, memory usage, and high throughput. The four key operation steps related to TensorRT include creating frozen graphs for trained models, converting frozen graph to the TensorRT engine, running TensorRT engine, and benchmarking all models. Details are given in our open-source repository.

V. EXPERIMENTS & RESULTS
In this section, we illustrate our experimental setup, followed by the quantitative assessment of five 16-class classification approaches. Then, we deploy MobileNetV2, onto our embedded board, Jetson Nano (the red dot in Fig. 1(a1)). Finally, we run our robot, in flax fields in North Dakota, with real-time video streaming. This is to verify the capabilities of the deployed model, i.e. whether the robot can successfully detect multiple types of weeds in flax fields with a medium weed density and spray the corresponding herbicide. The experimental results and supplementary video validate the practicality of MobileNetV2 on SAMBot.

A. Experimental Setup
All experiments were conducted on our miniaturized, low-cost, functional agricultural robot -SAMBot -in Fig. 1(a1) and Fig. 4. It is developed and tested for weed control in flax (as shown in Fig. 4(a1)) and canola fields of North Dakota, the leading producer with 91% of the U.S. flax production and 85% of canola production [26]. The robot is generally applicable to row crops. The robot has a powerful drive train 1 (the rated torque of motors is 4.81N·m). It successfully passed all the bumps/dents (the maximum height/depth of which is the same as the height of chassis) and finished the full exploration of the fields during field tests during the Summer of 2021 in Fargo, North Dakota. It continuously worked in the fields more than 14 hours with 12-cell 18400mAh onboard LiPo batteries 2 . Referring to Fig. 1(a1) and Fig. 4(b), two cameras 3 are mounted at the back of the robot, about 20-40 cm above the ground. The images in AIWeeds were therefore taken from the robot's perspective. One camera and one pressure sprayer 4 are rigidly coupled and actuated together by a gimbal 5 to realize a yaw angle of 0 • − 150 • . Each sprayer is connected to a herbicide tank 6 . Not only the orientation of the gimbal assemblies can be changed by servos, but also their positions are adjustable left and right, up and down on the 3D-printed pegboard based on the growth stage of crops/weeds and row spacing, as indicated in the red arrows in Fig. 4(c).

B. Quantitative Results of Workstation Training
We use the F 1 score for quantitative evaluation: where precision s , recall s are the precision, recall for class s, respectively. All models presented in this section are trained and tested with the dataset in Table I. Fig. 5 shows the training loss and average validation class accuracy of models over 64 epochs on our AIWeeds dataset. On our GTX 1080 Ti platform, each epoch of DenseNet121, InceptionV3, MobileNetV2, ResNet50, and Xception took 978s, 437s, 274s, 672s, and 672s on average, respectively. Training loss and average validation class accuracy of different models are plotted in Fig. 5 to eliminate over-fitting during training. MobileNetV2 offers an accuracy of 94.50%, while being the fastest to finish training, far ahead of other models. DenseNet121, on the other hand, gives the best accuracy, 96.77%, and the smallest loss, 0.0027, after being trained for 64 epochs. We continued to train MobileNetV2 for 128 epochs, which doubled the time needed for 64 epochs, and give a second-best accuracy of 96.15%. Fig. 6 displays the F 1 -score of the five trained models on each kind of weed. All models perform well (above 90% for all classes) considering the complexity of AI-Weeds as mentioned in Section III. The F 1 -score of Neg. (backgrounds) class is relatively low. Looking carefully into the confusion matrix of all models, we find that most mispredictions are between Neg. and other weeds. This makes sense as the number of Neg. in AIWeeds is double as other weeds, as shown in Table I. The targeted plant takes a smaller area out of the overall image. When we took pictures of it, we did not avoid other native nontargeted plants in view, so it would be more difficult to be identified from a noisy background. One surprising finding is that BS. is narrow-leaf and looks similar to SF. from human recognition, especially at an early stage and in a noisy background, but were distinguished well by CNN models. This verifies the ability of CNNs to use a deep hierarchical structure to extract features.

C. Flax Field Experiments
All of the above well-trained models besides Mo-bileNetV2 cannot be deployed onto SAMBot (with Jetson Nano). Considering the running speed of the robot, the resolution of the two cameras as shown in Figs. 1(a1) and 4 is set to 384 × 224, the same as the input of CNN models. The frame rate is set to 10 frames per second. Experimentally, with MobileNetV2 running, we ran SAMBot in flax fields in North Dakota with medium weed density (with VM. and CT.) for 15m, and the robot was able to classify each weed at an average accuracy of 90%. Meanwhile, it consumed less herbicide than commercial sprayers for the same spraying range (the flux rate of our customized pressurized sprayer is 78ml/min while 95.6ml/min for a commercial two-sprayer system). The status of weeds before and after herbicide spraying is shown in Figs. 1(b1) and (b2), respectively. Fig. 7 shows the field test results. The robot successfully recognized and sprayed VM. in (a) and (b) though there was an

VI. CONCLUSIONS
In summary, we introduce the first large, realistic multiclass weed image dataset, AIWeeds, with considerable variation (e.g. shadows, lighting and perspective change, different plant growth stages, and so on), collected entirely from in situ in flax fields or gardens. It consists of flax, the 14 most common weeds, and backgrounds col-lected from North Dakota and California (U.S.) and middle China. Based on our dataset, we present baseline performance of five benchmark CNN models -DenseNet121, InceptionV3, MobileNetV2, ResNet50, and Xceptionall of which perform well with an average F 1 -score above 90% on a highly variable dataset. Our low-cost, compact SAMBot with a computational resource-limited onboard Jetson Nano is then run in flax fields with a medium density of Venus mallow and Canada thistle after the lightest MobileNetV2 being deployed. It realized a weed classification accuracy of 90% with an inference time of 47.78ms. Evaluations on both AIWeeds dataset and experiments in real fields demonstrate that our system is (i) applicable to under-canopy weeding, (ii) adaptable to unseen scenes, and (iii) able to robustly classify weeds at varying growth stages and environments. Our work (including a dataset, multi-class weed classification pipeline, and experimental results) is a milestone towards under-canopy weed control in fields. The data and tools introduced in this paper enable various commercial mobile robots to detect, classify, and manage weeds of multiple types and thus reduce the amount of herbicide use by at least an order of magnitude.