Skip to Content
SustainabilitySustainability
  • Article
  • Open Access

27 November 2026

21 Pages

Low-Cost YOLO-CBAM-Enabled Embedded System for Real-Time Tomato Pest Insect Detection and IoT-Based Monitoring

,
,
and
1
LISAD Laboratory, National School of Applied Sciences, Ibn Zohr University, Agadir 80000, Morocco
2
IMIS Laboratory, Faculty of Applied Sciences, Ibn Zohr University, Agadir 80000, Morocco
3
I2SP Team, Faculty of Sciences Semlalia, Cadi Ayyad University, Marrakech 40000, Morocco
4
LISTI Laboratory, National School of Applied Sciences, Ibn Zohr University, Agadir 80000, Morocco

Abstract

Effective pest monitoring is essential for safeguarding crop yield and quality, yet conventional methods often rely on manual inspection or costly commercial smart traps, which are inaccessible to many small- and medium-scale farmers. This study proposes a low-cost, AI-enabled pest-counting device that integrates the YOLO-CBAM object detection framework with an embedded Raspberry Pi 4B platform. The system captures images from pheromone traps, processes them locally, and transmits results to a Firebase IoT platform via cellular connectivity, enabling real-time remote monitoring without the need for Wi-Fi. The proposed YOLO-CBAM model was trained and evaluated on a custom dataset of tomato pests and benchmarked against YOLOv5-m, YOLOv8-m, and YOLOv12-m under identical conditions. Experimental results demonstrate that YOLO-CBAM achieved the highest overall detection performance, with a precision of 99.00%, recall of 99.33%, F1-score of 99.16%, mAP@0.5 of 98.02%, and mAP@0.5:0.95 of 91.56%, while maintaining competitive computational efficiency. Class-wise and qualitative analyses further demonstrate its strong capability to detect and distinguish multiple pest species under diverse visual conditions, including variable backgrounds, illumination changes, partial occlusions, and inter-class similarities. By combining high detection accuracy with affordability and portability, the proposed device offers a practical tool for Integrated Pest Management (IPM), supporting timely, data-driven, and more targeted pest-management interventions while reducing reliance on labor-intensive manual monitoring. This approach addresses a critical barrier to the adoption of precision pest monitoring and has strong potential for deployment in resource-limited agricultural settings.

1. Introduction

