Skip to Content
AgriEngineeringAgriEngineering
  • Article
  • Open Access

11 June 2026

21 Pages

CB-YOLOv7: A Modified YOLOv7 Approach for Accurate Weed Detection in Complex UAV Imagery from Cotton Fields

,
and
College of Engineering, West Texas A&M University, Canyon, TX 79016, USA
*
Author to whom correspondence should be addressed.

Abstract

Weed detection is an important part of precision agriculture because it allows farmers to manage weeds more efficiently and reduce unnecessary herbicide use. With the use of UAVs, it is now possible to capture high-resolution images of agricultural fields, but identifying weeds from these images is still challenging due to complex backgrounds, lighting variations, and the visual similarity between crops and weeds. In this study, an improved YOLOv7-based approach is developed to address these challenges using UAV imagery collected from rainfed cotton fields in the Texas Panhandle. The original dataset consisted of high-resolution UAV images, which were divided into smaller patches and manually annotated to label weed and cotton classes. After cleaning the dataset and applying simple augmentation techniques, a total of 8396 images were used for training and testing. To improve detection performance, two modifications were introduced: Convolutional Block Attention Module (CBAM) to help the model focus on important features and Bidirectional Feature Pyramid Network (BiFPN) to improve how information is shared across different scales. Three models—YOLOv7-CBAM, YOLOv7-BiFPN, and the combined CB-YOLOv7—were evaluated. The results show that CBAM helps detect more weed instances, BiFPN reduces false detections, and the combined model gives the best overall performance, achieving an mAP@0.5 of 0.89 and an F1-score of 0.84. Overall, the study shows that improving both the dataset and the model can lead to more reliable weed detection under real field conditions. The proposed approach can be useful for identifying weeds in cotton fields using UAV imagery and can support better crop management and more efficient use of herbicides in precision agriculture.

1. Introduction

Recent advances in precision agriculture and remote sensing technologies have created new opportunities for improving crop monitoring and field management. Unmanned aerial vehicles (UAVs), commonly known as drones, are increasingly used to capture high-resolution images of agricultural fields, enabling detailed observation of crop conditions at large spatial scales. These images provide valuable information for tasks such as weed detection, crop health monitoring, yield estimation, and disease identification. However, the large volume of UAV imagery generated during agricultural surveys makes manual analysis inefficient and time-consuming. As a result, artificial intelligence (AI) and deep learning-based computer vision techniques have become essential tools for automated analysis of agricultural imagery [1,2].
Convolutional neural networks (CNNs) are currently one of the most widely used deep learning architectures for object detection and image classification. Although CNNs are a relatively recent development, they have largely surpassed earlier AI approaches for weed identification [3]. In the recent past, models such as You Only Look Once (YOLO) have gained immense popularity due to their capability of achieving real-time object detection. YOLO treats object detection as a regression problem, in which the entire image is input to the network and the locations of all objects and their corresponding class probabilities are output in real time. Recent advancements in YOLO, such as YOLOv3, YOLOv4, YOLOv5, YOLOv7, YOLOv8 and YOLOv11, have generally focused on enhancing the feature extraction, model structure, and the learning process [4,5]. With the release of YOLOv7, there has been a marked improvement in terms of accuracy as well as inference speed, which is important for practical agricultural applications [6].
Weed infestation is a major yield reducing factor in many farming systems. In broad-leaved crops such as cotton, weeds can be a major competitor to the crop for water, light and nutrients; therefore, potential large yield losses can occur. Current methods of weed control involve the broad-scale application of herbicides to attempt to control weeds in the whole crop area [1]. This results in higher pesticide usage, higher production costs, and greater environmental degradation [7]. Precision agriculture offers a solution in the form of site-specific weed control, where herbicides can be targeted only where weeds have been detected. An important component of the system is the ability to detect weeds using a UAV or by examination of aerial-derived imagery [8].
Wang et al. [6] proposed BA-YOLO, an improved YOLOv8-based object detection framework for complex satellite remote sensing imagery. The model integrates BiFPN to enhance multi-scale feature fusion and incorporates attention-based mechanisms to improve contextual feature representation. Evaluated on the DOTA dataset, BA-YOLO achieved an mAP of approximately 72.2%, showing the effectiveness of combining feature fusion and attention strategies for detecting complex targets in remote sensing imagery.
Wang et al. [7] developed CSCW-YOLOv7 for weed detection in complex wheat field environments where weeds and crops often have similar visual features. The model integrates CARAFE upsampling, SE attention modules, CoT blocks, and WIoU loss to improve feature extraction and localization accuracy, achieving 97.7% precision, 98.0% recall, and 94.4% mAP. Similarly, Hu et al. [9] proposed EL-YOLO to improve small-object detection in aerial imagery by introducing a high-resolution feature layer and an Efficient Spatial Pyramid Pooling (ESPP) module. Evaluated on the VisDrone and DIOR-VAS datasets, EL-YOLO achieved 45.2% mAP and 60.3% mAP, respectively, showing improved performance compared to baseline detectors.
Li et al. [10] proposed SOD-YOLO, an improved YOLOv8-based framework for small-object detection in UAV images. The model enhanced the backbone and neck using an RFCBAM module, an additional micro-small object detection head, and DySample upsampling to preserve fine spatial details during feature fusion. Evaluated on the VisDrone2019 and SODA-D datasets, SOD-YOLO-s achieved 42.0% mAP50 and 25.1% mAP50-95 on VisDrone2019, and 64.1% mAP50 and 32.0% mAP50-95 on SODA-D, outperforming baseline YOLOv8s. Despite recent progress, detecting weeds from UAV images remains challenging. Agricultural fields often contain complex backgrounds, varying illumination conditions, occlusion between crops and weeds, and significant visual similarity between plant species. These factors can reduce the accuracy of standard object detection models. Several studies have applied deep learning models to weed detection using UAV imagery, demonstrating promising results; however, many models still struggle with false positives, small-object detection, and generalization under varying field conditions [8,11]. Therefore, improving the detection capability of deep learning architectures remains an active research area. These challenges are consistent with recent studies that highlight the limitations of existing detection models in complex agricultural environments [12,13].
In this study, a modified YOLOv7-based framework was developed to improve weed detection performance in UAV imagery collected from cotton fields. Rather than introducing entirely new detection modules, this study focuses on adapting and integrating existing attention and multi-scale feature fusion strategies within the YOLOv7 framework to better address the challenges of UAV-based weed detection under complex agricultural field conditions. In our previous work, we evaluated three YOLOv7 variants, namely YOLOv7, YOLOv7-x, and YOLOv7-w6, for weed detection using UAV imagery collected from cotton fields. Among these, the baseline YOLOv7 model achieved the best overall detection performance with approximately 83% weed detection capability, followed by YOLOv7-x (77%) and YOLOv7-w6 (63%). Despite this performance, all models exhibited limitations in detecting small weed instances and differentiating weeds from visually similar crop structures under complex field conditions [14]. These limitations motivated the need for further architectural improvements. Prior remote sensing object detection studies have shown that integrating attention mechanisms and enhanced multi-scale feature fusion into YOLO-based frameworks can improve detection of small and complex targets under cluttered backgrounds [15]. Motivated by these findings, this study adapts similar design principles within a YOLOv7 framework for UAV-based weed detection in cotton fields.
The primary objective of this study is to improve the accuracy and reliability of weed detection in UAV-based precision agriculture for effective crop monitoring. To achieve this, we propose an enhanced version of the YOLOv7 network, named CB-YOLOv7, which is designed to better capture informative crop and weed features. The remainder of the paper is organized as follows: Section 2 describes the UAV dataset and presents the proposed CB-YOLOv7 architecture in detail. Section 3 reports the experimental results obtained from different models. Section 4 discusses the findings, and Section 5 concludes the paper.

