Abstract
To address the challenges of high labor intensity, low efficiency, and growing labor shortages in Morchella harvesting, this paper proposes the YOLO-CAS algorithm and develops a corresponding maturity detection system. Built upon the YOLOv8s architecture, the proposed model integrates the Convolutional Block Attention Module (CBAM) and Alterable Kernel Convolution (AKConv) while replacing the CIoU loss function with SIoU. These enhancements prioritize the refinement of feature extraction and selection for key Morchella characteristics, providing a robust algorithmic core for the detection system. The specific technical improvements are threefold: (1) CBAM modules are integrated into the three C2f-to-Detect coupling interfaces and the multi-scale output paths of the neck; (2) AKConv is embedded into the C2f structure at the end of the backbone prior to the SPPF module; and (3) the original CIoU is substituted with the SIoU loss function. Experimental results demonstrate that the refined model’s precision increased from 0.847 to 0.939, recall rose from 0.761 to 0.867, mAP50 improved from 0.853 to 0.927, and mAP50:95 advanced from 0.531 to 0.599, alongside a boost in inference speed. Furthermore, a deployment system with a streamlined and intuitive interface was developed using PyQt5. This system offers high flexibility and scalability, effectively meeting the practical demands of diverse agricultural environments.
1. Introduction
Morchella, commonly known as morels, represents a category of precious fungi valued for both culinary and medicinal purposes. The name is derived from the uneven, honeycomb-like surface of the pileus, which resembles a sheep’s stomach [1,2,3]. In Europe, morels are ranked second only to truffles in gastronomic importance; they are regarded as the premier edible mushroom in North America and celebrated as the “meat among vegetables” in China [4]. Morels possess exceptional nutritional value, containing 18 amino acids [5] along with abundant vitamins and minerals [6], while their iron and zinc levels are 31 and 4.3 times those of shiitake mushrooms, respectively [7]. Additionally, they offer health benefits such as aiding digestion, enhancing immunity, alleviating fatigue, and inhibiting tumors [8,9].
Morels generally mature between February and April each year, characterized by asynchronous maturation and a brief harvest cycle [10,11]. Currently, the harvesting process relies heavily on manual labor [12]. The average daily yield per worker is less than 50 kg, resulting in high labor costs. Furthermore, improper handling can damage the fruiting bodies, leading to substantial direct economic losses annually [13].To address the edible fungi industry’s issues of excessive reliance on human resources, low efficiency, and exorbitant costs, the development of intelligent harvesting is urgently needed [14,15].
To drive agricultural intelligence forward and reduce both production costs and industrial losses, we propose YOLO-CAS, built upon YOLOv8s. Field environments are highly complex, characterized by cluttered backgrounds and varying target scales. To address this, we introduce the Convolutional Block Attention Module (CBAM) at the terminals of the three C2f modules connecting to the Detect layer within the YOLOv8s neck. This integration leverages the multi-scale structure to accommodate targets of diverse sizes while utilizing CBAM to dually calibrate features at each scale, thereby enhancing the precision of Morchella feature discrimination and localization. Furthermore, Morchella caps feature irregular, reticulate ridges [16]. To improve the recognition of complex geometric features—such as non-rigid edges and bumpy surfaces—we embed the Alterable Kernel Convolution (AKConv) module into the C2f structure at the end of the backbone, just before the SPPF module. Equipped with convolutional kernels that dynamically adjust sampling point locations, AKConv enables the network to adaptively focus on these intricate geometric traits, capturing the intrinsic patterns of their morphological structures with greater accuracy. Originally, YOLOv8s employs CIoU Loss for bounding box prediction. While CIoU accounts for the aspect ratio between predicted and ground-truth boxes, it overlooks the issue of complex angles within the training data. Therefore, we replace CIoU with SIoU. By considering the vector angle between desired regressions, SIoU redefines the angle penalty metric. This allows the predicted box to rapidly drift toward the nearest axis, after which only a single coordinate requires regression, effectively reducing the total degrees of freedom. Finally, we developed a Human–Machine Interface (HMI) that consolidates operation controls and result displays, balancing operational convenience with informational clarity.
The remainder of this paper is organized as follows: Section 2 reviews related work on YOLO-based object detection and intelligent agricultural harvesting. Section 3 details the methodology of YOLO-CAS, encompassing its network architecture and module design. Section 4 presents the experimental results, including both ablation studies and comparative evaluations. Finally, Section 5 concludes the paper and outlines directions for future research.
2. Related Work
2.1. Development of YOLO Object Detection
In recent years, Convolutional Neural Networks (CNNs) have emerged as the dominant models in deep learning, gradually superseding traditional feature extraction methods due to their superior representation capabilities [17,18]. As research progresses, the performance of mainstream object detectors has demonstrated a steady upward trajectory. However, during network optimization, researchers have observed that merely increasing network width or depth does not directly or efficiently enhance model performance. On the contrary, such simplistic stacking often triggers a series of issues, including a significant rise in computational complexity, a tendency toward overfitting during training, and gradient divergence inherent in deep architectures—all of which severely restrict further breakthroughs in network performance [19].
To address these challenges, Szegedy et al. proposed an innovative solution within the design of GoogLeNet. By introducing the Inception module, they fused convolutional and pooling layers of different sizes, enhancing the network’s adaptability to various scenarios through multi-scale feature extraction. Concurrently, to mitigate model complexity, the team incorporated 1 × 1 convolutional kernels to effectively compress feature map dimensions, substantially reducing parameter count and computational costs. This design philosophy of balancing performance and efficiency not only yielded excellent experimental results at the time but also laid a crucial foundation for the subsequent development of lightweight CNNs [20].
Prior to the advent of YOLO models [21], mainstream object detection algorithms primarily utilize a “two-stage” paradigm: generating region proposals followed by detection [22]. Although these algorithms ensured high detection precision, the two-step process was relatively cumbersome, resulting in slow overall detection speeds that struggled to meet the requirements of real-time scenarios [23]. The YOLO model innovatively introduced a single-stage detection method based on regression [24]. By merging region proposal generation and object detection into a single forward pass, it directly determines the positions and categories of targets [25]. This approach significantly streamlines the detection workflow and enhances efficiency [26,27].
2.2. Intelligent Harvesting of Edible Fungi
The United Kingdom pioneered research into the image recognition and automated harvesting of edible fungi. In 1991, Tillett’s team developed a mushroom localization algorithm, laying the groundwork for visual mushroom recognition [28,29]. The Silsoe Research Institute in the UK later engineered a mushroom-harvesting manipulator; its actuator comprised translational and rotational joints, ending with a suction cup for grasping, while utilizing a monochrome CCD camera for recognition [30]. In 2005, Professor Gaohong Yu from Zhejiang Sci-Tech University in China achieved mushroom recognition by applying a sequential algorithm for the region labeling of images [31,32]. By 2008, Reed’s team in the UK successfully constructed a fully functional harvesting robot capable of performing picking operations under laboratory conditions [33,34]. In 2010, Xingyi Huang et al. at Jiangsu University investigated the machine vision-based recognition of malformed small oyster mushrooms, reporting a recognition rate of 96.67% [35]. In 2021, Jingjun Cao’s team developed a multimodal perception and lightweight algorithm framework. Their prototype system, integrated with 3D localization and path planning algorithms, achieved a measured harvesting success rate of 90% and a localization error of <1.5 cm [36]. In 2024, to address the recognition difficulties caused by minimal morphological differences between early and mature stages, along with the complex backgrounds of cultivation logs, Lin Yang et al. proposed an intelligent recognition method based on YOLOv5. Operating on a Jetson Xavier device, it delivered a real-time detection speed of 45.25 FPS and an average detection precision of 92.7%. This yielded a 2.5 percentage point improvement over the baseline model, with specific recognition precisions of 94.0% for the early stage and 91.3% for the mature stage [37].
Although research on edible fungi harvesting robots has made significant strides—enabling automated production for certain species—the intelligent harvesting of Morchella remains in its preliminary developmental stage. Currently, Morchella extraction relies predominantly on manual labor. Moving forward, as smart agriculture continues to evolve and mature, fungi harvesting robots will play an increasingly vital role in scenarios such as high-density cultivation and factory-scale production. Consequently, in-depth research and exploration into the intelligent harvesting of Morchella are of profound significance.
3. Materials and Methods
3.1. YOLOv8 Architecture
YOLOv8, released by the Ultralytics team in early 2023, is the latest iteration of the YOLO series. Building upon the technical accumulation of predecessors like YOLOv5 and YOLOv7, it integrates cutting-edge achievements in deep learning and computer vision. By adopting state-of-the-art (SOTA) model design principles, it further optimizes object detection performance and scene adaptability [38]. The overall architecture of YOLOv8 is shown in Figure 1.
Figure 1.
The overall network architecture of YOLOv8.
3.1.1. Backbone Network
The YOLOv8 backbone is centered on the principle of “dimensionality reduction followed by deep feature extraction.” It initially employs two consecutive 3 × 3 convolutional layers to downsample the input image, expanding the receptive field while reducing resolution. This process compresses redundant pixels and aggregates the contour features of morels, satisfying the demand for rapid target localization. The core feature extraction unit is the C2f structure, which is divided into two categories: one incorporates a residual structure, utilizing skip connections to preserve shallow details such as morel edge textures while preventing gradient vanishing in deep training; the other lacks a residual structure, enhancing representation through intensified local feature fusion. Furthermore, the C2f design utilizes more skip connections and “Split” operations. The former enables interaction between deep and shallow features, simultaneously leveraging texture and semantic information, while the latter enhances the model’s ability to capture targets in complex backgrounds—such as overlapping morels or weed interference—through feature map segmentation and reorganization. The structure of the C2f module is shown in Figure 2.
Figure 2.
Structure diagram of the C2f module.
3.1.2. Neck Network
YOLOv8 utilizes an FPN + PAN structure to construct a feature pyramid, achieving comprehensive fusion of multi-scale features to support the identification of morels of various sizes. In terms of network operations, standard convolutions are executed via “Conv” layers, and deep feature extraction networks are built using the C2f structure. The “Bottleneck” module is employed to deepen feature extraction—the output of each Bottleneck is concatenated via “Concat,” and 1 × 1 convolutional layers are used to compress input channels to the minimum, efficiently extracting key features. During forward propagation, the “Split” module combines convolutional layers and Bottleneck modules to complete feature extraction and transformation. Finally, the “Detect” layer performs the object detection.
3.1.3. Detection Head
YOLOv8 processes the output of the detection layers through convolutional layers to generate predicted bounding boxes and class probabilities, providing direct results for morel localization and classification. The training loss consists of two categories corresponding to core task requirements. The first is classification loss, calculated using the VariFocal Loss (VFL) function (see Equation (1)). This loss dynamically adjusts the weights of positive and negative samples, strengthening the model’s ability to distinguish between mature and immature morels. The second is localization loss, integrating Complete IoU (CIoU) and Distribution Focal Loss (DFL) (see Equations (2) and (3), respectively). CIoU loss accounts for bounding box overlap, center point distance, and aspect ratio to improve the precision of morel framing. DFL loss models the bounding box position as a probability distribution, guiding the network to focus rapidly on areas close to the morel’s actual position. These two losses act synergistically to ensure the model continuously reduces prediction bias while learning “what” (category) and “where” (position) the morels are.
The meanings of the symbols in the equation are shown in Table 1.
Table 1.
Table of Symbols.
3.2. Five YOLOv8 Models
YOLOv8 offers five models of different scales—n, s, m, l, and x—to satisfy diverse requirements across various scenarios. As shown in Table 2.
Table 2.
Performance comparison of different models.
YOLOv8n is the most lightweight model in the series, offering the fastest processing speed but relatively lower accuracy, making it suitable for resource-constrained environments. Compared to YOLOv8n, YOLOv8s improves accuracy while maintaining high speed, suitable for applications requiring a balance between the two. YOLOv8m provides a significant boost in accuracy for scenarios where precision is prioritized over raw speed. YOLOv8l’s higher accuracy makes it suitable for precision-demanding applications, albeit with slower speeds. Finally, YOLOv8x offers the highest accuracy but requires substantial hardware support, targeting high-end applications where precision is paramount. Considering the real-time requirements, recognition accuracy, and field deployment feasibility for morel maturity detection, this study selects YOLOv8s as the baseline model for further improvement.
3.3. Improved YOLOv8s Object Detection Algorithm
3.3.1. Improving YOLOv8s with Attention Mechanisms
The design of attention mechanisms is inspired by the signal processing of the human brain. During visual perception, the brain autonomously focuses on key target regions while ignoring irrelevant background information. This characteristic provides a vital strategy for enhancing the feature extraction efficiency of object detection models. In recent years, embedding attention modules into detection networks has become a key method for performance optimization, guiding models to capture target information accurately in complex scenes.
There are three common types of attention mechanisms: spatial attention, spatial-and-channel attention, and channel attention. Representative examples include the STN (Spatial Transformer Network), which performs suitable preprocessing by learning input deformations; CBAM (Convolutional Block Attention Module), which integrates channel and spatial importance and is easily embedded into networks; and SENet, a channel-based mechanism that models the importance of individual channels to enhance or suppress specific features [39].
CBAM, as a lightweight and efficient mechanism, significantly enhances CNN feature representation via dual-dimensional attention. Its plug-and-play nature allows for easy integration into various deep architectures. In practice, CBAM is widely used in tasks such as classification, detection, and segmentation with remarkable results [40]. The CBAM structure is shown in Figure 3.
Figure 3.
Architecture of the Convolutional Block Attention Module (CBAM).
To enhance the model’s perception and utilization of morel features, this study introduces CBAM at the terminals of the three C2f modules interfacing with the “Detect” layer in the YOLOv8s neck. Additionally, CBAM modules are embedded within the multi-scale output paths of the neck. While introducing moderate computational overhead, CBAM remains within a reasonable range as an efficient “channel-spatial” dual-attention mechanism, significantly strengthening the model’s ability to focus on key morel features and their spatial positions. In the YOLOv8s architecture, CBAM is deployed at multiple stages: first, at the junction of the three C2f modules before the “Detect” layer, it filters important channels and then reinforces key spatial regions, precisely fitting the complex relationship between morel features and their distribution. Secondly, based on multi-scale optimization, CBAM operates on feature maps of different scales through dynamic learning of channel and spatial importance. This allows the model to simultaneously focus on key features and accurate locations while effectively suppressing interference from complex backgrounds.
This design preserves the multi-scale detection advantages of YOLOv8s while achieving adaptive synergistic optimization of features in both channel and spatial dimensions. In the morel maturity recognition task, the improved model adapts to various target sizes via its multi-scale structure and enhances discrimination and localization precision through dual-calibration by CBAM. This approach achieves an optimal balance between recognition accuracy, computational efficiency, and robustness, demonstrating stronger feature representation and anti-interference capabilities in scenarios with cluttered backgrounds and variable target scales.
Field-grown morels typically grow among soil and weeds. Their color closely resembles that of the soil, making traditional convolutional networks prone to false detections. Moreover, morels possess a highly unique honeycomb-like reticulated cap. The CBAM attention mechanism assigns higher weights to the channels representing the specific textures, edge contours, and particular color distributions of morels. This enables the model to capture their most essential features even when facing morels of diverse morphologies, thereby improving recognition precision and recall.
3.3.2. Improving YOLOv8s with AKConv
AKConv (Alterable Kernel Convolution) introduces a versatile convolutional mechanism that accommodates an arbitrary number of parameters and sampling shapes. By circumventing the constraints of traditional convolutions—typically restricted to fixed local windows and rigid sampling patterns—AKConv enables the operation to adapt precisely to targets across diverse datasets and spatial locations. Its core innovation lies in the dynamic adjustment of kernel parameters and sampling shapes based on target characteristics. Specifically, it employs a dedicated initial coordinate generation algorithm to suit various target scales, supplemented by an adaptive offset mechanism to refine sampling positions, thereby significantly enhancing feature extraction precision. Through this innovative design, AKConv achieves efficient feature representation by flexibly tailoring the convolution kernel to the specific requirements of the dataset [41].
In this study, the AKConv module is embedded into the C2f structure at the end of the backbone network, preceding the SPPF module. This integration aims to enhance the model’s capability to recognize the irregular morphologies and fine-grained features of morel mushrooms while maintaining a controllable computational overhead. By leveraging kernels with dynamically adjustable sampling points, the network can adaptively focus on complex geometric attributes, such as the non-rigid edges and rugose surfaces of morels, capturing the intrinsic structural patterns more accurately.
While preserving the efficient multi-scale feature pyramid of the original YOLOv8s, this design optimizes feature extraction at the most critical information aggregation path. The improved model facilitates morel maturity recognition by adapting to varied target sizes via its multi-scale architecture and enhancing the geometric perception of abstract high-level features through the AKConv module. This synergy yields a new equilibrium among feature representation, robustness, and computational efficiency. Consequently, the model demonstrates superior geometric feature fitting and shape discrimination in challenging scenarios characterized by significant target deformation, intricate textures, and field occlusions. The architecture of the improved model is illustrated in Figure 4.
Figure 4.
Architecture of the improved model.
When extracting the irregular edges of morels, traditional 3 × 3 convolution kernels often include a large amount of irrelevant background information or lose critical edge features. In contrast, AKConv can dynamically adjust the positions of sampling points based on the actual contours of the morels, enabling the network to extract features by closely fitting their true boundaries. This adaptability to geometric deformations significantly enhances the model’s representation capability for irregular morphologies.
3.3.3. Loss Function Optimization
Intersection over Union (IoU) serves as a pivotal metric for evaluating the alignment between predicted and ground-truth bounding boxes. Characterized by scale insensitivity, non-negativity, symmetry, and the triangle inequality, IoU effectively reflects detection performance. However, when two boxes do not overlap, IoU drops to zero, failing to provide a gradient for training or capture subtle differences in spatial proximity; its formula is given in (4).
The design of the loss function is fundamental to model performance, with the bounding box regression (BBR) loss being the cornerstone. Although the original YOLOv8s employs CIoU Loss, which accounts for the aspect ratio, it overlooks the orientation discrepancies between the predicted and target boxes during training.
SIoU addresses this by redefining the penalty metric through the consideration of the vector angle between regressions. This approach directs the predicted box to “drift” rapidly toward the nearest axis, subsequently requiring the regression of only a single coordinate, which effectively reduces the total degrees of freedom.
Angle cost: This term describes the minimum angle between the line connecting the center points and the x/y axes. The penalty Λ vanishes when the center points are aligned along either axis and reaches its maximum when the connection is at a 45° angle to the x-axis. This cost guides the anchor box toward the nearest axis of the target box, simplifying the BBR process. The formula is as follows:
Distance cost: To address the vanishing gradient problem of the pure IoU loss, the distance cost evaluates the spatial alignment of the boxes. Analytically, it calculates the squared Euclidean distance between the center points of the predicted and ground truth (GT) boxes, normalizing it by the squared diagonal length of their smallest enclosing box. Geometrically, this introduces a continuous penalty term that actively forces the predicted box to move toward the target center regardless of whether they overlap, thereby significantly accelerating the convergence speed. The formula is as follows:
Shape cost: The shape cost governs dimensional matching. Analytically, it evaluates the relative differences in width and height (or aspect ratio) between the predicted and ground truth (GT) boxes. By calculating the ratio of the absolute dimensional differences to the maximum dimensions, it constructs a penalty term for shape mismatch. This mechanism forces the model to not merely locate the target but also precisely regress its non-rigid morphology, which is particularly crucial for targets exhibiting diverse scales and aspect ratios, such as morels. The formula is as follows:
The IoU loss formula is defined as follows:
In practical cultivation, morels frequently grow in clusters, causing mutual occlusion. If bounding box localization is imprecise and the overlap between boxes is excessive, they are highly susceptible to being mistakenly eliminated by the algorithm as a single target. Bounding boxes trained with SIoU achieve more accurate localization and tighter edge convergence. Therefore, when processing densely distributed morels, the boundaries between individual boxes become much clearer. This alleviates the false suppression issue caused by overlapping occlusion, thereby improving the recall of clustered morels.
The calculation of the SIoU loss introduces only marginal computational overhead during training, while the inference process remains completely latency-free.
4. Experiments
4.1. Image Acquisition and Preprocessing
Machine vision technology emulates human visual perception by utilizing sensors such as cameras to capture image information. By integrating advanced image processing and analytical algorithms, it achieves precise identification of target objects [42,43].
4.1.1. Data Collection
The subjects of this study were morels cultivated in greenhouses in Siyang County, Suqian City, Jiangsu Province. Images were captured from multiple angles under varying conditions of occlusion, illumination, and quantity. This approach ensured high image quality while accentuating the color and texture features of the morels. The growth of morels is divided into five stages: the primordium, pinhead, mulberry, juvenile, and mature stages. Morels in the primordium, pinhead, and mulberry stages are exceedingly small; therefore, we primarily distinguish between the juvenile and mature stages during field harvesting. Juvenile morels are roughly the size of a peanut, featuring a distinct separation between the cap and the stipe. In contrast, the reticulated meshes on the caps of mature morels are fully expanded, deepening in color to dark brown or even approaching black. Meanwhile, their stipes transition from off-white or milky white to developing brownish hues, accompanied by a markedly enlarged base. Juvenile and mature morels are illustrated in Figure 5 and Figure 6, respectively.
Figure 5.
Juvenile morels.
Figure 6.
Mature morels.
4.1.2. Preprocessing
Dataset preprocessing involves a series of annotation and data augmentation operations performed before images are input into a convolutional neural network (CNN) for feature extraction. These steps enrich the sample set and serve as an essential prerequisite for network training. Figure 7 illustrates the preprocessing workflow, which encompasses data acquisition, followed by image annotation and, finally, data augmentation.
Figure 7.
Preprocessing Flow Diagram.
We manually annotated the data using LabelImg (version 1.8.6). Dataset annotation categorizes the positions and types of morels within the dataset. Precise labeling is fundamental to achieving optimal performance in subsequent network training tasks. For this process, target objects were enclosed in minimum bounding boxes that fully encompass the morels, with their respective types specified. The resulting labels were stored in XML format. To prepare the dataset for the YOLO-style detector, the annotated bounding boxes were exported and converted into the standard YOLO format. Specifically, the annotations for each image were saved as corresponding .txt files. Each line in the text file represents a single object, containing the class index and the normalized bounding box coordinates. The annotation interface and representative results are displayed in Figure 8.
Figure 8.
The data labeling interface and visualization of the ground truth bounding boxes.
To facilitate training on YOLO-series models, the dataset was organized into a YOLO-compatible format. This structure comprises two critical subfolders: images and labels. The images folder contains all morel images in .jpg format, while the labels folder stores annotation information corresponding to each image in .txt format. Each text file shares the same name as its respective image; each line within a file records a target’s class index, normalized bounding box center coordinates (x, y), and the relative width and height of the bounding box.
Data augmentation primarily serves to expand the training sample size and enhance dataset diversity. A diversified dataset allows the network to extract morel features more comprehensively during training, aiding the model in learning feature information more accurately and thus effectively boosting detection precision. Although the current morel dataset covers core varieties, a subset of low-quality images exists due to varying shooting conditions. Direct training on such data could lead to weak model generalization and elevated miss rates. Consequently, augmenting the morel dataset to supplement sample quantity and optimize quality is essential for ensuring robust training outcomes.
By invoking functions from the OpenCV library, techniques such as cropping, rotation, flipping, and brightness adjustment were applied. Specifically, the rotation angle ranged from −30° to +30°, and cropping retained at least 80% of the area. Horizontal and vertical flips were applied with a probability of 0.5. For brightness adjustment, the contrast was randomly sampled between 0.7 and 1.3, while the base brightness fluctuated randomly between −30 and +30 pixel values. These methods simulate image variations likely encountered in actual field scenarios, increasing dataset diversity and enabling the model to better adapt to detection requirements in complex environments.
A total of 2105 morel images were collected for this study. To facilitate effective training and evaluation, the dataset was partitioned into training, validation, and testing sets according to a 7:2:1 ratio. Dataset partitioning was performed prior to data augmentation to avoid inflated performance metrics. The specific distribution is shown in Table 3.
Table 3.
Statistical Table of Dataset Split.
4.2. Experimental Setup
4.2.1. Experimental Configuration
The training and testing phases of the proposed model were conducted on a Microsoft Windows 10 platform. The hardware environment featured an AMD Ryzen Threadripper PRO 3955WX 16-Core CPU and an NVIDIA GeForce RTX 4090 GPU. For software development, we utilized Python (version 3.8.10) as the programming language within the PyCharm IDE (version 2021.3.2), with PyTorch (version 1.9.0) serving as the deep learning framework. The PyQt5 framework was also integrated to support visualization during the deployment phase.
4.2.2. Hyperparameter Settings
In model training, meticulous hyperparameter configuration is essential to ensure experimental fairness and consistency. Tailored to the specific requirements of morel detection and the characteristics of our architecture, we established a set of parameters that balances detection sensitivity with generalization performance after multiple rounds of empirical tuning. The specific settings are summarized in Table 4.
Table 4.
Hyperparameter Configurations.
4.2.3. Evaluation Metrics
To comprehensively evaluate the overall performance of the object detection model, we employed a multi-dimensional set of metrics for quantitative analysis. These metrics include precision (Pre), recall (R), mean average precision at specific IoU thresholds (mAP50 and mAP50:95), frames per second (FPS), and the network parameter count (P). Precision typically refers to the ratio of correctly predicted samples (TP) to the total predicted positives (TP + FP), reflecting the model’s accuracy in not misclassifying the background as a target. Recall measures the positive examples correctly identified by the model (the ratio of true positives, TP, to all actual positives, TP + FN). Ranging from 0 to 1, it reflects the model’s sensitivity in avoiding the misclassification of targets as the background. During object detection tasks, a correctly detected true sample occurs when the overlap between the predicted box and the ground-truth bounding box reaches a certain threshold (such as a preset IoU threshold). Once the Intersection over Union (IoU) between the two boxes exceeds the established threshold, the prediction is considered correct, and the target is successfully detected. The formulas for Precision and Recall are as follows:
In evaluating object detection performance, the definitions of mean Average Precision (mAP) and Average Precision (AP) depend on the number of classes within the dataset. If the dataset contains only a single class, mAP and AP are identical. Conversely, for multi-class datasets, mAP is defined as the arithmetic mean of the APs across all categories. Its primary role is to comprehensively measure the model’s overall accuracy in multi-class detection tasks; a higher mAP indicates a more balanced detection precision across various classes and superior overall performance. Specifically, AP is calculated by integrating precision (P) with respect to recall (R), whereas mAP is subsequently derived by averaging these class-specific APs. The detailed formulas are as follows:
n represents the number of detection classes.
4.3. Results and Analysis
4.3.1. Ablation Study
This study meticulously designed five sets of ablation experiments. We initially validated the individual efficacy of SE and CBAM modules, followed by an evaluation of the CBAM + AKConv feature extraction combination. Finally, a full-pipeline optimization involving the SIoU loss function and feature modules was verified. The core objective was to systematically identify the optimal individual components and their combinations.
During data preprocessing, all morel images underwent a standardized workflow, including uniform resizing to meet the model’s input requirements and normalization to stabilize pixel values. These steps ensured consistency across different experimental groups and eliminated interference from preprocessing discrepancies.
Throughout the training process, critical parameters—including the learning rate, batch size, and total iterations—were strictly controlled. Specifically, the initial learning rate was set to 0.01, the batch size to 16, and the iteration count to 200. Maintaining identical parameters across all groups ensures that the reliability of the results depends solely on the architectural modifications.
For performance evaluation, we employed consistent metrics: Precision, Recall, mAP50, mAP50:95, P, and FPS. The comparative results are presented in Table 5.
Table 5.
Experimental Results.
As shown in Table 4, the YOLOv8s-CBAM model outperformed YOLOv8s-SE across several key metrics. Subsequent improvements were built upon the YOLOv8s-CBAM baseline, culminating in the YOLOv8s-CAS model. Regarding Precision, the final model achieved 0.939, a significant increase from the baseline 0.847, indicating a higher proportion of true positives among predicted samples and enhanced identification accuracy. Recall rose from 0.761 to 0.867, demonstrating the model’s ability to effectively capture positive instances and reduce background misclassifications. Furthermore, mAP50 and mAP50:95 increased from 0.853 to 0.927 and 0.531 to 0.599, respectively. These improvements suggest a comprehensive optimization in detection accuracy across various IoU thresholds. FPS (The metric encompasses the entire end-to-end pipeline overhead) exhibits a notable improvement, rising from 35.3 in the baseline YOLOv8s to 45.17, which reflects a substantial boost in inference speed. Meanwhile, the parameter count (P) decreased from 11.1 M to 9.0 M, as a lightweight module, CBAM typically increases the parameter count. However, we embedded the AKConv module into the backbone, which accounts for the majority of YOLOv8’s parameter weights. By replacing the standard 3 × 3 convolutions in deep, heavy channels with AKConv modules, the saved parameters far offset and cover the minor increment introduced by CBAM. Consequently, the model complexity is effectively reduced. Overall, these metrics indicate that the improved model not only enhances detection performance but also accelerates inference. With robust generalization capabilities, the model effectively improves the overall accuracy of Morchella maturity detection.
As shown in Figure 9 and Figure 10, comparative analysis of the experimental results indicates that the improved model significantly outperforms the baseline YOLOv8 across all categories. Notably, the detection accuracy for the “unripe” class exhibits a substantial increase of 11.6%. The precision–recall (P-R) curves for both models are presented below to facilitate a more comprehensive and granular analysis.
Figure 9.
Precision–recall curves of the YOLOv8s baseline model.
Figure 10.
Precision–recall curves of the YOLOv8-CAS model.
Ablation experiments demonstrate that the CBAM module fundamentally underpins the accuracy gains in morel mushroom detection. Specifically, the standalone integration of the CBAM module boosted mAP50 and mAP50:95 by 5.2% and 6.5%, accounting for 70.2% and 94% of the total improvements, respectively.
4.3.2. Analysis of Evaluation Metric Curves
The performance metric curves in Figure 11 quantitatively characterize the training dynamics of YOLO-CAS. Accuracy metrics exhibit a logarithmic growth trend, reaching convergence after 100 iterations. Such stability is essential for practical deployment, as it ensures reliable outcomes in real-world scenarios. This consistent performance across various metrics underscores the model’s effectiveness in balancing precision and recall, making it well-suited for agricultural detection tasks with diverse requirements.
Figure 11.
Evaluation metric curve.
4.3.3. Performance Comparison with Other YOLO Versions
Regarding lightweight performance, YOLOv8s-CAS not only achieves parameter and model size reductions of approximately 18.9% and 19.0% compared to the baseline YOLOv8s, but also outperforms YOLOv11s and YOLOv12s. Although it has a larger model size and parameter count than YOLOv7-tiny, YOLOv5s, and YOLOv10s, it yields substantial accuracy gains, effectively striking a balance between precision and lightweight design. As shown in Table 6, the YOLOv8s-CAS model achieves high detection performance with fewer parameters and lower computational cost.
Table 6.
Performance Comparison.
4.3.4. Visualization and Analysis
We employed YOLO-CAS to demonstrate the detection results of morel maturity. As shown in Figure 12, for each image, the model predicts the bounding box of the morel and assigns a corresponding maturity label. Through visual analysis of different morels, we found that YOLO-CAS can accurately identify and classify mature and immature morels.
Figure 12.
YOLO-CAS inference visualization results.
5. System Design
5.1. Core Module Design
The system interface adopts a “function-display” bipartite structure, integrating operational controls with result presentation to balance ease of use with information clarity. The specific design is as follows:
The left side of the interface serves as the Functional Interaction Area, employing an “icon + text” button layout that covers five core operations: single-image import, batch detection for multiple images, and frame-by-frame video detection and playback. A “Run” button triggers the detection task—incorporating a lockout mechanism during processing to prevent redundant operations, followed by a status notification upon completion. Additionally, the “Export Data” function allows detection results to be exported in XLS format and supports the saving of annotated images.
The right panel of the interface serves as the result display area, encompassing two main sub-modules. During object detection, the result visualization section annotates targets using colored bounding boxes overlaid with “class + confidence” labels, and supports image zooming for detailed inspection. Complementing this, the tabular information section manages batch data through structured tables. It records seven specific fields: index, image name, input time, recognition result, target count, processing time, and save path. Clicking any row in the table switches the view to the detection results of the corresponding image.
5.2. System Architecture Design
To ensure modularity, maintainability, and scalability, the morel maturity detection system adopts an industry-standard three-tier architecture comprising the View Layer, Business Logic Layer, and Data Layer. Guided by the principles of single responsibility, inter-layer decoupling, and transparent data flow, the system implements a full-process detection workflow through a synergistic model of user interaction, logical computation, and data support. The detailed architecture is illustrated in Figure 13.
Figure 13.
Overall System Architecture.
The View Layer serves as the primary interface for user interaction. Developed with QtDesigner, the visualization interface features a tripartite layout: functional interaction, result display, and status feedback. The interaction zone provides controls for loading images, videos, and folders, alongside buttons for detection initiation and data export, supporting drag-and-drop operations for enhanced usability. The display zone presents a dual-window comparison between raw media and detection results, where identified targets are annotated with colored bounding boxes and “category + confidence” labels. Differentiated box colors are utilized to align with the operational habits of agricultural users, effectively lowering the technical threshold for system adoption.
The Business Logic Layer acts as the system’s central hub, integrating task control, model inference, and result processing modules. The task control module receives commands from the View Layer and orchestrates the coordinated workflow of other modules; for instance, initiating video detection signals the Data Layer to load media while simultaneously prompting the inference module to prepare. The model inference module encapsulates the improved YOLOv8s model—which incorporates the CBAM—executing detection on preprocessed data to yield raw outputs. Subsequently, the result processing module applies Non-Maximum Suppression (NMS) to eliminate redundant boxes and match morel labels, generating structured results and visualized annotations.
The Data Layer provides underlying data support, encompassing media management, preprocessing, and result management. The media management module parses images and videos, resizing them for model compatibility. The preprocessing module performs normalization consistent with the training phase to ensure uniform data distribution. Finally, the result management module handles the storage of detection outcomes, supporting exports in CSV and XLS formats alongside the saving of annotated images. This ensures both the persistence and traceability of results while providing the Business Logic Layer with compliant data.
This three-tier architecture forms a closed loop through the bidirectional flow of instructions and data. The View Layer transmits user actions to the Business Logic Layer, which orchestrates the Data Layer for loading and preprocessing before feeding the data into model inference. Final processed results are simultaneously fed back to the View Layer for display and transmitted to the Data Layer for storage, ensuring high detection efficiency and a fluid user experience.
5.3. System Functional Implementation
The system implements several key features to facilitate efficient object detection in images and videos. The primary functions are detailed in Figure 14.
Figure 14.
Main interface layout of the proposed system.
- (1)
- Single Image Detection: Users can detect a single image by clicking the “Open Image” button to select a local file. Upon selection via the file dialog, the system loads the image and executes the detection. Once complete, identified targets are displayed with bounding boxes labeled with categories and confidence scores.
- (2)
- Folder Batch Detection: The system supports batch processing for multiple images. By clicking “Open Folder,” users can select a directory, after which the system automatically loads and detects all contained images. Results are displayed sequentially, and users can browse the detection output for each image by selecting different rows in the results table.
- (3)
- Video Detection: The system includes a robust video detection feature. Upon selecting a local video via the “Open Video” button, the system performs frame-by-frame inference. During playback, detection results are rendered in real-time, with bounding boxes and labels overlaid on each frame.
- (4)
- Data Export Functionality: To facilitate subsequent analysis and reporting, users can export detection results as Excel files. By clicking “Export Data,” the system saves the current session’s metadata—including categories, confidence, and coordinates—into a standardized export file.
6. Conclusions
To address the challenges of high labor intensity, low efficiency, and mounting labor shortages in morel harvesting, this study presents the design and development of a specialized maturity detection system.
Using YOLOv8s as the baseline model, we integrated the CBAM attention mechanism and AKConv module while refining the loss function. These enhancements significantly optimize the model’s capability for key feature extraction and screening, providing robust algorithmic support for the system’s detection functionality. Furthermore, a user-friendly interface was developed using the PyQt5 framework, allowing users to execute object detection across single images, image folders, and video streams through a clean and intuitive workflow. The resulting system offers the flexibility and scalability required to meet the practical demands of diverse agricultural scenarios.
In the context of intelligent agricultural production, high-speed and high-precision detection systems are of paramount importance. While the proposed system effectively meets these requirements, there remains room for further optimization. Future research will focus on refining the algorithms to enhance stability and robustness, ensuring adaptability to more complex natural environments and broader application scenarios, thereby contributing to the intelligent transformation of the morel industry.
Author Contributions
Conceptualization, Z.W. and M.W.; methodology, Z.W.; software, Z.W.; validation, Z.W.; formal analysis, Z.W.; investigation, Z.W.; resources, M.W.; data curation, Z.W.; writing—original draft preparation, Z.W.; writing—review and editing, Z.W.; visualization, Z.W.; supervision, M.W.; project administration, M.W.; funding acquisition, M.W. All authors have read and agreed to the published version of the manuscript.
Funding
This research received no external funding. The APC was funded by Nanjing Institute of Agricultural Mechanization, Ministry of Agriculture and Rural Affairs.
Institutional Review Board Statement
Not applicable.
Informed Consent Statement
Not applicable.
Data Availability Statement
The data presented in this study are openly available in https://github.com/MrFENGXINGYU/Maturity-Recognition (accessed on 1 April 2026).
Conflicts of Interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
References
- Zhang, Y.; Lin, C.; Duan, D.; Kang, X.; Ma, Y.; Chen, Y.; Chen, S. Simplified Cultivation Technologies for Morchella Interplanting under Pine Forest. Vegetables 2026, 1, 80–84. [Google Scholar]
- Du, X.; Zhao, Q.; Yang, Z. Diversity, evolutionary history and cultivation of morels: A review. Mycosystema 2014, 33, 183–197. [Google Scholar]
- Shang, X.; Zhang, M.; Jia, M.; Xia, S. Key Technical Points of Modern Facility Cultivation for Morels. Henan Agric. 2025, 8, 34–36. [Google Scholar]
- Cai, Y.; Ma, X.; Liu, W. A Review on the Nutritional Value and Health Functions of Morels. Edible Med. Mushrooms 2021, 29, 20–27. [Google Scholar]
- Sun, Q.; Zhang, J.; Xie, Y.; Yan, W. Recent Progress in Research on Nutrients, Functional Components and Health Benefits of Morchella esculenta. Food Sci. 2019, 40, 323–328. [Google Scholar]
- Zhao, R.; Liu, S.; Ma, C. Current Situation and Market Analysis of Morchella spp. Industry in China. Edible Fungi China 2020, 39, 7–10. [Google Scholar]
- Christudas, S.; Xu, B. Mycochemical Profile and Health-Promoting Effects of Morel Mushroom Morchella esculenta (L.)—A Review. Food Res. Int. 2022, 159, 111571. [Google Scholar]
- Yi, R.; Wei, J.; Zang, S.; Hu, W.; Du, X. Cultivars Breeding of Morels (Morchella) in China: Current Status and Prospects. J. Fungal Res. 2026, 24, 26–43. [Google Scholar]
- Yao, Y.; Rong, D.; Tang, M.; Jiang, M.; Yu, Y.; Zhang, Y.; Yu, M. Medical Value and Product Development Status of Morchella spp. Edible Fungi China 2022, 41, 13–17. [Google Scholar]
- Hu, Q.; Liao, C.; Zou, Y. Current Status and Future Prospects of Rare Edible Fungi in China. Agric. Integr. Dev. China 2022, 4, 50–54. [Google Scholar]
- Liao, G.; Li, Y.; Yang, B.; Deng, H.; Li, H. Cultivation Techniques for Morels. J. Chang. Veg. 2020, 3, 26–27. [Google Scholar]
- Sun, L.; Li, M.; Yu, J.; Tang, S.; Liao, Z.; Hao, Y. Exploration of the Production Technology of Interplanting Morchella spp. and Stropharia rugosoannulata in Different Zones of Greenhouses for Ziziphus jujuba ‘Dongzao’. Edible Fungi China 2025, 44, 54–59. [Google Scholar]
- Zhang, F. Measurement Method of Morel Mushroom Size Parameters Based on Computer Vision. Master’s Thesis, Shenyang Agricultural University, Shenyang, China, 2025. [Google Scholar]
- Zhang, Y.; Liu, L.; Li, D.; Niu, M. Research on Evolutionary Impetus and Path of Unmanned Farm. Shandong Agric. Sci. 2020, 52, 160–166. [Google Scholar]
- Zhao, C. Reflections on Developing Smart Agricultural Technology. Robot Ind. 2020, 4, 36–40. [Google Scholar]
- Luo, Y.; Wang, T.; Wei, Y.; Huang, J. Introduction and Key Cultivation Techniques of Morel Varieties in Yinjiang, Guizhou Province, China. Tillage Cultiv. 2025, 45, 147–149. [Google Scholar]
- Rashid, M.; Khan, M.A.; Sharif, M.; Raza, M.; Sarfraz, M.M.; Afza, F. Object Detection and Classification: A Joint Selection and Fusion Strategy of Deep Convolutional Neural Network and SIFT Point Features. Multimed. Tools Appl. 2019, 78, 15751–15777. [Google Scholar] [CrossRef] [Scilit]
- Zhu, L.; Spachos, P.; Pensini, E.; Plataniotis, K.N. Deep Learning and Machine Vision for Food Processing: A Survey. Curr. Res. Food Sci. 2021, 4, 233–249. [Google Scholar] [CrossRef] [Scilit]
- Simonyan, K.; Zisserman, A. Very Deep Convolutional Networks for Large-Scale Image Recognition. arXiv 2014, arXiv:1409.1556. [Google Scholar]
- Szegedy, C.; Liu, W.; Jia, Y.; Sermanet, P.; Reed, S.E.; Anguelov, D.; Erhan, D.; Vanhoucke, V.; Rabinovich, A. Going Deeper with Convolutions. arXiv 2014, arXiv:1409.4842. [Google Scholar] [CrossRef] [Scilit]
- Redmon, J.; Divvala, S.K.; Girshick, R.B.; Farhadi, A. You Only Look Once: Unified, Real-Time Object Detection. arXiv 2015, arXiv:1506.02640. [Google Scholar]
- Girshick, R.; Donahue, J.; Darrell, T.; Malik, J. Rich Feature Hierarchies for Accurate Object Detection and Semantic Segmentation. arXiv 2013, arXiv:1311.2524. [Google Scholar]
- Zhao, Y.; Li, X.; Gao, F. Survey on Deep Learning-Based Visual Object Detection Algorithms. Print. Digit. Media Technol. Study 2025, 6, 15–29. [Google Scholar]
- Sermanet, P.; Eigen, D.; Zhang, X.; Mathieu, M.; Fergus, R.; LeCun, Y. OverFeat: Integrated Recognition, Localization and Detection Using Convolutional Networks. arXiv 2013, arXiv:1312.6229. [Google Scholar]
- Yang, Z.; Yuan, J.; Xu, C.; Yao, D. Review of Research Progress on Object Detection Based on YOLO Series. In Proceedings of the 2024 28th Annual Conference on Network New Technologies and Applications, Network Application Branch, China Computer Users Association, Weihai, China, 21 November 2024. [Google Scholar]
- Xu, Y.; Li, J.; Dong, Y.; Zhang, X. Survey of Development of YOLO Object Detection Algorithms. J. Front. Comput. Sci. Technol. 2024, 18, 2221–2238. [Google Scholar]
- Li, C.; Zhang, Z.; Liang, Z.; Yao, C.; Zhang, J.; Yan, R.; Wu, P. Survey on Object Detection Models. J. Comput. Res. Dev. 2025, 62, 2895−2928. [Google Scholar]
- Tillett, R.D.; Batchelor, B.G. An Algorithm for Locating Mushrooms in a Growing Bed. Comput. Electron. Agric. 1991, 6, 191–200. [Google Scholar] [CrossRef] [Scilit]
- Reed, J.N.; Tillett, R.D. Initial Experiments in Robotic Mushroom Harvesting. Mechatronics 1994, 4, 265–279. [Google Scholar] [CrossRef] [Scilit]
- Noble, R.; Rama, T.; Miles, S.; Burton, K.S.; Stephens, T.M.; Reed, J.N. Influences of Compost and Casing Layer Depths on the Mechanical Properties of Mushrooms. Ann. Appl. Biol. 1997, 131, 79–90. [Google Scholar] [CrossRef] [Scilit]
- Yu, G.; Zhao, Y.; Li, G.; Shi, H. Algorithm for locating individual mushroom and description of its contour using machine vision. Trans. CSAE 2005, 21, 101–104. [Google Scholar]
- Yu, G.; Luo, J.; Zhao, Y. Region marking technique based on sequential scan and segmentation method of mushroom images. Trans. CSAE 2006, 22, 139–142. [Google Scholar]
- Reed, J.N.; Miles, S.J.; Butler, J.; Baldwin, M.; Noble, R. Automatic Mushroom Harvester Development. J. Agric. Eng. Res. 2001, 78, 15–23. [Google Scholar] [CrossRef] [Scilit]
- Noble, R.; Reed, J.N.; Miles, S.; Jackson, A.F.; Butler, J. Influence of Mushroom Strains and Population Density on the Performance of a Robotic Harvester. J. Agric. Eng. Res. 1997, 68, 215–222. [Google Scholar] [CrossRef] [Scilit]
- Huang, X.; Jiang, S.; Chen, Q.; Zhao, J. Identification of defect Pleurotus Geesteranus based on computer vision. Trans. CSAE 2010, 26, 350–354. [Google Scholar]
- Cao, J. Research on Computer Vision System of Agaricus bisporus Harvesting Robot Based on Deep Learning. Doctoral Dissertation, Chinese Academy of Agricultural Sciences, Beijing, China, 2021. [Google Scholar]
- Yang, L.; Zeng, D.; Bian, Y.; Chen, H.; Zong, W.; Gong, Y. Recognizing fruiting body growth period of Lentinus edodes using improved YOLOv5. Trans. CSAE 2024, 40, 182–189. [Google Scholar]
- Li, Y.; Fan, Q.; Huang, H.; Han, Z.; Gu, Q. A Modified YOLOv8 Detection Network for UAV Aerial Image Recognition. Drones 2023, 7, 304. [Google Scholar] [CrossRef] [Scilit]
- Wang, L.; Bai, J.; Li, W.; Jiang, J. Research Progress of YOLO Series Target Detection Algorithms. Comput. Eng. Appl. 2023, 59, 15–29. [Google Scholar]
- Woo, S.; Park, J.; Lee, J.Y.; Kweon, I.S. CBAM: Convolutional Block Attention Module. In Computer Vision—ECCV 2018; Springer: Cham, Switzerland, 2018. [Google Scholar]
- Zhang, X.; Song, Y.; Song, T.; Yang, D.; Ye, Y.; Zhou, J.; Zhang, L. AKConv: Convolutional Kernel with Arbitrary Sampled Shapes and Arbitrary Number of Parameters. arXiv 2023, arXiv:2311.11587. [Google Scholar] [CrossRef] [Scilit]
- Zou, Z.; Shi, Z.; Guo, Y.; Ye, J. Object Detection in 20 Years: A Survey. arXiv 2019, arXiv:1905.05055. [Google Scholar] [CrossRef] [Scilit]
- Sun, Z.; Xue, L.; Xu, Y.; Wang, Z. Overview of deep learning. Appl. Res. Comput. 2012, 29, 2806–2810. [Google Scholar]
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. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.