The projected increase in the global population to 10 billion by 2050, along with the intensifying effects of climate change, poses serious challenges to global food security [1]. Meeting future demand will require boosting agricultural output by at least 70%, which calls for the integration of innovative technologies capable of enhancing productivity and building climate resilience [2]. Among the crops most impacted by these challenges is the tomato (Solanum lycopersicum), one of the most widely cultivated horticultural crops in temperate regions, with global annual production exceeding 170 million tons [3]. Morocco has emerged as a prominent player in this sector, particularly in tomato exports, which rose by 7% in 2022 to reach 670,000 tons, up from 629,510 tons the previous year [4]. This growth elevated Morocco to third place among global tomato exporters, behind Mexico and the Netherlands [5], with the Souss-Massa region accounting for nearly 90% of the country’s total output [4].
However, the intensification of tomato production and the globalization of trade have also accelerated the spread of invasive pest species [6]. These pests threaten crop yields, reduce fruit quality, and shorten shelf-life, posing significant risks to both food supply and export competitiveness [7]. The expansion of trade networks has facilitated the movement of pests into new agroecological zones, making pest management a critical component of sustainable agriculture. This context highlights the urgency of adopting advanced, cost-effective solutions for pest monitoring and control, particularly in major production regions such as Souss-Massa.
Tomatoes, widely consumed as both a vegetable and a fruit, are highly valued for their nutritional content and dietary versatility [8,9,10]. Their high productivity and the increasing prevalence of greenhouse-based cultivation make them particularly susceptible to a broad spectrum of pests and diseases [11]. Key pest threats include whiteflies, Helicoverpa armigera, Ceratitis capitata, and Bactrocera dorsalis, as illustrated in Figure 1. The infestation process of Bactrocera dorsalis is detailed in Figure 2, showing critical stages such as adult settlement on fruit, egg deposition (oviposition), and larval damage. Due to the significant risk it poses to tomato crops, Moroccan authorities—particularly ONSSA [12]—have taken proactive measures to prevent its introduction. Pheromone traps have been strategically deployed at all land borders and commercial ports across the country. The pest remains widespread in several African nations with active trade relations with Morocco, as well as neighboring countries. Immediate containment protocols are activated upon any detection, ensuring a rapid response by the relevant authorities. Beyond direct damage, pests like whiteflies serve as vectors for harmful plant viruses such as Tomato Yellow Leaf Curl Virus (TYLCV), a disease that impairs photosynthesis and severely limits both plant growth and fruit yield [13].
Figure 1. Pests affecting tomato crops.
Figure 2. (a) Adult Bactrocera dorsalis on tomato fruit; (b) oviposition behavior on the fruit surface; (c) visible damage caused by larval infestation.
Globally, biotic stresses—including insect pests, pathogens, and invasive weeds—affect approximately 40% of agricultural production [14]. Timely and accurate detection remains a persistent challenge, and in many cases, reliance on chemical pesticides remains the default control strategy [15]. According to the FAO, pest-related damage accounts for an estimated 20% to 40% of crop losses annually, translating into global economic losses as high as $220 billion—with invasive insects alone responsible for around $70 billion [16]. Although chemical pesticides are widely used to mitigate yield losses, their long-term application carries severe consequences for the environment and human health, including associations with cancer, respiratory disorders, and genetic mutations [17]. In response to these challenges, farmers in Morocco’s Souss-Massa region have increasingly turned to smart agronomic interventions. One such method involves using plastic floor coverings in greenhouses (Figure 3), which disrupt insect life cycles by preventing soil-borne pests from emerging and eliminating larvae that hatch within the soil. These preventive strategies reflect a broader shift toward sustainable and integrated pest management practices.
Figure 3. Smart agronomic practice in greenhouses: Plastic floor covering for pest prevention.
The automation of insect counting has progressed rapidly with the integration of image processing, deep learning, and edge computing technologies. Advances in computer vision have facilitated the development of high-performance deep learning models, particularly those based on Convolutional Neural Networks (CNNs), which have demonstrated strong capabilities in addressing object detection challenges across diverse domains, including agriculture [18]. In this context, insect counting can be considered a specialized object detection task, making CNN-based detection frameworks especially suitable [19]. Among these, the YOLO (You Only Look Once) family of models has gained prominence for its ability to perform object localization and classification in a single forward pass, thereby achieving both high accuracy and real-time inference. Its architecture is inherently robust to variations in object size, orientation, and partial occlusion, making it highly adaptable to the complex visual conditions encountered in agricultural environments. These attributes are particularly advantageous for precision pest management, where rapid and reliable detection is critical for timely intervention. Since its inception, YOLO has undergone multiple iterations, with YOLOv5 [20], YOLOv8 [21], and YOLOv12 [22] standing out as key milestones, each introducing architectural enhancements that improve detection accuracy, inference speed, and deployment flexibility—attributes essential for practical applications in agriculture.
Recent studies have further demonstrated the growing role of deep learning and artificial intelligence in sustainable agricultural monitoring. Han and Wang [23] highlighted the effectiveness of deep-learning approaches for plant monitoring, including pest and disease identification, while Yang et al. [24] emphasized the potential of multimodal deep-learning strategies for crop monitoring and sustainable plant care. More recently, Sun et al. [25] reviewed the integration of artificial intelligence into smart agriculture, particularly for crop monitoring, plant protection, and intelligent decision-support systems. These advances reinforce the importance of developing accurate, efficient, and deployable AI-based solutions for precision pest monitoring.
Despite the growing potential of precision agriculture, the real-world adoption of intelligent pest monitoring systems remains limited, particularly in resource-constrained farming environments. A primary obstacle is the high cost of commercial electronic traps. Advanced solutions such as iMETOS iSCOUT [26], Trapview [27], and Semios [28] incorporate high-resolution imaging, cloud-based analytics, and wireless connectivity to enable automated insect detection. However, their unit costs—ranging from $850 to $1000 depending on the region—present a substantial financial barrier for small and medium-scale farmers [29]. As a result, many producers continue to rely on manual inspection methods, which are time-consuming, labor-intensive, and often delay necessary interventions. This dependency not only reduces the efficiency of pest control strategies but also hampers the widespread adoption of precision agriculture practices.
To address these limitations, this research proposes a cost-effective and portable pest-counting device based on the YOLO-CBAM object detection framework, implemented on a Raspberry Pi 4B. The system captures images directly from pheromone traps and processes them locally to identify pest instances. Detection results are transmitted to a Firebase IoT platform via cellular connectivity, allowing real-time remote monitoring and centralized visualization of pest populations. The specific contribution of this study lies in the integration of YOLO-CBAM-based multi-class tomato pest detection, Raspberry Pi 4B edge processing, cellular connectivity, and Firebase-based remote reporting within a single low-cost monitoring prototype. This solution offers an affordable and scalable alternative to commercial systems, enabling farmers to make timely, data-driven pest-management decisions. By providing timely pest-monitoring information and reducing reliance on manual monitoring, the proposed device can support more targeted pest-management decisions and contribute to sustainable and efficient agricultural practices.
The main contributions of this study are:
  • Development of a low-cost, portable pest-counting device: Designed and implemented a Raspberry Pi 4B–based embedded system equipped with the YOLO-CBAM object detection framework, enabling real-time pest identification and counting directly from pheromone trap images.
  • Integration of AI-based detection with IoT connectivity: Combined advanced deep learning detection capabilities with cellular IoT transmission to deliver real-time pest monitoring data to a centralized Firebase platform, eliminating the need for Wi-Fi and enabling deployment in remote agricultural areas.
  • Superior detection performance compared to state-of-the-art YOLO models: Achieved higher detection accuracy, precision, and recall than other YOLO variants (YOLOv5-m, YOLOv8-m, and YOLOv12-m), particularly in challenging field conditions involving multiple pest species, variable backgrounds, and occlusions.
  • Contribution to sustainable pest management and Integrated Pest Management (IPM): The proposed affordable and scalable monitoring prototype provides timely pest-population information that can support more targeted pest-management interventions and facilitate the adoption of IPM strategies by small and medium-scale farmers.
The remainder of this paper is organized as follows: Section 2 details the materials and methods, including dataset preparation, model architecture, and system design. Section 3 describes the experimental setup, outlines the performance evaluation criteria, and presents both quantitative and qualitative results of the proposed approach in comparison with other YOLO variants. Finally, Section 4 concludes the paper and suggests directions for future research.

2. Experimental Analysis

2.1. Methodology

Our proposed approach comprises a series of seven consecutive stages, as illustrated in Figure 4. Each stage represents a critical step in the insect pest detection pipeline:
Figure 4. Flowchart representation of the research methodology.
  • Stage 1 (S1): Collection of insect pest images to build a comprehensive dataset used for training and evaluating the deep learning (DL) model.
  • Stage 2 (S2): Preprocessing and augmentation of the dataset. All images are resized to a resolution of 640 × 640 pixels, and data augmentation techniques are applied to increase variability and improve model generalization.
  • Stage 3 (S3): Annotation of insect pests using bounding boxes, resulting in a labeled dataset in YOLO-compatible format.
  • Stage 4 (S4): Training the proposed YOLO-CBAM object detection model using the annotated dataset. During this phase, hyperparameters are optimized to enhance detection performance.
  • Stage 5 (S5): Validation of the trained model using a reserved validation set. Evaluation metrics such as mean Average Precision (mAP), Precision, and Recall are used to assess detection accuracy.
  • Stage 6 (S6): Deployment of the selected model into an embedded Pest Counting Device for real-time insect pest detection in the field.
  • Stage 7 (S7): Transmission of real-time detection results to a Firebase IoT Dashboard, enabling remote monitoring and data visualization for precision agriculture stakeholders.

2.2. Dataset