2. Data and Methods

2.1. Data

2.1.1. Experimental Site and Data Acquisition

The dataset used in this study was collected from rainfed cotton fields located in Bushland, TX, USA (35.169734° N, 102.092734° W; elevation ≈ 1170 m) in the Texas Panhandle, a region characterized by a semi-arid climate with limited annual precipitation and strong seasonal variability. An overview of the experimental field site is shown in Figure 1.
Figure 1. Satellite view of the experimental field site located in Bushland, TX, USA.
The dominant soil type in the study area is Pullman clay loam, which has moderate water-holding capacity but is susceptible to cracking and surface crusting under dry conditions. Because the fields are rainfed and lack irrigation, crop growth and field conditions are largely influenced by natural rainfall patterns.
UAV imagery was captured using an Autel Robotics EVO II Dual 640T (Autel Robotics Co., Ltd., Shenzhen, China) [16] UAV equipped with an RGB camera under clear sky conditions during the cotton growing season. Flights were conducted at a low altitude to obtain high-resolution imagery suitable for crop and weed detection. A more detailed description of the experimental site, UAV flight configuration, and data acquisition procedures can be found in our previous study [14].

2.1.2. Data Processing

The initial dataset used in this study consisted of approximately 300 high-resolution UAV images collected from the field. A detailed description of the original dataset and the dataset can be found in our previously published dataset article [17]. To increase the number of training samples and improve the detection of small weed targets, these images were divided into smaller patches through a tiling process using a custom developed python script, resulting in a total of 9249 images. The tiling process was performed using non-overlapping image patches. Overlapping tiles were not applied in this study to avoid generating redundant samples that could increase computational cost and introduce repeated object representations during training. The selected patch size (585 × 438 pixels) was chosen to balance computational efficiency with sufficient spatial detail for detecting small weed instances. This size preserved local contextual information while increasing the relative visibility of weeds within UAV imagery, thereby improving small-object detection capability. All images were manually annotated using LabelImg software v1.8.1 to label two classes, namely weed and cotton, following the YOLO annotation format. These tiled and annotated images were used in our previous work to train different YOLOv7 variants, including YOLOv7, YOLOv7-w6, and YOLOv7-x [14].
For the current study, the dataset was further refined to improve its overall quality. All images were carefully reviewed, and those containing noise, redundant information, or no visible objects (empty images) were removed, resulting in a total of 7582 images. This step was important to ensure that the model is trained on meaningful data and to reduce the chances of learning irrelevant patterns.
In addition, the initial dataset showed a clear class imbalance, as the number of weed instances was much lower compared to cotton crop instances. To address this issue, data augmentation techniques were applied to improve the representation of weed samples and enhance model generalization. The outcome of the image after using the image augmentation approach is shown in Figure 2. Specifically, horizontal flipping and brightness adjustments (+10% and −10%) were used. Horizontal flipping helps simulate variations in image orientation that can occur during UAV flights, while brightness adjustments account for changes in lighting conditions due to sunlight and environmental factors. These simple yet effective augmentations were chosen to increase data diversity without altering the natural characteristics of the objects.
Figure 2. Representative of data augmentation applied to UAV imagery: (a) original image, (b) horizontal flip, (c) brightness increased (+10%), and (d) brightness decreased (−10%).
After applying these preprocessing and augmentation steps, the final dataset consisted of 8396 images, which were then split into training, validation, and testing sets using a 70:20:10 ratio, resulting in 5877 training images, 1763 validation images, and 756 test images, respectively. The class distribution of the dataset (Table 1) reflects the outcome of the refinement and augmentation process. In the initial dataset, weed instances were significantly fewer than cotton, accounting for weed 10.10% of the total annotations, whereas cotton represented 89.90%, indicating a strong class imbalance. After augmentation, the representation of weed samples improved, although cotton still remains the dominant class. This more balanced distribution helps the model better learn features of the minority class and improves overall detection performance.
Table 1. Distribution of annotated weed and cotton instances.

2.2. Methods

2.2.1. Base Framework

YOLOv7 is a one-stage object detection framework designed to achieve high accuracy while maintaining real-time detection speed. The architecture consists of three main components: a backbone, neck, and detection head, which together enable efficient feature extraction and multi-scale object detection. The backbone utilizes the Extended Efficient Layer Aggregation Network (E-ELAN) structure to improve feature learning and gradient flow through multiple convolution and aggregation layers. The neck aggregates features from different scales using a feature pyramid structure to enhance detection of objects of varying sizes [18]. Finally, the detection head predicts bounding boxes, objectness scores, and class probabilities at multiple scales, enabling robust detection performance across complex scenes. A detailed description of the YOLOv7 architecture can be found in our previous work [14].