To develop and evaluate our insect pest detection system, we assembled a diverse and extensive image dataset from multiple sources. These included direct field collections and publicly available datasets compiled by Jeremy Tusubira [30], Sana Tariq [31], as well as a relevant Kaggle project [32]. Additional images were retrieved from online platforms and search engines, including IPM Images, Lepiforum, iStock, Google, Bing, and Flickr. The external datasets and online images considered in this study were obtained from publicly accessible sources and were available for research use without additional access restrictions, with the corresponding sources acknowledged where applicable. This multi-source approach resulted in a dataset that spans various geographical and ecological contexts where the targeted pest species are prevalent. Such diversity contributes to the model’s ability to generalize across the varied visual conditions represented in the dataset.
Before preprocessing and augmentation, the collected images underwent a quality-control procedure. Images were screened to retain clear and sufficiently resolved pest specimens that preserved the relevant morphological characteristics of each target insect class. Duplicate and unsuitable images were excluded, and the pest categories were checked before annotation to ensure consistency of the class labels. Following this curation process, the original dataset contained 794 images.
To ensure uniformity across the dataset, all images were resized to a fixed resolution of 640 × 640 pixels. Given that deep learning models often require substantial amounts of data for effective training, we applied data augmentation techniques to enrich the dataset and prevent overfitting. Specifically, each of the 794 original images underwent rotational transformations of 90°, 180°, and 270°, producing three additional variants per original image. This method preserved the integrity of the original image content while expanding the dataset to 3176 images (794 original images × 4 versions), as shown in Figure 5.
Figure 5. Data augmentation.
Accurate image annotation is a crucial step in preparing datasets for supervised learning, as it enables the model to recognize and learn relevant visual features. In this study, annotation was carried out using the MakeSense online platform, which allowed for efficient and consistent labeling of insect pest instances. This step significantly enhanced the quality of the dataset and provided a solid foundation for model training. Following augmentation and annotation, the resulting dataset of 3176 images was divided into training and validation subsets in an 85:15 ratio, as shown in Table 1, to ensure a balanced evaluation during the learning phase.
Table 1. Dataset split for training and validation (85:15 ratio).

2.3. YOLO-CBAM: Attention-Guided Object Detection Framework

To improve insect pest detection performance, we enhanced the YOLOv8 architecture, illustrated in Figure 6, by integrating the Convolutional Block Attention Module (CBAM) into its backbone. This modification aims to guide the network’s attention toward the most relevant spatial and channel-wise information during feature extraction, thereby improving detection accuracy under complex agricultural conditions. The resulting YOLO-CBAM architecture is illustrated in Figure 7.
Figure 6. Overview of the YOLOv8 architecture, highlighting its Backbone, Neck, and Head components.
Figure 7. Proposed YOLO-CBAM architecture with CBAM integrated into the backbone for enhanced feature extraction.
Inspired by the human visual system, the attention mechanism mimics the process of selectively focusing on the most informative regions of a scene. In the context of fine-grained object detection, such as distinguishing insect pests in diverse field environments, CBAM allows the model to emphasize pest-specific and discriminative visual features, thereby enhancing feature representation.
CBAM operates in two sequential stages, the Channel Attention Module (CAM) and the Spatial Attention Module (SAM), as illustrated in Figure 8. Let F ∈ R C × H × W represent the input feature map. The CAM first generates two channel descriptors via Global Average Pooling (GAP) and Global Max Pooling (GMP):
F c avg = 1 H × W ∑ i = 1 H ∑ j = 1 W F ( i , j )
F c max = max i , j F ( i , j )
Figure 8. Structure of the CBAM block consisting of Channel Attention and Spatial Attention modules.
These descriptors are passed through a shared Multi-Layer Perceptron (MLP) to produce channel attention weights:
M c ( F ) = σ MLP ( F c avg ) + MLP ( F c max )
Here, σ denotes the sigmoid activation function. The output attention map M c ( F ) is then used to recalibrate the original feature map F via element-wise multiplication:
F 1 = M c ( F ) ⊗ F
The resulting map F 1 is then refined using the Spatial Attention Module. To compute the spatial attention weights, average and max pooling operations are applied along the channel axis, producing two spatial descriptors F s avg and F s max , which are concatenated and processed with a 7 × 7 convolution:
M s ( F 1 ) = σ f 7 × 7 [ F s avg ; F s max ]
Finally, spatial attention is applied:
F 2 = M s ( F 1 ) ⊗ F 1
This two-step process enables CBAM to answer both “what” and “where” the model should attend, selectively enhancing meaningful features while suppressing irrelevant background noise. In our proposed YOLO-CBAM model, CBAM modules were integrated exclusively within the backbone, where hierarchical features are extracted. These refined features are then forwarded to the neck through concatenation layers, allowing the attention-enhanced representations to propagate deeper into the detection pipeline without modifying the neck structure.
Overall, this integration improves the model’s ability to detect small, partially occluded insect pests or pests that visually blend with their surroundings in complex backgrounds an essential capability for automated agricultural monitoring systems.

2.4. Low-Cost AI-Enabled Field Device for Automated Pest Counting and IoT-Based Reporting

Effective pest monitoring is a cornerstone of modern precision agriculture, yet conventional practices—such as manual inspection of pheromone traps—are labor-intensive, time-consuming, and dependent on expert knowledge. The proposed low-cost, AI-enabled pest-counting device addresses these challenges by introducing an automated, scalable solution that empowers farmers to monitor insect populations in real time, without requiring specialized personnel or costly infrastructure.
Designed with affordability and ease of use in mind, the system is particularly valuable for small and medium-sized farmers who often lack access to commercial smart traps due to their high cost and limited availability. Instead of relying on manual counting by agricultural experts, farmers simply take a photo of a pheromone trap using the system’s embedded camera. The image is processed locally by a Raspberry Pi 4B running the YOLO-CBAM object detection model. The model rapidly identifies insect species and counts their occurrences, delivering the detection results in under 10 s. Since the proposed system performs single-image analysis rather than continuous video-stream processing, this response time is suitable for periodic pheromone-trap monitoring. For CPU-only inference at an input resolution of 640 × 640 pixels, the evaluated medium-scale YOLO models showed comparable embedded-system requirements. CPU utilization was approximately 90–100%, RAM usage was 500–700 MB, and inference throughput was approximately 0.7–1.0 FPS, depending on the model and runtime environment. Under intensive CPU operation, a representative power-consumption range for the Raspberry Pi 4B is approximately 6–7 W. These computational requirements remain compatible with the intended image-based pest-monitoring workflow.
Following detection, the device transmits the captured image together with the corresponding classification and pest-count information to the Firebase IoT platform using cellular connectivity provided by the SIM7000E module. This configuration provides Wi-Fi-independent communication, which is particularly suitable for rural and isolated farming environments. The centralized data transmission enables remote access to pest-monitoring information by farmers, agronomists, and agricultural cooperatives, thereby supporting timely and data-driven pest-management decisions.
In the implemented IoT workflow, data transmission is initiated after each pheromone-trap image is captured and processed locally rather than being accumulated in hourly batches. The transmitted payload consists primarily of the captured image, while the associated numerical classification and counting metadata represent only a small fraction of the transmitted data. Consequently, the total payload size may vary depending on image content and compression settings. Cellular connectivity is provided through a mobile Internet subscription from win by inwi, costing approximately $8 per month and providing 40 GB of mobile data. This monthly allowance is more than sufficient for the intended periodic image-based monitoring workflow. Data exchange with Firebase is performed through encrypted HTTPS connections, while access permissions can be managed using Firebase authentication mechanisms and Security Rules.
Regarding power management, the proposed prototype performs periodic image acquisition, local inference, and cellular transmission rather than continuous video processing, thereby limiting the duration of intensive CPU operation. Detailed stage-wise power measurements for idle operation, image acquisition, inference, and cellular transmission, together with the evaluation of sleep/wake scheduling and solar-battery autonomy, are planned as part of the ongoing field-deployment phase of the project.
To further evaluate the economic accessibility of the proposed device, a bill of materials (BOM) was established for the complete prototype. The total one-time hardware cost is approximately $276 per device. In addition, cellular connectivity requires an Internet subscription of approximately $8 per month. This hardware cost remains substantially lower than the approximately $850–$1000 price range reported for representative commercial smart pest-monitoring systems, highlighting the affordability of the proposed solution for small and medium-sized agricultural operations.
The system architecture and data flow are illustrated in Figure 9, while detailed hardware specifications of the Raspberry Pi 4B and the bill of materials are provided in Table 2 and Table 3, respectively.
Figure 9. Schematic view of the proposed pest counting device for automated detection and IoT-based reporting.
Table 2. Specifications of the Raspberry Pi-based system.
Table 3. Bill of materials and estimated cost of the proposed pest-monitoring device.

3. Experimental Results

3.1. Experimental Setup and Performance Evaluation Criteria

To achieve a balance between high detection accuracy and efficient real-time processing, the medium-scale version of the YOLO-CBAM model was selected as the primary architecture for pest monitoring tasks. Training was conducted on the Google Colab platform using an NVIDIA Tesla T4 GPU with 16 GB of VRAM. The environment used CUDA 12.4 with driver version 550.54.15. The training process spanned 100 epochs, with a batch size of 16, allowing the model to progressively improve its ability to detect insect pests with high precision.
For comparative analysis, three additional YOLO-based models—YOLOv5-m, YOLOv8-m, and YOLOv12-m—were also trained under identical conditions. This consistent setup ensured a fair and rigorous comparison of detection accuracy, inference speed, and computational load, particularly within the context of agricultural pest monitoring applications.
To improve the reproducibility of the experiments and ensure a consistent comparison, the same training configuration, hyperparameters, and augmentation settings were applied to all evaluated models, namely YOLOv5-m, YOLOv8-m, YOLOv12-m, and YOLO-CBAM. These common settings are summarized in Table 4. The Ultralytics automatic optimizer-selection mode (optimizer=auto) selected AdamW with an effective initial learning rate of 0.00125 and momentum of 0.9. A weight decay of 0.0005 was applied to the corresponding weight parameter group, while the final learning-rate factor was set to 0.01. Training included a 3-epoch warm-up period, and cosine learning-rate scheduling was disabled.
Table 4. Common training configuration and hyperparameters used for all evaluated YOLO models.
In addition to the rotation-based augmentation applied during dataset preparation, the same online augmentation pipeline was applied to all evaluated models during training. This pipeline included HSV color-space variations, translation, scaling, horizontal flipping, and mosaic augmentation. Low-probability Albumentations transformations consisting of Blur, MedianBlur, grayscale conversion, and CLAHE were also applied, each with a probability of 0.01. Mosaic augmentation was disabled during the final 10 epochs to stabilize the final stage of training, while MixUp, vertical flipping, shear, perspective transformation, and copy-paste augmentation were not applied. The same loss configuration was maintained across all evaluated models, combining bounding-box regression, classification, and Distribution Focal Loss (DFL), with corresponding loss gains of 7.5, 0.5, and 1.5, respectively.
The performance of all evaluated models was assessed using a set of standard object detection metrics that collectively characterize detection reliability and computational efficiency. These metrics are particularly relevant for evaluating the suitability of the models for deployment on resource-constrained embedded systems used in precision agriculture and tomato pest monitoring. The evaluation criteria are described as follows:
  • Precision (P): Measures the proportion of correctly identified pests relative to all detected instances. High precision indicates the model’s effectiveness in minimizing false positives.
  • Recall (R): Assesses the model’s capacity to detect all actual pest instances within an image. A high recall score reflects a low false-negative rate, which is crucial for early pest outbreak detection.
  • F1-Score (F1): Represents the harmonic mean of precision and recall, providing a single metric that balances both sensitivity and specificity. It is particularly useful in cases with imbalanced classes or error types.
  • Floating Point Operations (FLOPs): Measures the computational operations required to process an input image. A lower FLOPs count generally indicates lower computational complexity, which is particularly relevant for deployment on resource-constrained embedded agricultural platforms.
  • Mean Average Precision (mAP): This metric summarizes the model’s ability to correctly localize and classify pests across all classes. In this study, performance is reported using AP/mAP at an IoU threshold of 0.50 (AP@0.5 and mAP@0.5), as well as the more stringent AP/mAP@0.5:0.95 criterion averaged over IoU thresholds from 0.50 to 0.95.