2.2.2. Convolutional Block Attention Module (CBAM)

The CBAM is a lightweight attention mechanism that improves feature representation by sequentially applying channel attention and spatial attention to intermediate feature maps, as shown in Figure 3. By refining feature responses adaptively, CBAM enables the network to focus on the most informative regions while suppressing less relevant background features. This mechanism has been shown to improve performance in various computer vision tasks including image classification and object detection [19].
Figure 3. Convolutional Block Attention Mechanism. (a) Channel Attention Module. (b) Spatial Attention Module.
Given an intermediate feature map:
F   ∈   R C × H × W
where F denotes the input feature map, and   R C × H × W indicates that the feature map is defined in a real-valued space with channels C, height H and width W of the input data, respectively.
CBAM first applies a channel attention module to capture inter-channel dependencies. As illustrated in Figure 3a, the channel attention map is computed using global average pooling and global max pooling, followed by a shared multilayer perceptron (MLP):
M c F = σ M L P A v g P o o l F + M L P M a x P o o l F
where σ denotes the sigmoid activation function.
The refined feature map after channel attention is obtained as
F ′ = M c F ⊗ F
where ⊗ represents element-wise multiplication.
Next, the spatial attention module is applied to emphasize important spatial locations. As shown in Figure 3b, spatial attention is calculated by applying average pooling and max pooling along the channel dimension and concatenating the resulting feature maps:
M s F ′ = σ f 7 × 7 A v g P o o l F ′ ; M a x P o o l F ′
where f 7 × 7 denotes a convolution operation with a kernel size of 7 × 7, and [⋅;⋅] represents channel-wise concatenation. Finally, the refined output feature map is obtained as
F ″ = M s F ′ ⊗ F ′
By combining channel and spatial attention, CBAM allows the model to learn “what” and “where” to focus, improving detection performance. In practical applications, integrating CBAM into YOLO-based architectures has been shown to enhance detection accuracy, especially for small and indistinguishable targets, while maintaining computational efficiency [20].

2.2.3. Bidirectional Feature Pyramid Network (BiFPN)

The BiFPN is an advanced multi-scale feature fusion architecture designed to enhance object detection performance by enabling efficient information exchange across different feature levels. Unlike traditional FPN (Feature Pyramid Network) and PANet (Path Aggregation Network) structures, BiFPN introduces bidirectional feature fusion, allowing both top-down and bottom-up pathways to iteratively refine feature representations. This design improves the integration of high-level semantic information with low-level spatial details, which is critical for detecting objects of varying sizes, especially in complex environments such as UAV and remote sensing imagery [21].
In Figure 4, the difference between PANet and BiFPN lies in the structure of feature connections. Figure 3a introduces a bottom-up pathway to complement the top-down flow, but it still treats all feature inputs equally. In contrast, Figure 4b reorganizes the feature pyramid into a repeated bidirectional structure, where features are fused multiple times through both top-down (upsampling) and bottom-up (downsampling) pathways [21]. This design enables stronger propagation of both high-level semantic information and low-level spatial details, which is critical for detecting objects of varying sizes.
Figure 4. Comparison of PANet and BiFPN feature fusion architectures.
The BiFPN module combines the multi-scale feature maps output from the backbone network, namely, P 3 ,   P 4 ,   P 5 to perform the iterative fusion. The top-down path increases the spatial resolution of the high-level features by enlarging them and fusing them into the low-level features. The bottom-up path increases the feature consistency in the low-level and high-level features by shrinking the fused features and fusing them into the middle- and high-level features. Through the repeated bidirectional process, the network can retain the fine-grained information and enhance the semantic information between the different scales [22]. As shown in Figure 4b, the BiFPN module removes the nodes with only one input and introduces the direct cross-scale connections, which results in an efficient and compact network structure. The BiFPN block can be stacked in multiple times, and it can also be placed in the deep network without increasing too much computational cost [21].
A key innovation of BiFPN is the use of learnable weighted feature fusion, where each input feature contributes differently to the output based on its importance [6]. Instead of simple summation, BiFPN assigns trainable weights to each feature map, enabling adaptive feature selection during training. The fusion process can be expressed as:
O = Σ w i · I i Σ w i + ε
where O denotes fused output feature, I i represents the input feature maps, w i are learnable non-negative weights and ϵ is a small constant to ensure numerical stability [21].
In remote sensing and agricultural applications, such as crop and weed detection, objects often vary significantly in size and appearance. Because of this, standard feature fusion methods do not always capture small or closely packed targets effectively [23]. To overcome this limitation, the integration of BiFPN helps improve the interaction between features at different scales and reduces the loss of important information. Recent studies have also shown that using more advanced feature fusion techniques can significantly improve detection performance, especially in complex satellite and UAV imagery environments [6,22].

2.2.4. Proposed CB-YOLOv7 Architecture