The formulas used to compute Precision, Recall, and the F1-Score are as follows:
Precision = TP TP + FP
Recall = TP TP + FN
F1-Score = 2 × Precision × Recall Precision + Recall
Here, the following apply:
  • True Positives (TP): Insect pests that are present in the image and correctly identified by the model.
  • False Positives (FP): Cases where the model incorrectly labels a non-pest region or object as an insect pest.
  • False Negatives (FN): Instances where the model fails to detect actual insect pests that are visibly present in the image.
The mean Average Precision (mAP) is calculated using the following formulas:
A P = ∫ 0 1 P ( R ) d R
m A P = ∑ i = 1 N A P i N
Here, the following apply:
  • Average Precision (AP): Measures the detection accuracy for a single class by calculating the area under the precision-recall curve. It indicates how well the model balances precision and recall at various confidence thresholds for that specific class.
  • Mean Average Precision (mAP): Computes the mean of AP values across all object classes in the dataset. This metric offers an overall assessment of the model’s ability to detect and correctly classify multiple pest categories.
Mean Average Precision (mAP) serves as a key evaluation metric in object detection tasks, offering a comprehensive assessment of a model’s ability to correctly detect and localize target objects across different IoU thresholds. In the context of pest monitoring, mAP is particularly important as it reflects both detection accuracy and consistency—two critical factors for ensuring reliable decision-making in precision agriculture.
Figure 10 presents a comparison of training performance between the proposed YOLO-CBAM model and three baseline models: YOLOv5-m, YOLOv8-m, and YOLOv12-m. The graph illustrates the evolution of mAP50 (mean Average Precision at IoU = 0.5) across 100 training epochs. As shown, YOLO-CBAM consistently achieves high detection accuracy throughout the training process and converges quickly. Both YOLOv5-m and YOLOv8-m also demonstrate stable learning behavior with satisfactory performance. In contrast, YOLOv12-m exhibits noticeable fluctuations in accuracy, particularly before epoch 80, suggesting challenges in achieving convergence and model stability.
Figure 10. Evolution of mAP50 during training for YOLO models on the tomato pest dataset.
While these training curves provide insight into the models’ learning dynamics, performance must also be evaluated on an independent test set. Such evaluation provides a more objective assessment of the models’ ability to generalize to unseen images exhibiting diverse visual conditions relevant to agricultural pest monitoring.

3.2. Result Analysis

3.2.1. Evaluation of Detection Accuracy Using Confusion Matrices and Quantitative Metrics

The trained models were evaluated on an independent test set consisting of 142 images containing a total of 297 annotated insect instances. The objective of this evaluation was to assess the models’ capability to accurately detect and classify insect pests under diverse and challenging visual conditions, including variable backgrounds, lighting conditions, and partial occlusions, which are commonly encountered in agricultural environments.
Figure 11 shows the confusion matrices for the four models under comparison: YOLOv5-m, YOLOv8-m, YOLOv12-m, and the proposed YOLO-CBAM. These matrices provide a class-wise breakdown of predictions across five categories: Helicoverpa armigera (HA), Ceratitis capitata (CC), Whiteflies (WH), Bactrocera dorsalis (BD), and Background. Diagonal elements represent correctly classified instances, while off-diagonal values indicate classification errors, including both false positives and false negatives.
Figure 11. Confusion matrices for YOLOv5-m, YOLOv8-m, YOLOv12-m, and YOLO-CBAM models on the pest detection test dataset.
Among the evaluated models, YOLO-CBAM achieved the most accurate results in the confusion-matrix analysis, exhibiting minimal confusion across classes and no misclassification of background regions. It correctly detected all CC, WH, and BD instances in the evaluated test set, with only a single misclassification in the HA category. YOLOv5-m and YOLOv8-m also showed competitive performance but occasionally confused HA and WH, particularly under more complex visual conditions. In contrast, YOLOv12-m exhibited comparatively more classification errors and confusion between related pest categories.
Analysis of the confusion matrices also provides insight into the main causes of the remaining classification errors. In particular, Ceratitis capitata (CC) and Bactrocera dorsalis (BD) exhibit relatively similar morphological characteristics and coloration, which can make their visual differentiation more challenging; this is reflected by some BD instances being classified as CC in the comparison models. In addition, Helicoverpa armigera (HA) can be more difficult to identify when the insect occupies a small region of the image, since fewer discriminative visual features are available to the detector. Variable illumination and partial occlusion may further reduce the visibility of these characteristics. Therefore, the main current challenges of the model are associated with very small pest instances and species presenting strong visual similarities. Nevertheless, YOLO-CBAM substantially reduced these inter-class confusions in the evaluated test set.
To further assess the reliability and repeatability of the quantitative results, each of the four models was trained independently three times under the same experimental configuration. The performance values reported in Table 5, Table 6 and Table 7 are therefore expressed as mean ± standard deviation across the three runs. The observed variations were small, with standard deviations ranging from 0.22 to 0.30 percentage points for YOLOv5-m, 0.19 to 0.26 for YOLOv8-m, 0.22 to 0.33 for YOLOv12-m, and 0.14 to 0.20 for YOLO-CBAM. These narrow ranges indicate that the reported performance was highly consistent across repeated training runs. In particular, YOLO-CBAM maintained a consistently low variability range while preserving the highest overall detection performance.
Table 5. Comparison of detection performance metrics for YOLO-based models (mean ± std of 3 runs).
Table 6. Class-wise AP@0.5 performance for the evaluated YOLO models (mean ± std of 3 runs).
Table 7. Class-wise AP@0.5:0.95 performance for the evaluated YOLO models (mean ± std of 3 runs).
In addition to the confusion-matrix analysis, Table 5 summarizes the principal quantitative performance and computational-complexity indicators, including Precision, Recall, F1-score, FLOPs, and the number of model parameters. Across the three independent runs, YOLO-CBAM achieved the highest mean Precision ( 99.00 ± 0.14 %), Recall ( 99.33 ± 0.18 %), and F1-score ( 99.16 ± 0.16 %) among the evaluated models, while introducing only a marginal increase in computational complexity compared with YOLOv8-m. To provide a more detailed class-wise evaluation, Table 6 and Table 7 additionally report the Average Precision (AP) for HA, CC, WH, and BD at an IoU threshold of 0.50 and across the more stringent IoU range of 0.50:0.95, respectively.
The class-wise AP results provide a more detailed assessment of the behavior of the models across the four pest categories. At AP@0.5, all evaluated models achieved high mean performance, particularly for CC and WH. YOLO-CBAM achieved the highest mean AP@0.5 for BD ( 97.54 ± 0.20 %) and the highest overall mean mAP@0.5 ( 98.02 ± 0.16 %). For HA, the differences among the models remained relatively small, with YOLOv8-m obtaining the highest mean AP@0.5 value of 96.78 ± 0.23 %, while YOLO-CBAM achieved 95.58 ± 0.18 %.
Under the more stringent AP@0.5:0.95 criterion, the advantage of YOLO-CBAM became more evident. The proposed model achieved the highest mean AP values for CC ( 94.41 ± 0.14 %), WH ( 93.97 ± 0.15 %), and BD ( 89.41 ± 0.19 %), together with the highest overall mean mAP@0.5:0.95 ( 91.56 ± 0.16 %). YOLOv12-m achieved a slightly higher mean AP for HA ( 88.69 ± 0.30 %) than YOLO-CBAM ( 88.46 ± 0.17 %), indicating that HA remains a comparatively challenging pest class. Overall, the class-wise results complement the confusion-matrix analysis and demonstrate that YOLO-CBAM provides particularly strong performance for the visually similar CC and BD classes while maintaining robust detection performance across all four pest categories. The consistently small standard deviations observed across the three independent training runs further support the repeatability and reliability of the reported performance.

3.2.2. Qualitative Results and Detection Output Comparison

To complement the quantitative evaluation, a qualitative comparison was conducted between the proposed YOLO-CBAM model and the most recent YOLOv12-m architecture. This analysis aimed to visually assess the models’ detection capabilities under realistic conditions, including diverse pest classes, variable backgrounds, and natural occlusions—challenges frequently encountered in agricultural environments.
The test image used in this comparison contains 18 insect pests, comprising 6 Ceratitis capitata (CC), 3 Helicoverpa armigera (HA), 6 Whiteflies (WH), and 3 Bactrocera dorsalis (BD). This composition reflects a representative scenario commonly observed in tomato cultivation. The primary objective was to evaluate the models’ ability to accurately localize and classify each pest instance without generating false positives or overlooking true detections.
As shown in Figure 12a, YOLOv12-m successfully detected all HA and WH instances but exhibited reduced performance for the remaining classes. Specifically, it identified only 3 out of 6 CC and 2 out of 3 BD insects. Additionally, one CC instance was redundantly detected—once correctly as CC and once incorrectly as BD—introducing both a false positive and a false negative. These errors suggest that YOLOv12-m struggles to distinguish between morphologically similar pest species and may be prone to inter-class confusion. Although it is the most recent version in the YOLO family, this result indicates limitations in generalization under complex, multi-class detection scenarios. These limitations point to the need for enhanced attention mechanisms or feature refinement strategies, particularly for precision agriculture applications where detection accuracy is critical.
Figure 12. Qualitative comparison of YOLOv12-m and YOLO-CBAM detection outputs.
In contrast, the YOLO-CBAM model correctly detected and classified all pest instances in the representative example shown in Figure 12b. It accurately identified and classified all 18 insects, with high confidence scores and precise bounding boxes. No false positives or missed detections were observed. This qualitative outcome illustrates YOLO-CBAM’s effective feature discrimination under the evaluated multi-class scenario.
These results underscore the effectiveness of integrating the Convolutional Block Attention Module (CBAM) into the YOLO backbone. YOLO-CBAM not only outperforms earlier versions (YOLOv5-m, YOLOv8-m), but also surpasses YOLOv12-m in terms of detection precision, class separation, and stability. The attention mechanism enables the model to focus on the most informative spatial and channel features, improving reliability in heterogeneous field environments.
Overall, the proposed YOLO-CBAM framework offers a reliable, high-accuracy solution for automated pest detection. Its ability to reduce false alarms and maintain precision makes it highly suitable for real-time deployment on low-power embedded devices, especially in small to medium-sized farms where resources are constrained but decision-making speed is critical.

3.3. Limitations

The present study was designed to provide a controlled and reproducible evaluation of the proposed YOLO-CBAM-based pest-monitoring framework while demonstrating its suitability for embedded deployment. Within this scope, several aspects provide opportunities for further extension. First, the quantitative evaluation was performed on an independent curated test set comprising 142 images and 297 annotated insect instances. The test set incorporates diverse backgrounds, illumination conditions, object sizes, and partial occlusions, allowing the models to be assessed under a broad range of visually challenging conditions. Nevertheless, this evaluation does not yet constitute a large-scale validation under fully uncontrolled field conditions. The ongoing development of the system therefore includes broader field deployment, where automated detections can be compared with expert manual observations across different environmental and seasonal conditions.
Second, the qualitative comparison presented in Figure 12 was intentionally based on a representative image containing all four target pest classes simultaneously. Such multi-species images are comparatively less frequent in the current dataset, and the selected example therefore provides a useful common scene for visually comparing the localization and classification behavior of all evaluated models. Future dataset expansion will enable similar qualitative analyses across a larger number of multi-species and more complex field images.
Third, the architectural evaluation in this study was specifically focused on assessing the contribution of CBAM when integrated into the YOLOv8-m backbone, using the original YOLOv8-m model as the direct reference architecture under identical training conditions. Accordingly, alternative attention mechanisms such as Squeeze-and-Excitation (SE), Efficient Channel Attention (ECA), and Coordinate Attention (CA) were not included in the present comparison. A broader comparative investigation of different attention strategies would represent a valuable extension for further examining the most suitable feature-refinement mechanism for embedded pest detection.
Finally, the current dataset focuses on four economically relevant pest species, namely Helicoverpa armigera, Ceratitis capitata, Whiteflies, and Bactrocera dorsalis. Although the dataset incorporates substantial visual diversity in terms of backgrounds, orientations, illumination conditions, object appearance, and partial occlusions, the reported results are naturally associated with the target species considered in this study. Extending the dataset to additional pest species, crops, geographical regions, and seasonal conditions will provide an important basis for evaluating the broader applicability of the proposed framework across different agricultural environments.