YOLOv7 is a fast and effective real-time object detection model; however, its performance can be challenged when applied to complex UAV-based agricultural datasets such as ours. The dataset used in this study contains small, densely clustered weed patches that are visually similar to surrounding crops, along with variations in illumination and background complexity. These characteristics make it difficult for the model to capture fine-grained features and fully utilize multi-scale information, which can reduce detection performance. In our previous work, the baseline YOLOv7 model achieved approximately 83% weed detection accuracy [14], indicating reasonable performance but also highlighting the need to better adapt the model to the complexity of the dataset. Similar trends have been reported in the literature, where detection performance decreases under conditions of cluttered backgrounds, uneven lighting, and significant scale variation, all of which are common in UAV-based agricultural imagery [24].
These problems greatly limit the effectiveness of UAV-based intelligent agricultural weed detection systems. To address these limitations, this study proposes a new model, CB-YOLOv7, by introducing an attention mechanism and improving the feature fusion strategy of YOLOv7, thereby enhancing target-focused feature learning and multi-scale feature representation. Experimental results show that the improved model significantly enhances the detection of small, overlapping, and hard-to-distinguish weed samples in UAV-based intelligent agricultural weed detection, which is consistent with real field detection conditions [25].
As illustrated in Figure 5, the CBAM is incorporated into the backbone at multiple feature levels P 3 ,   P 4   a n d   P 5 . The motivation behind this modification is to improve the network’s ability to focus on relevant features while suppressing background noise. Improved connectivity between layers allows the model to better preserve and utilize features during training [26]. Specifically, CBAM is applied to intermediate feature maps, where channel attention and spatial attention are sequentially used to refine feature representation [19]. This allows the model to emphasize important channel-wise and spatial information, thereby improving feature discrimination in complex scenes [25]. Similar integration of attention mechanisms into YOLO-based models has been reported to enhance detection of accuracy in agricultural applications [6,7,9,10].
Figure 5. CB-YOLOv7 Algorithm structure diagram.
To further improve multi-scale feature learning, the conventional PANet structure in YOLOv7 is replaced with a BiFPN in the neck. The motivation for this replacement is that PANet performs uniform feature aggregation, which may not effectively capture the relative importance of features at different scales [21]. In contrast, BiFPN introduces learnable weighted feature fusion, enabling adaptive importance assignment across feature levels. The fusion process is defined as:
F i = Σ j w j ε + Σ k w k · F j
where w j are learnable non-negative weights, F j means the input feature map coming from the j-th scale or branch, w k is the learned importance weight of the k-th feature, and ϵ is a small constant for numerical stability. This formulation allows the network to prioritize more informative features while reducing the influence of less relevant ones, thereby improving cross-scale information propagation and detection robustness.
The detection head remains consistent with YOLOv7, utilizing refined feature maps P 3 ,   P 4 ,   P 5 for multi-scale prediction. By combining CBAM-based feature refinement in the backbone and BiFPN-based adaptive feature fusion in the neck, the proposed CB-YOLOv7 effectively improves both feature extraction and multi-scale representation. As a result, the model achieves enhanced detection performance for small, overlapping, and visually complex targets while maintaining computational efficiency suitable for real-time applications.

2.2.5. Models and Parameters

In this study, multiple YOLOv7-based models were implemented to evaluate the effectiveness of architectural modifications for weed detection using UAV imagery. In our previous work, the baseline YOLOv7 model was applied to the same dataset and achieved a weed detection accuracy of approximately 83% [14]. While this result demonstrated the capability of YOLOv7 for agricultural applications, it also revealed certain limitations when dealing with complex UAV imagery, including difficulty in detecting small weed instances and confusion between weeds and visually similar crop structures.
Building on this, three models were considered in the present study: (i) YOLOv7-CBAM, (ii) YOLOv7-BiFPN, and (iii) the proposed CB-YOLOv7, which integrates both CBAM and BiFPN into a unified framework. The baseline YOLOv7 model was retained as a reference due to its strong balance between detection accuracy and real-time performance, as well as its demonstrated effectiveness in agricultural applications [24].
To address these challenges, due to small object size, class imbalance, and high visual similarity between crops and weeds, the first modification involved incorporating the CBAM into the YOLOv7 backbone, resulting in the YOLOv7-CBAM model. The rationale behind this modification was to enhance feature extraction by enabling the network to focus more effectively on informative channel and spatial features, thereby improving detection performance in complex and cluttered environments [19].
The second modification focused on improving multi-scale feature fusion. In the standard YOLOv7 architecture, the PANet structure aggregates features uniformly, which may not fully capture the relative importance of features across different scales. Therefore, the YOLOv7-BiFPN model replaces PANet with a BiFPN. BiFPN introduces learnable weights and bidirectional connections, allowing adaptive feature aggregation and more effective propagation of both high-level semantic and low-level spatial information, which is particularly important for detecting small and densely distributed weed targets [21].
Finally, the proposed CB-YOLOv7 model combines both modifications by integrating CBAM into the backbone and replacing PANet with BiFPN in the neck. This combined approach was designed to simultaneously improve feature representation and multi-scale feature fusion. By building upon the findings of our previous work and systematically introducing these modifications, the proposed model aims to achieve improved detection performance, particularly for small, overlapping, and visually complex targets commonly observed in UAV-based agricultural imagery. The key architectural differences and corresponding improvements among the baseline and modified YOLOv7 models are summarized in Table 2.
Table 2. Comparative Summary of Baseline and Modified YOLOv7 Models.
YOLOv7 was selected as the baseline architecture in this study because of its strong balance between detection accuracy and real-time inference performance, which makes it suitable for UAV-based agricultural applications. In our previous work [14], YOLOv7 demonstrated effective weed detection capability in cotton fields; however, some limitations were observed under complex field conditions, particularly when weeds were small, densely distributed, partially occluded, or visually similar to surrounding crops. These challenges suggested that the baseline model could benefit from improved feature representation and enhanced multi-scale feature fusion. Therefore, the proposed CB-YOLOv7 architecture was developed by integrating CBAM and BiFPN into YOLOv7 to address these limitations and improve weed detection robustness in UAV imagery.
All YOLOv7-based models were trained under the same experimental settings to ensure a fair comparison among the modified architectures. The detailed training hyperparameters, including optimizer, learning rate, momentum, weight decay, pretrained weights, number of epochs, batch size, and workers, are summarized in Table 3, while the hardware and software specifications used in this study are presented in Table 4. By maintaining the same training configuration across all experiments, performance differences can be mainly attributed to the proposed architectural modifications rather than variations in hyperparameter tuning.
Table 3. Parameters used for training weed detection models.
Table 4. Operational Environment.
The performance of the models was evaluated using standard object detection metrics, including precision, recall, F1-score, and mAP. These metrics provide a comprehensive assessment of detection accuracy and localization performance. The detailed definitions and formulations of these evaluation metrics can be found in our previous work [14].

3. Results

Weed detection plays an important role in precision agriculture, as it enables targeted weed management and helps reduce excessive herbicide use. With the advancement of deep learning, especially YOLO-based object detection models, significant improvements have been achieved in detecting weeds from UAV imagery due to their ability to handle complex visual patterns and perform real-time detection. However, accurately identifying weeds in real field conditions remains challenging because of small object size, dense distribution, and strong visual similarity between crops and weeds [27].
In our earlier research, we used the same dataset and found that the basic YOLOv7 model was able to detect weeds with an accuracy of 83%. It also gave us good results for precision, recall, and mAP values, as shown in reference [14]. These results showed that YOLOv7 is a good choice for farming applications, but they also highlighted some problems. For example, the model struggled to detect small and complicated weeds under difficult field conditions.
In the present study, with improved data preprocessing, dataset refinement, and the introduction of modified architectures (YOLOv7-CBAM, YOLOv7-BiFPN, and the proposed CB-YOLOv7), the detection performance was re-evaluated. The results show that the proposed modifications improve the model’s ability to capture discriminative features and enhance multi-scale feature representation, leading to better performance in detecting small, overlapping, and visually complex weed targets in UAV-based agricultural environments.
Table 5 presents a quantitative performance comparison of the baseline YOLOv7 and the modified YOLOv7 models. The baseline YOLOv7 result was taken from our previous work [14]. In the present study, this baseline result was used as a reference, while the refined dataset was used to train and evaluate the modified YOLOv7-based models. The baseline YOLOv7 achieves the highest precision, indicating a lower rate of false positive detections, but its lower recall suggests that some weed instances may still be missed [14]. The per-class AP values also show that cotton was detected more reliably than weeds, which is expected because cotton had a larger number of annotated instances in the dataset. The YOLOv7-CBAM model achieves higher recall, indicating its improved ability to detect weed instances, particularly in cluttered backgrounds. However, although YOLOv7-CBAM improved recall, its overall mAP@0.5 was slightly lower than the baseline YOLOv7 reported in our previous study. Therefore, CBAM alone did not improve the overall detection performance. Instead, its main benefit was improving attention to relevant weed features, which helped detect more weed instances but did not fully improve overall precision–recall balance when used independently. In contrast, the YOLOv7-BiFPN model demonstrates relatively high precision, suggesting a reduction in false positive detections due to improved multi-scale feature fusion through learnable weighted connections [21]. However, its lower recall and weed AP indicate that some weed instances, especially small or visually similar ones, were still difficult to detect.
Table 5. Performance comparison of baseline YOLOv7 reference and modified YOLOv7 models.
The proposed CB-YOLOv7 model achieves the most balanced performance, with the highest F1-score and mAP values among all models. Compared to the baseline YOLOv7, the F1-score improves from 0.82 to 0.84, while the mAP@0.5:0.95 increases from 0.50 to 0.55, representing an improvement of about 5%. Compared to YOLOv7-CBAM, the mAP@0.5 [28] increases from 0.86 to 0.89, representing an improvement of approximately 3%, while compared to YOLOv7-BiFPN, the improvement is about 6%. Similarly, the mAP@0.5:0.95 [28] improves from 0.48 in YOLOv7-CBAM and 0.45 in YOLOv7-BiFPN to 0.55 in CB-YOLOv7. The model also maintains a balanced precision and recall, resulting in the highest F1-score. The per-class AP results further show that CB-YOLOv7 improved weed AP compared with the other modified models, while also maintaining strong cotton detection performance. These improvements are mainly due to the combined effect of enhanced feature refinement and more effective multi-scale feature fusion. As a result, the proposed model performs better in detecting small, overlapping, and visually complex weed instances in UAV imagery.
In addition to detection performance, the computational complexity and inference efficiency of the evaluated models were also analyzed to better understand the trade-off between model accuracy and computational cost. The comparison of parameters, FLOPs, inference time, and model size is presented in Table 6.
Table 6. Computational complexity and inference performance comparison of YOLOv7-based models.
Table 6 presents the computational complexity and inference performance of the evaluated models. The baseline YOLOv7 achieved the fastest inference speed and lowest computational cost, while the modified models increased parameter count and FLOPs due to the addition of attention and feature fusion modules. Among the modified architectures, CB-YOLOv7 achieved improved overall detection performance while maintaining lower computational complexity than YOLOv7-CBAM, suggesting a more balanced trade-off between detection capability and inference efficiency.
Figure 6 shows the precision–recall (PR) curves for the models used in this study. The PR curve helps illustrate how precision and recall change with different confidence thresholds, giving a clearer picture of overall detection performance [23]. In general, a curve that stays closer to the top-right corner indicates better performance, as it means the model can detect more true instances while keeping false detections low. From Figure 6a, the baseline YOLOv7 model demonstrates strong performance for cotton detection, while weed detection shows a noticeable decline in precision at higher recall levels, indicating challenges in accurately identifying smaller or less distinct weed instances. In Figure 6b, the YOLOv7-CBAM model improves feature representation through attention mechanisms, resulting in more stable precision for weed detection compared to the baseline, although some degradation is still observed at higher recall levels. Figure 6c shows that the YOLOv7-BiFPN model enhances multi-scale feature fusion; however, the weed detection curve still drops more sharply, suggesting that certain complex or overlapping weed instances remain difficult to detect consistently. In contrast, the proposed CB-YOLOv7 model in Figure 6d exhibits a PR curve that remains closer to the top-right region for both weed and cotton classes, indicating improved balance between precision and recall. The smoother and more stable curve for weed detection suggests that the combined use of attention mechanisms and bidirectional feature fusion enhances the model’s ability to capture small and visually similar targets under complex field conditions. Overall, the proposed model demonstrates more consistent and robust detection performance compared to the individual modifications applied in isolation.
Figure 6. Precision–Recall (PR) curves for (a) YOLOv7 (b) YOLOv7-CBAM, (c) YOLOv7-BiFPN, and (d) CB-YOLOv7.
Figure 7 shows the confusion matrices for YOLOv7, YOLOv7-CBAM, YOLOv7-BiFPN, and the proposed CB-YOLOv7 models, highlighting their performance in weed detection. A confusion matrix provides a detailed comparison between predicted and actual classes, allowing evaluation of correct detections and different types of prediction errors such as false positives and false negatives. The baseline YOLOv7 model achieved a weed detection accuracy of 0.83, with approximately 0.15 missed weed instances. The YOLOv7-CBAM model achieved a weed detection accuracy of 0.82 with approximately 0.17 missed detections, while the YOLOv7-BiFPN model showed a weed detection accuracy of 0.79 with approximately 0.21 missed detections. The proposed CB-YOLOv7 model achieved the highest weed detection accuracy of 0.88 while reducing missed weed instances to approximately 0.12. These observations suggest that the combined use of attention and feature fusion strategies may improve the model’s ability to distinguish weed instances under the current experimental conditions.
Figure 7. Confusion matrices for YOLOv7 baseline model and three modified YOLOv7 models.
Figure 8 presents a visual comparison between the ground truth annotations and the detection results of the YOLOv7, YOLOv7-CBAM, YOLOv7-BiFPN, and the proposed CB-YOLOv7 models across representative test images. The ground truth images illustrate the manually annotated weed and cotton instances, where red rectangles represent weed and green rectangles represent cotton, while the subsequent rows show the corresponding predictions from each model. From the comparison, the baseline YOLOv7 model demonstrates reasonable detection performance but exhibits missed detections and confusion in cluttered regions. The YOLOv7-CBAM model improves feature representation, leading to better identification of weed instances, although some missed detections and false positives remain. The YOLOv7-BiFPN model shows improved localization across varying object scales; however, it still struggles with smaller or less distinct weed instances. In contrast, the proposed CB-YOLOv7 model provides more consistent and accurate detections, capturing a greater number of weed instances while reducing both missed detections and false positives.
Figure 8. Example images from the test dataset to show the detection accuracy of the models.
Overall, the visual results indicate that the proposed model achieves better alignment with ground truth annotations, particularly in challenging scenarios involving small, overlapping, and densely distributed weed patches.