4. Conclusions and Future Work

This study presented a low-cost, AI-enabled pest-counting device integrating the YOLO-CBAM object detection framework with an embedded Raspberry Pi 4B platform for real-time insect monitoring in agricultural fields. The proposed system demonstrated superior detection accuracy and robustness compared to YOLOv5-m, YOLOv8-m, and the latest YOLOv12-m, achieving strong classification performance across the evaluated multi-class pest detection scenarios under diverse visual conditions. By combining efficient local processing with IoT-based remote reporting via cellular connectivity, the device enables farmers—particularly those in small- and medium-scale operations—to access timely pest population data without relying on costly commercial smart traps or constant Wi-Fi availability. The system’s ability to support targeted interventions aligns with Integrated Pest Management (IPM) principles, promoting environmentally sustainable and economically viable agriculture.
Beyond its technical performance, the proposed solution addresses a critical barrier to the adoption of precision pest monitoring technologies: affordability. Its portability, scalability, and low operating costs support its potential for broader field deployment and for facilitating data-driven pest control strategies in greenhouse and open-field production systems.
Future work will focus on expanding the system’s capabilities to detect a wider range of pest species and incorporating disease symptom recognition in leaves and fruits. Planned enhancements include the integration of environmental sensors to analyze correlations between pest activity and climatic variables, as well as the optimization of the YOLO-CBAM architecture to further reduce power consumption. In addition, large-scale field trials will be conducted in collaboration with agricultural cooperatives to assess system performance across diverse ecological and agronomic conditions and to further evaluate its broader agronomic, economic, and sustainability benefits, including pesticide-use optimization, labor efficiency, farmer usability, and cost-effectiveness. The incorporation of predictive analytics for pest population forecasting will also be investigated, with the aim of enabling farmers to transition from reactive to proactive pest management strategies.

Author Contributions

Conceptualization, M.Z.; Methodology, M.Z.; Validation, M.Z. and M.K.; Investigation, M.K., S.C. and A.D.; Resources, M.Z., M.K., S.C. and A.D.; Data Curation, M.Z.; Writing—Original Draft, M.Z.; Writing—Review & Editing, M.Z., M.K., S.C. and A.D.; Supervision, S.C. and A.D.; Project Administration, S.C. and A.D. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The source code, dataset, and trained models associated with this study are publicly available via Google Drive to facilitate broader accessibility and support further research and development. The materials can be accessed at the following link: https://drive.google.com/drive/folders/1eqI5dvVpSeuveQaBF9YQxSveGMaB1IdN?usp=sharing (accessed on 1 May 2026).

Conflicts of Interest

The authors declare no conflicts of interest.

References

  1. Nadathur, S.; Wanasundara, J.P.D.; Marinangeli, C.P.F.; Scanlin, L. Proteins in our diet: Challenges in feeding the global population. In Sustainable Protein Sources; Elsevier: San Diego, CA, USA, 2024; pp. 1–29. [Google Scholar] [CrossRef] [Scilit]
  2. Jararweh, Y.; Fatima, S.; Jarrah, M.; AlZu’bi, S. Smart and sustainable agriculture: Fundamentals, enabling technologies, and future directions. Comput. Electr. Eng. 2023, 110, 108799. [Google Scholar] [CrossRef] [Scilit]
  3. Méndez-Carmona, J.Y.; Ramírez-Guzmán, N.; Sandoval-Cortes, J.; Ascacio-Valdés, J.A.; Boone-Villa, V.D.; Govea-Salas, M.; Aguilar, C.N. Valorization of tomato fruit processing residues. In Sustainable Development and Biodiversity; Springer Nature Singapore: Singapore, 2023; pp. 215–243. [Google Scholar] [CrossRef] [Scilit]
  4. Zarboubi, M.; Bellout, A.; Chabaa, S.; Dliou, A. CustomBottleneck-VGGNet: Advanced tomato leaf disease identification for sustainable agriculture. Comput. Electron. Agric. 2025, 232, 110066. [Google Scholar] [CrossRef] [Scilit]
  5. EastFruit. Morocco Ranked Third in the Global Tomato Exports! 2023. Available online: https://east-fruit.com/en/trending/morocco-ranked-third-in-the-global-tomato-exports/ (accessed on 23 April 2026).
  6. Zarboubi, M.; Chabaa, S.; Dliou, A. Advancing precision agriculture with deep learning and IoT integration for effective tomato pest management. In 2023 IEEE International Conference on Advances in Data-Driven Analytics and Intelligent Systems (ADACIS); IEEE: Hoboken, NJ, USA, 2023; pp. 1–6. [Google Scholar] [CrossRef] [Scilit]
  7. Guégan, J.F.; de Thoisy, B.; Gomez-Gallego, M.; Jactel, H. World forests, global change, and emerging pests and pathogens. Curr. Opin. Environ. Sustain. 2023, 61, 101266. [Google Scholar] [CrossRef] [Scilit]
  8. Tiwari, M.; Sharma, N.C.; Fleischmann, P.; Burbage, J.; Venkatachalam, P.; Sahi, S.V. Nanotitania exposure causes alterations in physiological, nutritional and stress responses in tomato (Solanum lycopersicum). Front. Plant Sci. 2017, 8, 633. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  9. Réant, C.; Dantigny, P.; Poirier, E.; Coton, E.; Hymery, N.; Coton, M. Mycotoxin migration in Alternaria alternata molded tomatoes: An on-going challenge for food safety and food waste management. Food Microbiol. 2026, 138, 105065. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  10. Liu, C.F.; Chen, H.C.; Chen, C.I.; Huang, C.R.; Lee, C.L. Dual effects of complex fermentation on wild tomato products: Flavor diversification and functional enrichment. Future Foods 2026, 13, 100925. [Google Scholar] [CrossRef] [Scilit]
  11. Mamun, M.A.; Islam, T. Oxygenated nanobubbles as a sustainable strategy to strengthen plant health in controlled environment agriculture. Sustainability 2025, 17, 5275. [Google Scholar] [CrossRef] [Scilit]
  12. ONSSA. National Office for the Sanitary Safety of Food Products. 2025. Available online: https://www.onssa.gov.ma/ (accessed on 23 April 2026).
  13. Bertacca, S.; Rotunno, S.; Frascati, F.; Noris, E.; Accotto, G.P.; Davino, S.; Miozzi, L.; Vaira, A.M. Oxford Nanopore sequencing as a useful tool for investigating the population dynamics of invasive begomoviruses in Sicily. bioRxiv 2025. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  14. Zarboubi, M.; Bellout, A.; Chabaa, S.; Dliou, A. Towards eco-friendly apple farming: Real-time codling moth monitoring using improved YOLOv10 and IoT integration. PLoS ONE 2026, 21, e0346415. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  15. Karim, M.J.; Goni, M.O.F.; Nahiduzzaman, M.; Ahsan, M.; Haider, J.; Kowalski, M. Enhancing agriculture through real-time grape leaf disease classification via an edge device with a lightweight CNN architecture and Grad-CAM. Sci. Rep. 2024, 14, 16022. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  16. Zarboubi, M.; Bellout, A.; Chabaa, S.; Dliou, A. Enhancing integrated pest management with IoT and YOLO-Evo: A smart, low-cost monitoring system for sustainable apple farming. Results Eng. 2026, 29, 108850. [Google Scholar] [CrossRef] [Scilit]
  17. Narenderan, S.T.; Meyyanathan, S.N.; Babu, B.J.F.R.I. Review of pesticide residue analysis in fruits and vegetables. Pre-treatment, extraction and detection techniques. Food Res. Int. 2020, 133, 109141. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  18. Medjadba, Y.; Drid, H.; Yu, X. Enhancing crop disease classification and severity assessment through Fuzzy Rank-based ensemble learning approach. Signal Image Video Process. 2025, 19, 642. [Google Scholar] [CrossRef] [Scilit]
  19. Ahmed, S.; Marwat, S.N.K.; Brahim, G.B.; Khan, W.U.; Khan, S.; Al-Fuqaha, A.; Koziel, S. IoT based intelligent pest management system for precision agriculture. Sci. Rep. 2024, 14, 31917. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  20. Jocher, G.; Stoken, A.; Borovec, J.; Changyu, L.; Hogan, A.; Diaconu, L.; Poznanski, J.; Yu, L.; Rai, P.; Ferriday, R.; et al. ultralytics/yolov5. Zenodo. 2020. Available online: https://zenodo.org/records/3983579 (accessed on 25 April 2026).
  21. Jocher, G.; Chaurasia, A.; Qiu, J. YOLO by Ultralytics. Github. 2023. Available online: https://github.com/ultralytics/ultralytics (accessed on 25 April 2026).
  22. Tian, Y.; Ye, Q.; Doermann, D. YOLOv12: Attention-Centric Real-Time Object Detectors. arXiv 2025, arXiv:2502.12524. [Google Scholar] [CrossRef] [Scilit]
  23. Han, S.; Wang, H. Application of Deep Learning Technology in Monitoring Plant Attribute Changes. Sustainability 2025, 17, 7602. [Google Scholar] [CrossRef] [Scilit]
  24. Yang, Z.X.; Li, Y.; Wang, R.F.; Hu, P.; Su, W.H. Deep Learning in Multimodal Fusion for Sustainable Plant Care: A Comprehensive Review. Sustainability 2025, 17, 5255. [Google Scholar] [CrossRef] [Scilit]
  25. Sun, J.; Wang, Q.; Li, Q.; Xu, G.; Liang, B.; Ma, C.; Tian, S.; Gao, Q. Artificial Intelligence in Smart Agriculture Across the Production-to-Postharvest Continuum: Progress, Challenges, and Future Directions. Sustainability 2026, 18, 4908. [Google Scholar] [CrossRef] [Scilit]
  26. iMETOS. Remote Monitoring of Insect Pressure Saves Time and Optimizes Use of Resources–Producing More with Less. 2025. Available online: https://metos.global/en/iscout/ (accessed on 23 April 2026).
  27. Trapview. Pest Monitoring and Forecasting—Integrated Pest Management. 2025. Available online: https://trapview.com/ (accessed on 23 April 2026).
  28. Semios. Integrated Pest Management. 2025. Available online: https://semios.com/solutions/insect-pest-management/ (accessed on 23 April 2026).
  29. Agroressources. Piège à Insecte Connecté—Trapview—Agro-Ressources. 2025. Available online: https://www.agroressources.com/boutique/piegeage/pieges-insectes/piege-a-insecte-connecte-trapview/ (accessed on 23 April 2026).
  30. Tusubira, J. Cassava Whitefly Dataset. Mendeley. 2021. Available online: https://data.mendeley.com/datasets/5g38399z9p/3 (accessed on 23 April 2026).
  31. Sana, S.T. An Image Dataset of Fruit Fly Species. Mendeley. 2022. Available online: https://data.mendeley.com/datasets/hgz2n5jxhp/1 (accessed on 23 April 2026).
  32. Reda, M. Cassava Healthy Whitefly Classification. 2020. Available online: https://www.kaggle.com/datasets/mahmoudreda55/cassava-healthy-whitefly-classification (accessed on 23 April 2026).
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.