4. Discussion

This study was motivated by the need to improve weed detection in real-field agricultural environments using UAV imagery, where traditional approaches often fail due to the complexity of field conditions, small target sizes, and low image quality. The UAV imagery used in this work was collected from rainfed cotton fields in the Texas Panhandle, a region characterized by variable soil conditions, limited rainfall, and heterogeneous crop growth patterns. These factors create a challenging environment for automated detection systems, as weed instances are often small, densely clustered, and visually similar to surrounding crops. As observed in previous studies, such conditions significantly affect the performance of deep learning–based detection models and limit their practical applicability in precision agriculture [24,27]. To address these challenges, this study focused not only on improving model architecture but also on refining the dataset and adapting the detection framework to better represent real-field variability. The dataset was carefully processed by removing noisy and irrelevant samples and applying targeted augmentation techniques to improve class balance and generalization. This step was essential because model performance in agricultural applications is highly dependent on data quality and representation [29]. Similar observations have been reported in recent studies, where dataset refinement and augmentation significantly improved detection performance in UAV-based weed detection tasks [30].
The results of this study suggest that integrating attention mechanisms with advanced multi-scale feature fusion may improve weed detection performance in complex UAV-based agricultural environments. Under the current experimental setting, the proposed CB-YOLOv7 model showed more balanced overall performance compared to the individual modifications. The observed improvement may be attributed to the complementary roles of CBAM and BiFPN, where CBAM helps emphasize informative weed-related features and BiFPN improves feature exchange across different scales. These characteristics are particularly important for detecting small, overlapping, and visually similar weed instances under challenging field conditions. Similar observations have also been reported in recent agricultural detection studies, where combining architectural enhancements improved localization performance and robustness in UAV imagery [23,31].
From a real-world deployment perspective, the proposed CB-YOLOv7 framework could support UAV-based precision spraying systems and agricultural decision-support tools. Accurate weed localization from UAV imagery may enable site-specific herbicide application, reducing unnecessary chemical usage and minimizing environmental impact. In addition, the generated weed distribution maps could assist farmers and agricultural managers in monitoring weed infestation patterns and making timely field management decisions.
One important contribution of this study is the integration of dataset refinement with model-level modifications. In addition to improving the model architecture, the dataset was carefully refined by removing noisy and empty images and applying augmentation techniques such as horizontal flipping and brightness adjustment. These augmentation methods were selected to improve class representation while preserving the natural field appearance and authenticity of UAV imagery. The results suggest that improving both data quality and model architecture is important for achieving reliable weed detection in real agricultural environments [25,32]. Although the individual contributions of dataset refinement and architectural modification were not separately quantified in this study, the combined improvements produced more stable and balanced detection performance under complex field conditions. This suggests that both data quality and feature-learning capability play important roles in UAV-based weed detection.
Despite the improvements achieved by the proposed model, some limitations still remain. First, the dataset continues to exhibit class imbalance, with fewer weed instances compared to cotton, which may still affect model learning and weed recall performance. Although horizontal flipping and brightness adjustment helped reduce this issue to some extent, the imbalance was not completely eliminated. Future work will therefore focus on collecting additional field data containing more weed samples to improve class balance, model generalization, and detection robustness under diverse agricultural conditions. Second, repeated training runs with different random seeds were not performed in this study. Although all models were trained and evaluated using the same dataset split and training configuration, the stability of the observed performance differences was not assessed through variance analysis, confidence intervals, or statistical testing. Therefore, the improved performance of CB-YOLOv7 should be interpreted as an improvement under the current experimental setting rather than statistically confirmed superiority. Future work will include repeated experiments with multiple random seeds to evaluate the robustness and statistical reliability of model performance.
In addition, this study used only RGB imagery, which may not fully capture spectral differences between crops and weeds. Incorporating multispectral or hyperspectral UAV imagery could provide additional discriminatory information for improving classification performance [1,33]. Another limitation is that the current model was evaluated using imagery from a specific field environment. Although the proposed approach performed well under the conditions used in this study, additional testing across different locations, seasons, soil backgrounds, crop growth stages, and weed species would be necessary to confirm broader generalizability.
Overall, the findings of this study demonstrate that combining data-driven refinement with targeted architectural improvements provides an effective approach for improving weed detection in UAV-based precision agriculture. The proposed CB-YOLOv7 framework achieved more reliable and balanced detection performance while maintaining suitability for real-world agricultural applications such as site-specific weed management and automated weed control systems [34].

5. Conclusions

This study developed CB-YOLOv7, a modified YOLOv7-based framework, to improve weed detection in UAV imagery collected from rainfed cotton fields. The main contribution of this work is the adaptation and evaluation of CBAM-based attention, BiFPN-based multi-scale feature fusion, and dataset refinement within the YOLOv7 framework to address common challenges in agricultural imagery, including small weed size, crop–weed visual similarity, overlapping vegetation, and complex field backgrounds.
The key findings show that the proposed CB-YOLOv7 model provides a better balance between precision and recall than the individual modifications. CBAM helped the model focus more effectively on informative weed-related features, while BiFPN improved the use of features across different scales. When combined, these two components improved the model’s ability to detect weeds more consistently under difficult field conditions. This study also highlights the importance of data quality in UAV-based deep learning applications. Removing noisy and empty images and applying targeted augmentation helped improve the training dataset while preserving realistic field conditions. However, class imbalance remains a limitation, and future work should include collecting additional field data with more weed samples across different growth stages and field conditions.
Beyond model performance, this work provides a foundation for developing field-level weed mapping systems using UAV imagery. The improved detection output can be further converted into spatial weed distribution information, which may help identify weed-prone zones and guide future field scouting or management planning. In this way, the proposed framework contributes not only to automated detection but also to the broader goal of data-driven crop management in cotton production systems.
Overall, the proposed CB-YOLOv7 framework shows promising potential for UAV-based weed detection in cotton fields. However, further validation using larger and more diverse datasets from different locations, seasons, growth stages, planting densities, and lighting conditions is needed before broader robustness and practical deployment can be confirmed.

Author Contributions

Conceptualization, Y.Y. and V.H.S.; methodology, Y.Y. and V.H.S.; software, A.D.; validation, A.D., Y.Y. and V.H.S.; formal analysis, A.D.; investigation, A.D.; resources, Y.Y.; data curation, V.H.S.; writing—original draft preparation, A.D.; writing—review and editing, A.D., Y.Y. and V.H.S.; visualization, A.D.; supervision, Y.Y. and V.H.S.; project administration, Y.Y. and V.H.S.; funding acquisition, Y.Y. and V.H.S. All authors have read and agreed to the published version of the manuscript.

Funding

This research is funded by the United States Department of Agriculture (USDA)—National Institute of Food and Agriculture (NIFA), Grant No. 2023-67014-39637.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The dataset is available in Mendeley Data at https://doi.org/10.17632/6nc2sbsphs.1 (Direct URL is https://data.mendeley.com/datasets/6nc2sbsphs/1 (accessed on 1 April 2026)). The trained YOLOv7 models’ weights are available in Mendeley data at https://doi.org/10.17632/c7r4w7sttr.1 (Direct URL is https://data.mendeley.com/datasets/c7r4w7sttr/1 (accessed on 1 April 2026)).

Acknowledgments

We gratefully acknowledge the contributions of all the student workers, as well as field and technical staff who assisted with data collection and processing. We also thank Nathan Howell, the PI, for his support and collaboration during this project. The views and conclusions contained in this material are those of the authors and should not be interpreted as representative of the official policies or endorsements of the USDA or the U.S. Government. We also gratefully acknowledge the computation resources provided by WTAMU HPC cluster, which was funded by the National Science Foundation (NSF CC* GROWTH 2018841).

Conflicts of Interest

The authors declare no conflicts of interest.

Abbreviations

The following abbreviations are used in this manuscript:
UAVUnmanned Aerial Vehicle
YOLOYou Only Look Once
CNNConvolutional Neural Network
BiFPNBidirectional Feature Pyramid Network
CBAMConvolutional Block Attention Module
PANetPath Aggregation Network
FPNFeature Pyramid Network
mAPMean Average Precision

References

  1. Kamilaris, A.; Prenafeta-Boldú, F.X. Deep learning in agriculture: A survey. Comput. Electron. Agric. 2018, 147, 70–90. [Google Scholar] [CrossRef] [Scilit]
  2. Liakos, K.G.; Busato, P.; Moshou, D.; Pearson, S.; Bochtis, D. Machine learning in agriculture: A review. Sensors 2018, 18, 2674. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  3. Gerhards, R.; Andújar Sanchez, D.; Hamouz, P.; Peteinatos, G.G.; Christensen, S.; Fernandez-Quintanilla, C. Advances in site-specific weed management in agriculture—A review. Weed Res. 2022, 62, 123–133. [Google Scholar] [CrossRef] [Scilit]
  4. Redmon, J.; Divvala, S.; Girshick, R.; Farhadi, A. You only look once: Unified, real-time object detection. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition; IEEE: New York, NY, USA, 2016; pp. 779–788. [Google Scholar]
  5. Bochkovskiy, A.; Wang, C.-Y.; Liao, H.-Y.M. YOLOv4: Optimal speed and accuracy of object detection. arXiv 2020, arXiv:2004.10934. [Google Scholar] [CrossRef] [Scilit]
  6. Wang, K.; Liu, Z. BA-YOLO for Object Detection in Satellite Remote Sensing Images. Appl. Sci. 2023, 13, 13122. [Google Scholar] [CrossRef] [Scilit]
  7. Wang, K.; Hu, X.; Zheng, H.; Lan, M.; Liu, C.; Liu, Y.; Zhong, L.; Li, H.; Tan, S. Weed detection and recognition in complex wheat fields based on an improved YOLOv7. Front. Plant Sci. 2024, 15, 1372237. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  8. Sa, I.; Chen, Z.; Popović, M.; Khanna, R.; Liebisch, F.; Nieto, J.; Siegwart, R. weedNet: Dense semantic weed classification using multispectral images and MAV for smart farming. IEEE Robot. Autom. Lett. 2017, 3, 588–595. [Google Scholar] [CrossRef] [Scilit]
  9. Hu, M.; Li, Z.; Yu, J.; Wan, X.; Tan, H.; Lin, Z. Efficient-Lightweight YOLO: Improving Small Object Detection in YOLO for Aerial Images. Sensors 2023, 23, 6423. [Google Scholar] [CrossRef] [Scilit]
  10. Li, Y.; Li, Q.; Pan, J.; Zhou, Y.; Zhu, H.; Wei, H.; Liu, C. SOD-YOLO: Small-Object-Detection Algorithm Based on Improved YOLOv8 for UAV Images. Remote Sens. 2024, 16, 3057. [Google Scholar] [CrossRef] [Scilit]
  11. Dos Santos Ferreira, A.; Freitas, D.M.; da Silva, G.G.; Pistori, H.; Folhes, M.T. Weed detection in soybean crops using ConvNets. Comput. Electron. Agric. 2017, 143, 314–324. [Google Scholar] [CrossRef] [Scilit]
  12. Hasan, A.M.; Diepeveen, D.; Laga, H.; Jones, M.G.; Sohel, F. Object-level benchmark for deep learning-based detection and classification of weed species. Crop Prot. 2024, 177, 106561. [Google Scholar] [CrossRef] [Scilit]
  13. Faizan Zeb, M.; Iqbal, A.; Husnain, G.; Zafar, W.; Junaid, A.; Alzahrani, A.S.; Bukhari, S.H.R.; Naidu, R.S. Automated weed monitoring and control: Enhancing detection accuracy using a YOLOv7-AlexNet fusion network. Front. Plant Sci. 2025, 16, 1664650. [Google Scholar] [CrossRef] [Scilit]
  14. Das, A.; Yang, Y.; Subburaj, V.H. YOLOv7 for Weed Detection in Cotton Fields Using UAV Imagery. AgriEngineering 2025, 7, 313. [Google Scholar] [CrossRef] [Scilit]
  15. Wang, G.; Chen, Y.; An, P.; Hong, H.; Hu, J.; Huang, T. UAV-YOLOv8: A small-object-detection model based on improved YOLOv8 for UAV aerial photography scenarios. Sensors 2023, 23, 7190. [Google Scholar] [CrossRef] [Scilit]
  16. Available online: https://www.autelrobotics.com/productdetail/evo-ii-dual-640t-drones/ (accessed on 15 July 2024).
  17. Das, A.; Subburaj, V.H.; Yang, Y.; Bednarz, C.W. A UAV image dataset for object detection with annotations generated using LabelImg and Roboflow. Data Brief 2026, 65, 112483. [Google Scholar] [CrossRef] [Scilit]
  18. Wang, C.-Y.; Bochkovskiy, A.; Liao, H.-Y.M. YOLOv7: Trainable Bag-of-Freebies Sets New State-of-the-Art for Real-Time Object Detectors. In Proceedings of the 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), Vancouver, BC, Canada, 17–24 June 2022. [Google Scholar]
  19. Woo, S.; Park, J.; Lee, J.Y.; Kweon, I.S. CBAM: Convolutional Block Attention Module. In Proceedings of the European Conference on Computer Vision (ECCV); Springer: Berlin/Heidelberg, Germany, 2018; pp. 3–19. [Google Scholar]
  20. Thakuria, A.; Erkinbaev, C. Improving the Network Architecture of YOLOv7 to Achieve Real-Time Grading of Canola based on Kernel Health. Smart Agric. Technol. 2023, 5, 100300. [Google Scholar] [CrossRef] [Scilit]
  21. Tan, M.; Pang, R.; Le, Q.V. EfficientDet: Scalable and Efficient Object Detection. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition; IEEE: Seattle, WA, USA, 2020; pp. 10781–10790. [Google Scholar]
  22. Yao, Z.; Wan, F.; Lei, G.; Xu, L. Maritime Ship Target Detection Based on Proved YOLOV7 Algorithm. In 2023 3rd International Conference on Computer Science, Electronic Information Engineering and Intelligent Control Technology (CEI); IEEE: New York, NY, USA, 2023; pp. 463–468. [Google Scholar]
  23. Li, S.; Chen, Z.; Xie, J.; Zhang, H.; Guo, J. PD-YOLO: A novel weed detection method based on multi-scale feature fusion. Front. Plant Sci. 2025, 16, 1506524. [Google Scholar] [CrossRef] [Scilit]
  24. Gallo, I.; Rehman, A.U.; Dehkordi, R.H.; Landro, N.; La Grassa, R.; Boschetti, M. Deep object detection of crop weeds: Performance of YOLOv7 on a real case dataset from UAV images. Remote Sens. 2023, 15, 539. [Google Scholar] [CrossRef] [Scilit]
  25. Peng, M.; Zhang, W.; Li, F.; Xue, Q.; Yuan, J.; An, P. Weed detection with improved Yolov 7. EAI Endorsed Trans. Internet Things 2023, 9, e1. [Google Scholar] [CrossRef] [Scilit]
  26. Huang, G.; Liu, Z.; Van Der Maaten, L.; Weinberger, K.Q. Densely connected convolutional networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition; IEEE: New York, NY, USA, 2017; pp. 4700–4708. [Google Scholar]
  27. Upadhyay, A.; Sunil, G.C.; Das, S.; Mettler, J.; Howatt, K.; Sun, X. Multiclass weed and crop detection using optimized YOLO models on edge devices. J. Agric. Food Res. 2025, 22, 102144. [Google Scholar] [CrossRef] [Scilit]
  28. Yang, Y.; Yang, S.; Chan, Q. LEAD-YOLO: A lightweight and accurate network for small object detection in autonomous driving. Sensors 2025, 25, 4800. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  29. Tong, Z.; Chen, Y.; Xu, Z.; Yu, R. Wise-IoU: Bounding Box Regression Loss with Dynamic Focusing Mechanism. arXiv 2023, arXiv:2301.10051. [Google Scholar]
  30. Li, J.; Zhang, W.; Zhou, H.; Yu, C.; Li, Q. Weed detection in soybean fields using improved YOLOv7 and evaluating herbicide reduction efficacy. Front. Plant Sci. 2024, 14, 1284338. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  31. Gao, X.; Wang, G.; Qi, J.; Liu, J.; Chen, S.; Scobie, M. Intelligent laser weeding system based on improved YOLOv7–improved DeepLabv3+ fusion model and adaptive power regulation. Comput. Electron. Agric. 2026, 240, 111180. [Google Scholar] [CrossRef] [Scilit]
  32. Zhao, H.; Wang, Y. Deep learning–based approaches for weed detection in crops. Front. Plant Sci. 2025, 16, 1746406. [Google Scholar] [CrossRef] [Scilit]
  33. Gopalakrishnan, K.; Sivaraj, R.; Vijayakumar, M. Automated weed and crop recognition and classification model using deep transfer learning with optimization algorithm. Sci. Rep. 2025, 15, 29279. [Google Scholar] [CrossRef] [Scilit]
  34. Xu, Y.; Liu, Z.; Li, J.; Huang, D.; Chen, Y.; Zhou, Y. Real-time detection and localization of weeds in Dictamnus dasycarpus fields for laser-based weeding control. Agronomy 2024, 14, 2363. [Google Scholar] [CrossRef] [Scilit]
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.