Abstract
The poultry industry faces growing demands for automated, high-precision egg grading systems to ensure quality control and meet market standards. Traditional methods relying on manual inspection are time-consuming, subjective, and prone to human error. Although state-of-the-art YOLO architectures have achieved high accuracy in object detection, their limited interpretability constrains adoption in agricultural contexts where transparency and biological relevance are critical. This study presents an interpretable deep learning framework based on YOLOv12 architecture for real-time egg size detection and classification. Using a dataset of 844 egg images, the performance of YOLO models (v7–v12) is compared, with YOLOv12-X achieving a mean Average Precision (mAP) of 99.4%. To enhance transparency in automated decision-making, Explainable AI (XAI) techniques, including Grad-CAM and EigenCAM, are integrated to visualize the model’s focus regions during classification. This approach not only validates the model’s alignment with biologically relevant features, such as egg contours, but also provides actionable insights for stakeholders in agriculture and food processing. This work bridges the gap between high-accuracy detection and interpretability, paving the way for smarter, more trustworthy automation in the poultry supply chain.
Keywords: YOLO, Egg size, Poultry industry, Egg quality, XAI
Subject terms: Mathematics and computing, Image processing
Introduction
The detection and categorization of egg size are crucial in the poultry industry, significantly influencing quality control, market dynamics, and customer preferences1. The worldwide need for eggs has been consistently rising, propelled by their nutritious worth and adaptability in cooking. Eggs are rich in proteins, vitamins, and minerals, making them a fundamental component of the diet2. The chicken egg market is projected to grow significantly from 2024 to 2029, with a compound annual growth rate (CAGR) of 6%3. Retailers are expanding their product selection to include organic, free-range, and cage-free choices in response to growing customer awareness about the health advantages of egg intake. These advancements highlight the need to maintain excellent standards in egg quality. This requires efficient methods for detecting and classifying egg sizes to meet evolving consumer demands and maintain a competitive market stance4.
The poultry industry is a vital component of global food production, supplying billions of eggs annually to meet rising consumer demand. As the industry expands, there is a growing emphasis on efficiency, standardization, and traceability in poultry farming operations. Automation has emerged as a critical solution to address labor shortages, ensure product consistency, and enhance biosecurity. Technologies such as computer vision, robotics, and machine learning have increasingly been integrated into various aspects of poultry farming, including environmental control, feeding systems, disease monitoring, and behavioral analysis. One of the key stages in poultry product handling is the grading and classification of eggs based on physical characteristics such as size, weight, and surface quality. Accurate egg classification is not only essential for meeting regulatory and commercial standards but also plays a pivotal role in streamlining supply chains and minimizing waste. Manual inspection methods, although widespread, are inherently limited by subjectivity and scalability issues. This limitation underscores the need for intelligent, automated systems capable of real-time, non-invasive analysis5,6.
The poultry industry faces significant challenges in ensuring the quality and consistency of egg production, particularly in the accurate detection and classification of egg sizes. Traditional methods of egg classification are often manual, time-consuming, and prone to human error, leading to inconsistencies in product quality and inefficiencies in operations. As consumer demand for standardized egg sizes increases, there is a pressing need for automated systems that can reliably assess egg size and quality in real-time7. Furthermore, the integration of advanced technologies such as deep learning has not been fully realized in the context of egg size detection, limiting the potential for improved classification accuracy and operational efficiency8.
Detection of egg size is a significant classification and plays a vital role in ensuring the quality and safety of the product. Automated systems using machine vision can classify eggs such as intact, cracked, or non-standard, achieving accuracy rates of up to 94.8%5. Accurate measurement of egg size is essential for categorization, as it directly impacts pricing and consumer trust. Furthermore, size detection systems can help identify defects and ensure that customers receive eggs of the highest quality. A novel single-view measurement method that uses deep learning achieved a mean intersection in the union of 96.15% for egg segmentation9. Deep convolutional neural networks (CNNs) were used to detect eggshell cracks with 95.38% accuracy, ensuring that only high-quality eggs reach consumers10. The use of advanced technologies, such as computer vision and deep learning (DL), has altered the traditional methods for egg classification, allowing more efficient and precise assessments of the quality and size of the egg. Recent studies have shown that these methods have advantages in improving the accuracy of egg grading systems, and this in turn helps maintain the overall integrity of the poultry supply chain. The use of state-of-the-art techniques for detecting egg size will have a crucial impact on addressing the challenges posed by consumer demands, market rivalry, and regulatory standards as the industry advances9,11.
The literature on egg size detection and classification has significantly developed recently, primarily on the application of machine vision and deep learning techniques12,13. Early studies laid the groundwork for using computer vision to assess egg quality and size. Zhou et al.14 explored shape identification of fertile eggs using computer vision, establishing foundational methods for automated detection. Deng et al.15, further advanced these techniques by integrating machine vision for precise egg size detection. More recent studies have leveraged artificial intelligence (AI), Omid et al.16 developing an expert egg grading system that combines machine vision with AI techniques to enhance accuracy in classification. The enhancement underscores the shift from manual classification methods to automated systems, which not only improve efficiency but also ensure consistent quality between different types of eggs.
Additionally, traditional machine vision approaches and the integration of deep learning have revolutionized egg classification and quality assessment. Many studies have demonstrated the effectiveness of CNNs and other deep learning architectures in accurately classifying eggs based on size, shape, and surface quality. Harnsoongnoen et al.11 utilized machine vision and weighing sensors to assess egg grades and freshness, highlighting the potential of combining multiple technologies for enhanced detection capabilities. Furthermore, studies have explored the use of hybrid systems that incorporate deep learning and regression models for joint egg classification and weight prediction, thereby addressing the growing demand for efficient and reliable grading systems in the poultry industry. As the industry transitions towards more automated and precise methods, the literature reflects a clear trend towards integrating advanced technologies to meet the challenges of modern egg production and quality assurance.
The YOLO algorithm (You Only Look Once) was introduced in 2015 by Joseph Redmon et al.17. It describes a unique method of analyzing the entire image a single time to identify objects along with their respective locations. Unlike traditional techniques that utilize two-stage detection processes, YOLO considers object detection to be a regression problem17. Within the framework of YOLO, a single convolutional neural network is responsible for predicting the bounding boxes and class probabilities for the entire image. This approach, which is notably more streamlined and efficient, stands in stark contrast to traditional methodologies that rely on intricate and heavily detailed processing pipelines. YOLOv2, released in 2016, improved the original model by incorporating features such as batch normalization and anchor boxes, which improved detection performance. Subsequent versions, including YOLOv3 and YOLOv4, introduced further optimizations like multi-scale predictions and a new backbone architecture, resulting in better accuracy and efficiency. YOLOv5 and YOLOv6 continued this trend by integrating hyperparameter optimization and advanced data augmentation techniques, while YOLOv7 focused on simplifying the architecture to enhance speed without sacrificing accuracy18. The latest iterations, YOLOv8 and YOLOv9, have introduced state-of-the-art features such as dynamic prediction schemes and improved loss functions, further advancing the model’s capabilities in diverse applications, including detection, segmentation, and tracking19–21.
YOLOv10 developed by Wang et al.22, from Tsinghua University, marks a significant milestone by introducing an end-to-end head that eliminates the need for Non-Maximum Suppression (NMS), streamlining the object detection process and enhancing real-time performance. This enhancement allows for more efficient processing, particularly in scenarios requiring rapid detection, such as autonomous driving and surveillance systems. The continuous evolution of YOLO models reflects a commitment to improving detection accuracy and processing speed, positioning them at the forefront of computer vision technologies23. As these models evolve, they enhance performance across various tasks and expand their applicability in real-world scenarios, demonstrating the importance of ongoing research and development in the field of object detection.
YOLOv12 establishes a new paradigm in real-time object detection through strategic integration of attention mechanisms with optimized architectural components. The model achieves superior accuracy-efficiency trade-offs compared to predecessor architectures while maintaining deployment flexibility across diverse hardware platforms. The attention-centric design addresses fundamental challenges in small object detection and complex scene understanding, positioning YOLOv12 as a significant advancement in computer vision applications requiring real-time performance constraints. YOLOv12m achieves higher mean Average Precision (mAP) on the COCO dataset while using up to 25% fewer parameters compared to YOLOv11m, demonstrating improved computational efficiency without accuracy degradation. The model variants (YOLOv12n, YOLOv12s, YOLOv12m, YOLOv12l, YOLOv12x) provide scalable solutions accommodating diverse deployment scenarios from edge devices to high-performance computing environments. Comparative analysis reveals that YOLOv12 consistently surpasses its predecessors in both inference speed and accuracy metrics24.
The integration of Explainable Artificial Intelligence (XAI) methodologies within YOLOv frameworks addresses the inherent opacity of deep learning models by elucidating feature attribution and decision pathways in object detection tasks. Techniques such as gradient-weighted class activation mapping (Grad-CAM) and LayerCAM are employed to visualize spatial regions prioritized by the model during inference, linking activation patterns to specific egg size classification outcomes. This transparency validates the model’s alignment with biologically relevant features and enables stakeholders to audit biases or misalignments in automated agricultural systems. The fusion of XAI with YOLOv thus bridges the gap between predictive accuracy and methodological interpretability, fostering trust in smart farming applications while guiding iterative refinements for domain-specific robustness.
Despite the rapid evolution of YOLO architectures, existing models remain limited in their interpretability. Their high accuracy in object detection comes at the cost of transparency, as they provide little insight into which image regions or features drive classification outcomes. This limitation restricts their adoption in agricultural applications, where decisions must be biologically meaningful and verifiable by human experts. In the context of egg size classification, it is insufficient to achieve high accuracy alone; the model must also demonstrate that its predictions align with observable traits such as egg contours and morphological dimensions.
To address this gap, this study proposes an interpretable deep learning framework based on YOLOv12 integrated with explainable AI (XAI) techniques. By combining real-time detection performance with visualization methods such as Grad-CAM and EigenCAM, the framework provides both accurate and transparent predictions. This contribution distinguishes our approach from prior YOLO applications by bridging the gap between predictive accuracy and interpretability, thereby offering a more trustworthy solution for automated egg grading in the poultry industry.
Consequently, this research aims to address these challenges by developing an automated system classifying egg sizes using interpretable YOLO object detection models, specifically YOLOv12, YOLOv10, YOLOv9, YOLOv8, and YOLOv725. Our research is organized into five distinct sections: (1) the first section presents the literature review and identifies research gaps; (2) the second section outlines the methodological framework; (3) the third section encompasses the statistical analysis and results of the model evaluation. This study holds significant importance as the exceptional performance of these models demonstrates their potential to substantially improve quality control, market dynamics, and consumer satisfaction within the poultry industry.
Materials and methods
This section describes the proposed models. Figure 1 shows the main steps of the proposed YOLOv12-X model.
Fig. 1.
The main steps of the proposed YOLOv12-X model.
Egg samples and image acquisition system
The data collection process involved the acquisition of 844 images of fresh brown chicken egg samples from a local market in Hangzhou City, Zhejiang Province, China. Each egg was labeled and its weight and volume were determined using a digital scale and a drainage method, respectively. The weight and volume measurements served as ground truth data for training and validation of the egg size detection model. The image acquisition system consisted of an MV-CA016-10UC industrial camera with a resolution of
pixels and a frame rate of 30 fps, as shown in Fig. 2. The camera was paired with an MVL-HF0628M-6MPE lens with a fixed 6 mm focal length. The camera was mounted vertically at a height of 45 cm above the conveyor belt. The vertical alignment minimized perspective distortion and ensured uniform egg appearance across samples. Although the MV-CA016-10UC camera is capable of higher frame rates (up to 165.9 fps), the acquisition system was configured at 30 fps. This frame rate was intentionally selected to align with the conveyor belt speed (0.2 m/s) and controlled illumination, thereby ensuring stable image capture without motion blur while maintaining manageable data storage and processing requirements.
Fig. 2.
The image acquisition system.
The isolation cabinet was custom-designed and fabricated to simulate a commercial conveyor belt environment under controlled lighting conditions. The cabinet measured 60 cm (length) × 40 cm (width) × 50 cm (height) and was constructed using matte black acrylic sheets to minimize light reflections. A uniform LED lighting array (4 W), a total of 160 pieces, was integrated into the top panel to ensure consistent illumination and reduce shadow artifacts. The conveyor belt mechanism inside the cabinet was configured to operate at a constant speed of 0.2 m/s.
An LED light is used to eliminate part of the shadow formed on the conveyor belt by projecting uniform light onto the eggs and conveyor belt. The specifications and positioning of the camera ensured that the acquired images provided sufficient detail and clarity for the deep learning model to detect and classify the eggs based on their size accurately. The labeled egg samples, along with their corresponding weight, volume, and image data, formed the comprehensive dataset used throughout the study. All experiments were carried out in Zhejiang University facilities.
A total of 844 eggs were selected using a stratified random sampling approach, as shown in Table 1. Within each weight class (Small, Medium, Large, Extra-Large), eggs were randomly sampled to ensure proportional representation across the dataset. The selection process was performed manually using a calibrated digital scale, and only undamaged, clean-surfaced eggs were included to ensure consistency in imaging and annotation. As shown, the dataset was approximately balanced, with a variation of less than 10% between class sizes. This natural balance reduced the risk of model bias during training and obviated the need for oversampling or undersampling techniques.
Table 1.
The distribution of samples across egg size classes.
| Small | Medium | Large | Extra-large | |
|---|---|---|---|---|
| Training | 142 | 128 | 129 | 119 |
| Testing | 56 | 93 | 86 | 91 |
| Total | 198 | 221 | 215 | 210 |
Dataset annotation
In this study, the classification of brown chicken eggs was expanded to four distinct categories, as defined by China’s Standardization Administration: Small eggs (Segg), Medium eggs (Megg), Large eggs (Legg), and Extra-Large eggs (XLegg). The classification criteria used is shown in Table 2. All egg samples were weighed using a calibrated digital scale with
g precision before image acquisition. Each egg was then assigned to its respective category based on these weight intervals, which served as the ground truth for model training and evaluation. These thresholds were also used to label the dataset during annotation with LabelImg.
Table 2.
The weight-based thresholds used to categorize the eggs.
| Class | Thresholds |
|---|---|
| Small (Segg) | Less than 48 g |
| Medium (Megg) | 48–58 g |
| Large (Legg) | 58–68 g |
| Extra-large (XLegg) | Greater than 68 g |
Each egg is labeled by its size and manually placed on the conveyor belt in a single line and oriented lengthwise (major axis aligned with the belt direction). The MV camera was connected via a USB port to a Microsoft Windows 10 laptop, pre-installed with MVS for windows software to capture the videos and the conveyor belt ran at a constant speed. The conveyor belt operated at a constant speed of 0.2 meters per second (m/s). This speed was selected to ensure that the camera’s 30 frames-per-second (fps) capture rate could acquire images without motion blur, while also simulating a moderate throughput typical of small- to medium-scale egg grading systems. Dataset annotation was performed manually using LabelImg26 to systematically annotate the entirety of the image dataset. This procedure of image annotation is depicted in Fig. 3. Each egg was enclosed with a single bounding box that closely followed its outer contour. The ground truth class labels (Segg, Megg, Legg, XLegg), determined based on measured weight intervals, were manually assigned to each bounding box during the annotation process. No semi-automated labeling methods were used, ensuring consistency and precision across the dataset.
Fig. 3.
The image annotation process.
Data augmentation: to enhance generalization, we applied multiple data augmentation techniques during training (e.g., random horizontal flip, brightness variation, scaling), effectively expanding the diversity of training samples. This dataset was further subdivided into two distinct parts: a training set, and a testing set.
YOLOv12 model
YOLOv12 represents a paradigm shift in real-time object detection by incorporating attention-centric mechanisms into the traditional YOLO framework while maintaining computational efficiency. This latest iteration addresses fundamental limitations of previous YOLO architectures by integrating three core innovations: Area Attention mechanisms, Residual Efficient Layer Aggregation Networks (R-ELAN), and optimized architectural components including FlashAttention integration.
YOLOv12m achieves higher mean Average Precision (mAP) on the COCO dataset while using up to 25% fewer parameters compared to YOLOv11m, demonstrating improved computational efficiency without accuracy degradation. The model variants (YOLOv12n, YOLOv12s, YOLOv12m, YOLOv12l, YOLOv12x) provide scalable solutions accommodating diverse deployment scenarios from edge devices to high-performance computing environments. Comparative analysis reveals that YOLOv12 consistently surpasses its predecessors in both inference speed and accuracy metrics. Notably, YOLOv12x achieves approximately 56% mAP at a mere 12ms inference time, surpassing all prior YOLO versions. In the low-latency regime (1–5ms), YOLOv12s maintains high accuracy of approximately 49% mAP, marking a significant milestone for real-time applications demanding both speed and precision. The YOLO models were initialized with pretrained weights from the COCO dataset. While COCO is a general-purpose dataset with objects unrelated to eggs, its large-scale diversity equips the model with transferable low and mid-level features, such as edges, contours, and shape boundaries. These features proved highly beneficial for egg classification, where contour and size morphology are key determinants.
YOLOv12 supports comprehensive computer vision tasks including object detection, instance segmentation, image classification, pose estimation, and oriented object detection. This versatility stems from the unified architectural framework that adapts to different task requirements through specialized head configurations while maintaining the core attention-centric backbone design. The model’s enhanced feature extraction capabilities enable reliable detection in dense environments such as urban traffic and crowded public spaces. In automotive applications, it bolsters advanced driver-assistance systems (ADAS) and autonomous vehicles through precise detection and tracking of road users. Healthcare applications benefit from improved accuracy in medical image analysis, while agricultural monitoring systems leverage robust small-object detection capabilities24.
Architectural framework
The model architecture departs from conventional CNN-only approaches while preserving the essential real-time inference capabilities that define the YOLO series. Through leveraging attention-centric design centered on area attention, which segments feature maps to focus more effectively on critical regions, YOLOv12 addresses previously unmet needs in detecting small, partially occluded, or overlapping objects27. The backbone network of YOLOv12 employs the Residual Efficient Layer Aggregation Network (R-ELAN) as its fundamental building block. This design addresses gradient bottlenecks and enhances feature reuse, boosting the model’s ability to capture intricate object details across various sizes and shapes. The mathematical formulation of the enhanced convolutional operations can be expressed as:
![]() |
1 |
where
represents the output feature map,
denotes the convolutional filters,
is the input feature map, and
represents the bias term. R-ELAN addresses optimization challenges introduced by attention mechanisms through block-level residual connections and scaling techniques to ensure stable training, along with a redesigned feature aggregation method that improves both performance and efficiency. The residual connections incorporate a scaling factor (default 0.01) to maintain training stability, particularly beneficial for larger model variants.
Area attention mechanism
The Area Attention mechanism represents a novel self-attention approach that processes large receptive fields efficiently by dividing feature maps into l equal-sized regions (defaulting to 4), either horizontally or vertically. This innovation addresses the computational complexity inherent in traditional attention mechanisms while maintaining substantial receptive fields. The mathematical foundation of the Area Attention can be formulated as:
![]() |
2 |
where
are the query, key, and value matrices derived by linear projections of the feature map output from the backbone, where B is the batch size, N is the number of spatial tokens (flattened feature map positions), and d is the embedding dimension.
where the feature map segmentation reduces computational complexity from
to
, with L representing the number of segments. This modification reduces the computational cost to
from the traditional
, making the model more efficient without sacrificing accuracy.
Network head and neck design
The neck component functions as an intermediary between the backbone and detection head, implementing feature aggregation and refinement processes. A hallmark innovation is the area attention mechanism accelerated by FlashAttention, which enhances the model’s focus on critical regions in cluttered scenes. The mathematical representation of this segmented attention operation is:
![]() |
3 |
where subscript ’seg’ denotes segmented feature maps, enabling reduced memory transfers and computational overhead while maintaining real-time inference capabilities. The detection head transforms refined feature representations into final predictions through streamlined multi-scale pathways. The loss function incorporates attention-weighted terms:
![]() |
4 |
where
parameters represent weighting coefficients, and
incorporates attention-based regularization terms.
YOLOv12 leverages Flash Attention to minimize memory access overhead, addressing the memory bottleneck of attention mechanisms and closing the speed gap with CNNs. This optimization enables efficient processing of high-resolution inputs while maintaining real-time performance constraints.
XAI models
XAI methodologies are critical for interpreting the decision-making processes of deep learning models, particularly in applications requiring transparency, such as agricultural product classification28,29. This section delineates seven Class Activation Mapping (CAM) techniques integrated into the fine-tuned YOLOv architecture to elucidate the model’s focus during egg size detection and classification. Gradient-weighted Class Activation Mapping (GradCAM) generates visual explanations by leveraging gradient information flowing into the final convolutional layer30. The gradients, representing the importance of each neuron for a target class, are globally averaged and combined with feature maps to produce a localization heatmap. While effective in highlighting salient regions, GradCAM occasionally emphasizes coarse areas due to its reliance on averaged gradients. HiResCAM refines traditional GradCAM by employing element-wise multiplication of gradients and activations, preserving spatial resolution and minimizing signal dilution. This approach enhances precision in identifying discriminative features, which is particularly advantageous for fine-grained tasks such as distinguishing subtle variations in egg dimensions. However, its computational complexity increases marginally compared to baseline methods.
GradCAM++ extends GradCAM by incorporating weighted average gradients, accounting for positive and negative influences within feature maps. This modification improves localization accuracy, especially for objects with irregular shapes or multiple instances, aiding in detecting overlapping or variably sized eggs in cluttered environments. XGradCAM introduces a normalized weighting scheme, scaling gradients by their corresponding activations before aggregation. This adjustment mitigates noise in heatmap generation, yielding sharper visualizations that align more closely with the model’s true regions of interest. The method proves beneficial for validating feature relevance in ambiguous classification scenarios. LayerCAM aggregates activation maps across all spatial positions within a convolutional layer, exploiting multi-scale information inherent in deep networks.
EigenGradCAM combines gradient data with Principal Component Analysis (PCA), utilizing the dominant eigenvector of feature map gradients to generate explanations. This technique reduces redundancy in activation patterns, emphasizing the most influential features while suppressing irrelevant background noise. EigenCAM, a gradient-free variant, applies PCA directly to activations, extracting principal components that capture maximal variance in the feature space. As a class-agnostic approach, EigenCAM provides generalized insights into the model’s attention mechanisms, independent of specific output classes31. Collectively, these XAI frameworks enhance the interpretability of the YOLOv model’s predictions, enabling stakeholders to validate the spatial and contextual reasoning behind egg-size classification.
The inclusion of seven Class Activation Mapping (CAM) variants—Grad-CAM, Grad-CAM++, HiResCAM, XGradCAM, LayerCAM, EigenGradCAM, and EigenCAM—was intentionally designed to capture a comprehensive view of the model’s attention across different interpretability paradigms. These methods represent both gradient-based and gradient-free approaches, each with distinct advantages in terms of resolution, class specificity, and computational complexity. The rationale behind using this diverse set of CAM techniques was to assess consistency and reliability in model interpretation from multiple perspectives. For example: Grad-CAM and Grad-CAM++ offer robust baseline visualizations but tend to produce coarse attention maps. HiResCAM improves spatial precision, which is valuable in tasks involving subtle visual cues like size differentiation. EigenCAM provides a class-agnostic view, revealing model saliency independent of prediction labels—useful for detecting possible biases or overfitting. LayerCAM and XGradCAM allow visualization at different convolutional depths, helping assess feature propagation.
The integration of Explainable Artificial Intelligence (XAI) methodologies within YOLO frameworks addresses the inherent opacity of deep learning models by elucidating feature attribution and decision pathways in object detection tasks. Techniques such as Gradient-weighted Class Activation Mapping (Grad-CAM)32 and LayerCAM33 have been widely adopted to visualize spatial regions prioritized by deep models during inference. Recent studies have demonstrated the utility of such approaches in agricultural domains, for example, in crop and food quality assessment30,31. These references highlight the growing importance of XAI in ensuring transparency and trust in automated agricultural systems. By applying Grad-CAM, EigenCAM, and related methods to YOLOv12, this study builds upon these advances to validate that predictions align with biologically relevant egg features such as contours and morphological structure.
Results and analysis
This research leveraged Google Colaboratory (Colab), a cloud-based computational environment, to conduct the experimental analyses. The reliance on Colab’s pre-configured virtual machine instances, equipped with the deep learning package used is PyTorch 2.3.1 and the programming language used is Python 3.9 under Ubuntu 20.04, eliminated the need for local resource provisioning as shown in Table 3. While specific hardware configurations within the Colab virtual machines were directly controlled, the consistent utilization of the platform ensured a degree of standardization across experimental runs, minimizing potential variations stemming from differing underlying hardware resources.
Table 3.
Software and hardware environment specifications.
| Software | Hardware |
|---|---|
| Operating system: Ubuntu 20.04 | CPU: 2 vCPU 2.2Ghz |
| Programming language: Python 3.9 | GPU: Tesla T4 (16 GB) × 1 |
| Deep learning framework: PyTorch 2.3.1 | RAM: 16 GB |
Specifically, the training utilized a Tesla T4 GPU with 16 GB of dedicated GPU memory, supported by a 2 vCPU 2.2 GHz processor and 16 GB of RAM. The system was configured with Ubuntu 20.04 and employed Python 3.9 in conjunction with the PyTorch 2.3.1 deep learning framework. The average training time for the YOLOv12 model, using the specified hardware, was approximately 3.8 hours for 300 epochs. This training time may vary slightly depending on runtime availability and system load on Colab servers.
The proposed YOLOv12-X model was trained for 300 epochs using mini-batches of size 32. An initial learning rate of 0.01 and a weight decay of 0.0005 were utilized. The training process incorporated a warm-up phase spanning the first three epochs, during which the momentum was set to 0.8. After this phase, momentum was increased to 0.937. Weight decay was fixed at 0.0005 to regularize the model and mitigate overfitting. Binary cross-entropy was employed for classification loss, and Complete Intersection over Union (CIoU) was used for bounding box regression. Several standard techniques are applied to improve the model’s generalization capability. These included horizontal flipping, random brightness and contrast adjustment, image scaling, and translation. These augmentations were applied probabilistically during training to simulate natural variability in image acquisition conditions and to reduce model sensitivity to illumination and orientation variations. Comprehensive details regarding the experimental setup and hyperparameter configurations are provided in Tables 3 and 4, respectively.
Table 4.
The list of parameters and their corresponding values.
| Parameters | Values |
|---|---|
| lr0 | 0.01 |
| lrf | 0.1 |
| obj | 0.7 |
| IOU_t | 0.2 |
| Momentum | 0.937 |
| Weight decay | 0.0005 |
| box | 0.05 |
| fl_gamma | 0.0 |
| Warmup momentum | 0.8 |
| Warmup epochs | 3 |
| Epochs | 300 |
| Batch size | 32 |
The values of
and
are manually tuned based on empirical performance. In the experiments, we adopted
and
, following configurations reported in recent object detection literature. This configuration was found to effectively balance the influence of classification confidence and IoU during the alignment process. These values were not treated as learnable parameters during training, but rather fixed coefficients to stabilize the allocation of high-quality anchors. All input images were resized to 640 × 640 pixels, which aligns with the default resolution in most YOLO configurations.
All YOLO models evaluated in this study, including YOLOv12, were initialized using pretrained weights provided by their respective official implementations. These weights were derived from training on the COCO dataset. We then fine-tuned the models on our custom egg dataset. This transfer learning approach significantly accelerated convergence and improved generalization, especially given the moderate size of our training set (844 images).
Model evaluation
Performance evaluation used three established metrics commonly utilized in object detection and classification tasks, as shown in Fig. 4.
Fig. 4.

The main elements of the confusion matrix.
Precision quantifies the accuracy of positive predictions, representing the proportion of correctly identified positive instances among all predicted positives34.
![]() |
5 |
Recall assesses the model’s sensitivity, measuring the proportion of actual positive instances correctly identified.
![]() |
6 |
Individual class average precision (
) contributes to the overall mAP calculation.
![]() |
7 |
Finally, mean Average Precision (mAP) provides a holistic assessment of detection accuracy by CIoU between predicted and ground-truth bounding boxes.
![]() |
8 |
The mAP metrics, mAP50, mAP75, and mAP50-95, employ varying IoU thresholds. Specifically, mAP50 utilizes an IoU threshold of 0.50, mAP75 uses 0.75, and mAP50-95 averages precision across IoU thresholds ranging from 0.50 to 0.95 in 0.05 increments. This broader assessment, which encompasses multiple IoU thresholds, is generally considered the most rigorous metric, as it evaluates the model’s performance over a wider spectrum of IoU requirements. Consequently, mAP50-95 represents the most stringent evaluation, followed by mAP75, with mAP50 exhibiting the least stringent criteria.
Baseline models
To provide a benchmark for evaluating the effectiveness of our proposed approach, we first assess the performance of state-of-the-art object detection models as baselines. This section presents the results obtained from YOLOv9 and YOLOv10, two recent and widely used versions of the YOLO architecture. These models are evaluated under the same experimental setup to ensure consistency and comparability. The subsequent subsections detail their individual performance metrics and qualitative observations.
YOLOv9
Figure 5 comprises a grid of plots that provide insights into the training and evaluation metrics of a model, organized into a 2
5 layout: (1) top row (left to right): Train/Box OM: this plot illustrates the training metrics related to bounding box predictions. The curve shows the relationship between the number of epochs and the corresponding metric values, with blue points representing actual results and a dotted orange line indicating a smoothed trend. Train/Cls OM: this plot presents the training metrics for classification accuracy, following a similar structure to the first plot. The graph indicates how classification performance evolves over epochs. Train/Diff OM: this graph represents differences in performance metrics during training, focusing on a specific aspect of the model’s learning. Train/Box OO: this plot shows the object detection performance metrics related to bounding box predictions in an out-of-order dataset or a different evaluation context.
Fig. 5.
Comparison of loss and accuracy curves for YOLOv9.
(2) Bottom row (left to right): metrics/recall: this plot displays the recall metric across training epochs, providing insight into the model’s ability to identify relevant instances correctly. Metrics/mAP50(B): This graph illustrates the mAP at a specific IoU threshold of 0.50, indicating overall object detection performance. Metrics/mAP50-95(B): this plot presents the mean average precision across multiple IoU thresholds (from 0.50 to 0.95), offering a broader perspective on the model’s accuracy in various conditions. Train/Metrics/Precision(B): this graph shows the precision metric, reflecting the model’s accuracy in predicting positive instances across training epochs.
Figure 6 illustrates the performance of the YOLOv9 model in classifying egg images into four categories. The matrix demonstrates the model’s ability to accurately classify eggs of various sizes while effectively distinguishing them from background elements. The diagonal elements of the confusion matrix represent the number of correctly classified samples for each class. For example, the value of 1.00 on the diagonal indicates that all Legg instances were correctly identified as Legg. The off-diagonal elements represent the number of instances misclassified as other classes. For instance, the value of 0.50 in the row for Legg and the column for XLegg suggests that 0.50% of Legg instances were incorrectly classified as XLegg.
Fig. 6.

The confusion matrix of YOLOv9.
The confusion matrix offers important information on the strengths and weaknesses of the model. The high values on the diagonal indicate the model’s ability to accurately classify eggs into their respective categories. The relatively low off-diagonal values suggest that the model is effective in distinguishing between different egg sizes and background elements.
Figure 7 illustrates the precision-recall curve of the YOLOv9 model in classifying egg images into five categories: Segg (small egg), Megg (medium egg), Legg (large egg), XLegg (extra-large egg), and background. The curve depicts the trade-off between precision and recall for each class and the overall model. Precision represents the proportion of correctly classified instances among all instances predicted as a particular class. Recall represents the proportion of correctly classified instances among all actual instances of a particular class. A high precision indicates that the model is effective at avoiding false positives, while a high recall indicates that the model is effective at avoiding false negatives.
Fig. 7.
The precision-recall curve of YOLOv9.
The precision-recall curve for each class demonstrates the model’s performance at different classification thresholds. As the threshold increases, precision generally increases but recall decreases. Conversely, as the threshold decreases, recall generally increases but precision decreases. The optimal threshold depends on the specific application requirements and the desired trade-off between precision and recall. The overall mAP@0.5 score of 0.994 indicates that the YOLOv9 model achieves high average precision across all classes at an IoU threshold of 0.5. This suggests that the model is effective in accurately classifying eggs of various sizes while maintaining a low false positive rate.
Figure 8 presents the precision-confidence curve of the YOLOv9 model in classifying egg images into five categories. The curve depicts the relationship between precision and confidence for each class and the overall model. Precision represents the proportion of correctly classified instances among all instances predicted as a particular class. Confidence refers to the model’s estimated probability that an instance belongs to a specific class. A high precision indicates that the model is effective at avoiding false positives, while a high confidence score suggests that the model is confident in its predictions.
Fig. 8.
The precision-confidence curve of YOLOv9.
The precision-confidence curve for each class demonstrates how precision varies with confidence. As confidence increases, precision generally increases, indicating that the model is more likely to make correct predictions when it is highly confident. However, there are instances where the model is highly confident but still makes incorrect predictions. The overall precision score of 1.00 at a confidence threshold of 0.995 indicates that the YOLOv9 model achieves perfect precision when considering only predictions with a confidence score above 0.995. This suggests the model is highly effective in accurately classifying eggs of various sizes while maintaining a low false positive rate.
YOLOv10
Figure 9 presents a series of loss curves and evaluation metrics for the YOLOv10 model, highlighting its performance across various aspects of training. The upper row illustrates the training and validation loss for box and classification metrics, where both metrics demonstrate a steady decline, suggesting effective learning and convergence of the model. The smooth lines indicate a reduction in variability, which reinforces the stability of the training process. In the lower section, recall and precision metrics are depicted alongside the mAP at different IoU thresholds. The consistently high values in recall and precision metrics indicate that the model maintains robust performance throughout the training phases. Overall, these results suggest that the enhancements made to the YOLOv10 architecture contribute to improved feature extraction and model reliability during object detection tasks.
Fig. 9.
Comparison of loss and accuracy curves for YOLOv10.
Figure 10 displays the confusion matrix for the YOLOv10 model. The matrix highlights the number of true positive identifications as well as instances of misclassifications, including false negatives and false positives. Notably, the model demonstrates effective recognition of the “Legg” category, achieving 84 true positives, while the “Megg” category exhibits a commendable performance with 91 true positives. However, the “Segg” category shows a more significant challenge, with only 55 true positives and 4 false negatives. Additionally, the “XLegg” category recorded 89 correct identifications, alongside minimal misclassifications. The background class reveals a few instances of confusion, with a total of two misclassifications. In general, the matrix provides valuable insight into the strengths and weaknesses of the model in different categories, identifying potential areas for further enhancement.
Fig. 10.

The confusion matrix of YOLOv10 model.
Figure 11 illustrates the precision-confidence curves for different categories within the YOLOv10 model, providing a comparative analysis of performance across classifications. Each curve represents the relationship between precision and confidence levels for all categories. The graph demonstrates that all categories achieve high precision values, approaching 1.0 as confidence increases. The curves for Legg and XLegg display particularly strong performance, consistently maintaining high precision throughout the range of confidence levels. In contrast, the Small egg category exhibits slightly lower precision, particularly at lower confidence thresholds. The overall trend indicates that as confidence rises, precision remains robust across categories, highlighting the model’s effectiveness in accurately identifying objects within the specified classes.
Fig. 11.

The precision confidence curve for YOLOv10.
Figure 12 displays six images of eggs, each enclosed within a bounding box and annotated with the label “Legg” and a confidence score ranging from 0.94 to 0.96. The eggs exhibit variations in shade, suggesting potential differences in color or lighting conditions. The images are presented against a dark background, with the eggs resting on a wire rack. The figure illustrates the model’s object detection capabilities, showcasing its ability to accurately identify and localize eggs within an image.
Fig. 12.
A sample of the output of the YOLOv10 model.
The proposed YOLOv12-X model
YOLOv12 establishes a new paradigm in real-time object detection through strategic integration of attention mechanisms with optimized architectural components. The model achieves superior accuracy-efficiency trade-offs compared to predecessor architectures while maintaining deployment flexibility across diverse hardware platforms. The attention-centric design addresses fundamental challenges in small object detection and complex scene understanding, positioning YOLOv12 as a significant advancement in computer vision applications requiring real-time performance constraints. The innovations introduced in YOLOv12, particularly the Area Attention mechanism, R-ELAN architecture, and FlashAttention integration, collectively demonstrate the potential for attention-based approaches in high-speed computer vision systems. These contributions advance the state-of-the-art in real-time object detection while providing a foundation for future developments in attention-centric architectures.
Figure 13 shows the training and validation performance metrics for a YOLOv12-X model across approximately 300 epochs. The training curves show typical deep learning behavior with all loss components (box loss, classification loss, and distribution focal loss) decreasing steadily from their initial high values and converging to low, stable values by around epoch 100. The validation losses exhibit more fluctuation, particularly noticeable in the validation box loss, which is characteristic of the model’s performance on unseen data. The evaluation metrics demonstrate strong model performance, with precision, recall, and both mAP50 and mAP50-95 scores rapidly ascending from near zero to high values (approaching 1.0 for precision and recall, and around 0.98 for mAP metrics) within the first 50 epochs and then maintaining these high performance levels. The smooth convergence of training losses combined with the sustained high validation metrics suggests successful model training without significant overfitting, indicating that YOLOv12-X achieved robust object detection performance on the dataset.
Fig. 13.
Comparison of loss curves for YOLOv12-X.
Figure 14 displays the confusion matrix for the YOLOv12-X model. The matrix highlights the number of true positive identifications as well as instances of misclassifications, including false negatives and false positives. The model demonstrates effective recognition of the “Legg” category, achieving 84 true positives, while the “Megg” category exhibits a commendable performance with 92 true positives. Additionally, the ’Segg’ category and ’XLegg’ category recorded 55 and 90 correct identifications, respectively.
Fig. 14.

The confusion matrix of YOLOv12-X model.
Figure 15 illustrates the precision-confidence curves for different categories within the YOLOv12-X model, providing a comparative analysis of performance across classifications. Each curve represents the relationship between precision and confidence levels for all categories. The graph demonstrates that all categories achieve high precision values, approaching 1.0 as confidence increases. The curves for Legg and XLegg display particularly strong performance, consistently maintaining high precision throughout the range of confidence levels. In contrast, the Small egg category exhibits slightly lower precision, particularly at lower confidence thresholds.
Fig. 15.

The precision confidence curve for YOLOv12-X.
Figure 16 summarizes the performance metrics of the YOLOv12-X model across multiple evaluation categories, demonstrating consistent precision in egg size classification and detection tasks. The model achieves a performance range of 0.90–0.98, underscoring its reliability in agricultural automation applications. These results validate the architecture’s capability to balance precision and adaptability, meeting the demands of real-world smart farming systems.
Fig. 16.
The results of testing of the YOLOv12-X model.
XAI results
The EigenCAM heatmap illustrates the principal activation regions identified by the YOLOv12-X model during egg size classification, as shown in Figure 17. By decomposing feature map variances, the technique highlights spatially significant areas without relying on gradient computations, offering class-agnostic interpretability. Dominant components, represented by intensity variations in the heatmap, correlate with structural features critical to the model’s decision-making, such as egg contours and size-related patterns. The visualization underscores YOLOv12’s ability to prioritize salient anatomical attributes while suppressing extraneous background details, validating its alignment with biologically relevant discriminative criteria. This method enhances transparency in automated grading systems by mapping activation coherence to observable egg characteristics.
Fig. 17.
The EigenCAM of YOLOv12.
The EigenCAM heatmap (Fig. 17) highlights spatially significant regions in egg size classification by decomposing feature map variances. Unlike gradient-based methods, EigenCAM provides class-agnostic interpretability, revealing that YOLOv12-X consistently prioritizes egg contours and size-related spatial patterns (e.g., length-to-width ratios) while suppressing background noise. In misclassified large eggs, EigenCAM showed activations biased toward texture artifacts (e.g., cracks or dirt) rather than true size contours, suggesting the model may overfit to superficial features in noisy data. For small eggs misclassified as medium, activations were weak or fragmented, indicating low feature coherence—likely due to occlusion or atypical orientations.
Figure 18 shows the GradCAM of YOLOv12-X. GradCAM’s gradient-weighted visualizations complement EigenCAM by showing how local feature sensitivity influences decisions. High-intensity regions often align with egg boundaries, but some cases reveal “hallucinations” (e.g., activations on shadows mistaken for contours). In 15% of errors, GradCAM highlighted non-egg regions (e.g., tray edges), exposing a need for better spatial regularization during training.
Fig. 18.
The GradCAM of YOLOv12-X.
The EigenCAM and GradCAM visualizations provide critical insights into YOLOv12-X’s decision-making process for egg size classification. EigenCAM reveals that the model primarily focuses on biologically relevant features, such as egg contours and size-related spatial patterns, while suppressing background noise. However, analysis of misclassified cases shows limitations—false positives often arise when the model overfits to texture artifacts like cracks or dirt, while false negatives occur due to weak activations in occluded or atypically oriented eggs. GradCAM further exposes dependencies on edge features and occasional “hallucinations,” where shadows or tray edges are incorrectly weighted. These findings highlight actionable areas for improvement, such as augmenting training data with occlusions and synthetic noise to reduce texture bias, incorporating spatial attention mechanisms to reinforce contour detection, and using adversarial validation to refine the dataset. The XAI visualizations of the ResNet50 model and the ResNet101 model are presented in “Appendix”.
Model validation
Table 5 presents a comparative analysis of five different YOLO object detection models in terms of AP across various egg size categories and the mAP. YOLOv8 achieves the highest overall mAP at 99.5%, demonstrating consistent performance across all size categories, with AP values of 99.5% for small and medium eggs, and 99.4% for both large and x-large eggs. YOLOv12 closely follows with an impressive mAP of 99.4%, showcasing strong metrics across the board, particularly in the small and x-large egg categories. YOLOv9 records a mAP of 99.4%, exhibiting slightly lower performance in the large and x-large categories compared to YOLOv8 and YOLOv10. YOLOv7, while still effective, presents the lowest mAP at 99.2%, reflecting a minor decline in precision for medium, large, and x-large eggs. Finally, the results indicate that all models perform exceptionally well, YOLOv8 and YOLOv12-X achieve the best performance in detecting eggs of various sizes. The proposed model in this study is YOLOv12-X, which we identified as the most balanced candidate in terms of accuracy, computational efficiency, and interpretability suitability for real-time agricultural applications. YOLOv12-X was selected for deeper analysis based on its high performance (mAP = 99.4%), end-to-end architecture, and practical advantages in inference time.
Table 5.
The results of the different YOLO object detection models.
| Model | AP (small egg) | AP (medium egg) | AP (large egg) | AP (XLarge egg) | mAP |
|---|---|---|---|---|---|
| YOLOv12-X | 99.5 | 99.3 | 99.4 | 99.4 | 99.4 |
| YOLOv10 | 99.5 | 99.4 | 98.8 | 99.3 | 99.3 |
| YOLOv9 | 99.5 | 99.5 | 99.3 | 99.2 | 99.4 |
| YOLOv8 | 99.5 | 99.5 | 99.4 | 99.4 | 99.5 |
| YOLOv7 | 99.6 | 99.2 | 99.0 | 99.1 | 99.2 |
Table 7 shows a comparative assessment of various state-of-the-art detection models, highlighting their respective accuracy and mAP metrics. The performance results reported in this table are based on datasets of different sizes (YOLOv12: 844 images, RTMDet: 3726 images, YOLOv5: 800 images). The proposed YOLOv12-X model demonstrates a high performance, achieving an accuracy of 99.4% and an mAP of 99.4%, indicating its efficacy in object detection challenges. In contrast, the RTMDet model5 exhibits an accuracy of 94.8% and a significantly lower mAP of 79.2%, suggesting limitations in precision and overall reliability. The YOLOv5 model35 records an accuracy of 96.4% and an mAP of 95.2%, reflecting a strong performance but still falling short of the proposed model’s metrics. These results show that the proposed model outperforms existing detection frameworks, indicating its potential for practical applications in the field.
Table 7.
The results of the comparison of state-of-the-art detection models.
Discussion
The results presented in Table 5 demonstrate the exceptional performance of all five YOLO object detection models in accurately identifying eggs of varying sizes. Each model achieved remarkably high AP scores across all egg size categories, indicating their proficiency in detecting eggs of diverse dimensions. The superior performance of these models can be attributed to several factors. First, the YOLO architecture is inherently efficient and robust, allowing for rapid and accurate object detection. Second, the models were likely trained on a large and diverse dataset of egg images, enabling them to learn and generalize well to different egg variations. Third, the advancements in YOLO architecture, such as the introduction of new features and techniques in YOLOv12, have contributed to the improved performance.
YOLOv7 demonstrated competitive accuracy but was relatively limited by its deeper backbone and higher computational demand, which impacted inference speed and generalization in smaller object classes. YOLOv8 introduced decoupled head structures and an enhanced feature pyramid, leading to moderate improvements in class-specific accuracy but showed slightly lower mAP compared to later versions under our training configuration. YOLOv9 benefited from the integration of lightweight attention mechanisms (e.g., GIRAFFE modules), improving contextual awareness. However, its training stability varied more noticeably across classes. YOLOv10, while promising in terms of architectural innovation, was not fully optimized or validated in our specific application context, and thus its comparative performance remains exploratory. YOLOv12-X, which achieved the highest performance in our study, leverages task-aligned learning and adaptive label assignment. These modifications improved its capacity to balance localization and classification loss, particularly benefiting categories with subtle morphological differences (e.g., Megg vs. Segg).
To account for variability across different training runs, each experiment was repeated with three random seeds, and the mean ± standard deviation (SD) values are reported. As shown in Tables 5 and 6, YOLOv12-X consistently achieved the highest AP and mAP scores. However, we note that some of the numerical differences between models (e.g., 99.4% vs. 99.5%) fall within the margin of experimental variability, as indicated by overlapping confidence intervals. These results suggest that while the incremental gains may not be statistically significant on their own, the consistent trend across seeds provides stronger evidence of YOLOv12’s robustness and suitability as the most balanced candidate (Table 8).
Table 6.
Comparison of YOLO architectures in terms of accuracy and efficiency metrics (300 epochs).
| Model | Precision (%) | Recall (%) | mAP (%) | Inference speed (ms/image) | FLOPs (G) | Memory usage (MB) |
|---|---|---|---|---|---|---|
| YOLOv8 | 98.9 | 99.3 | 99.5 | 21.19 | 8.1 | 32.4 |
| YOLOv10 | 98.79 | 99.0 | 99.3 | 15.06 | 8.2 | 74.1 |
| YOLOv12-X | 99.0 | 99.7 | 99.4 | 46.1 | 6.3 | 67.96 |
Table 8.
Comparison of YOLO versions on egg dataset with statistical context (mean ± SD across 3 random seeds).
| Model | AP (%) | mAP (%) |
|---|---|---|
| YOLOv7 | 98.9 ± 0.2 | 99.1 ± 0.1 |
| YOLOv8 | 99.0 ± 0.3 | 99.2 ± 0.2 |
| YOLOv9 | 99.2 ± 0.2 | 99.3 ± 0.1 |
| YOLOv10 | 99.3 ± 0.1 | 99.4 ± 0.1 |
| YOLOv12-X | 99.4 ± 0.1 | 99.5 ± 0.1 |
Although all YOLO models demonstrated exceptional performance, it is worth noting that YOLOv12-X exhibited a slight edge in terms of overall mAP. This model is due to specific architectural enhancements or training strategies employed in YOLOv12-X. However, the differences in performance among the models were relatively small, suggesting that all five models are viable options for egg object detection. It is clear that the performance of these models is influenced by various factors, such as the quality and quantity of training data, the specific implementation details, and the computational resources available. The results of this study also have implications for the poultry industry. Accurate egg size detection can enhance quality control by enabling the identification of eggs that do not meet specific size standards. This can help to prevent the sale of substandard eggs and protect the reputation of poultry producers. In addition, accurate detection of egg size can be used to optimize the allocation of eggs to different markets based on consumer preferences.
A closer analysis of misclassification patterns reveals specific weaknesses across models. For example, YOLOv9 occasionally confused the Legg and XLegg categories, likely due to their high visual similarity and partially overlapping morphological traits. YOLOv10, by contrast, exhibited greater difficulty with the Segg category, which may be attributed to class imbalance in the dataset as well as subtle differences in contour boundaries that complicate detection. In addition, minor inconsistencies in manual annotations (e.g., boundary shifts for irregular eggs) could have contributed to these errors. These findings highlight the practical challenges of egg classification and underscore the need for balanced datasets, careful annotation protocols, and explainable architectures that can confirm biologically meaningful decision cues. YOLOv12 with XAI integration addresses some of these limitations by demonstrating more consistent attention to egg contours and size morphology, thereby reducing category-specific misclassifications.
Current research challenges
While this study highlights the strong performance of YOLO-based models in egg detection, certain limitations should be acknowledged. First, the study was conducted on a specific egg image dataset, limiting its generalizability. Variations in egg appearance, lighting, and background clutter can affect model performance. Also, the current study does not account for motion blur, variable lighting, or occlusion effects that occur in automated production environments. Second, the study focused on specific egg-size categories, and the models’ effectiveness on other sizes and shapes remains uncertain. Additionally, factors like egg quality and defects, which require distinct detection criteria, were not considered. Third, the study did not evaluate the computational cost of YOLO models. Although generally efficient, their resource requirements vary based on implementation and hardware, which is crucial for real-world applications with computational constraints.
It is clear that, the comparison presented in Table 7 involves datasets of varying sizes (844, 3726, and 800 images), which may influence the reported performance metrics. Larger datasets can provide models with greater diversity and robustness, while smaller datasets may constrain generalizability. Future work will address this limitation by constructing or adopting a standardized benchmark for egg size classification, enabling fairer and more conclusive evaluations across different architectures.
This research provides a strong foundation for future work in egg object detection. Expanding the evaluation to diverse datasets with varying egg types, lighting, and backgrounds would improve generalizability. Investigating different training strategies, hyperparameter settings, and architectural modifications such as transfer learning, data augmentation, and model ensembling could enhance accuracy and robustness. Integrating egg quality and defect detection would increase practical applicability, potentially requiring new or adapted object detection algorithms. Lastly, optimizing model inference speed and reducing memory usage would improve feasibility for resource-constrained environments.
Conclusion
The detection and categorization of egg size are crucial in the poultry industry, significantly influencing quality control, market dynamics, and customer preferences. Precise egg size detection can improve quality control by identifying eggs that fail to meet established size criteria, thereby preventing the distribution of substandard products and safeguarding the reputation of poultry producers. Furthermore, accurate egg-size classification can facilitate the strategic allocation of eggs to various markets, aligning with consumer preferences and enhancing market efficiency. This study presented an interpretable deep learning framework based on YOLOv12 architecture for real-time egg size detection and classification. The results demonstrated the exceptional performance of all five YOLO object detection models (YOLOv12, YOLOv10, YOLOv9, YOLOv8, and YOLOv7) in accurately identifying eggs of varying sizes. Each model achieved remarkably high AP scores across all egg size categories, consistently surpassing the performance of traditional object detection methods. In particular, YOLOv12-X demonstrated the best mAP score, indicating its remarkable efficacy in detecting eggs of all sizes. These findings underscore the effectiveness of YOLO-based models as precise tools for egg object detection, with YOLOv12-X emerging as a particularly promising candidate for applications demanding accurate and efficient egg identification. The superior performance of these models highlights their potential to significantly improve quality control, market dynamics, and consumer satisfaction within the poultry industry. Furthermore, the results suggest that YOLO-based models can be adapted to other agricultural applications, such as identifying fruits, vegetables, or livestock. The findings of this study also hold significant implications for the poultry industry.
Supplementary Information
Acknowledgements
This work was supported by the National Key R&D Program of China (2023YFD20008).
Author contributions
Conceptualization, E.M.A. and J.P.; methodology, E.M.A., I.G., H.L. and J.P.; software, E.M.A. and I.G.; validation, E.M.A., S.H. and H.L.; formal analysis, E.M.A., J.P. and I.G.; investigation, E.M.A.; resources, J.P.; data curation, E.M.A.; writing—original draft preparation, E.M.A., J.P. and I.G.; writing—review and editing, M.M.A., S.H., H.L. and J.P.; visualization, I.G.; supervision, J.P.; All authors have read and agreed to the published version of the manuscript.
Funding
This work was supported by the National Key R&D Program of China (2023YFD20008).
Data availability
The data presented in this study are available on request from the corresponding author.
Declarations
Competing interests
The authors declare no competing interests.
Footnotes
Publisher’s note
Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.
Supplementary Information
The online version contains supplementary material available at 10.1038/s41598-026-49155-1.
References
- 1.Sun, L., Zhang, P., Feng, S., Qiang, M. & Cai, J. Eggshell crack detection based on the transient impact analysis and cross-correlation method. Curr. Res. Food Sci.4, 716–723. 10.1016/j.crfs.2021.09.012 (2021). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 2.Atwa, E. M. et al. Advances in emerging non-destructive technologies for detecting raw egg freshness: A comprehensive review. Foods13, 3563. 10.3390/foods13223563 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 3.Technavio. Poultry eggs market analysis APAC, North America, Europe, South America, Middle East and Africa—US, Mexico, China, Japan, India—Size and forecast 2025-2029. Accessed 19 Jun 2025 (2023) (2023).
- 4.Technavio. Poultry Eggs Market Analysis APAC, North America, Europe, South America, Middle East and Africa - US, Mexico, China, Japan, India—Size and Forecast 2024–2028. https://www.technavio.com/report/poultry-eggs-market-industry-analysis. Accessed 19 Oct 2024 (2023).
- 5.Yang, X., Bist, R. B., Subedi, S. & Chai, L. A computer vision-based automatic system for egg grading and defect detection. Animals13, 2354. 10.3390/ani13142354 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 6.Jiang, T. et al. Improved yolov8 model for lightweight pigeon egg detection. Animals14, 1226. 10.3390/ani14081226 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 7.Lim, W. S., Kang Lai, D. J., Lim, S. T. & Yeo, B. C. Vision-based egg grading system using support vector machine. Int. J. Robot. Autom. Sci.6, 13–19. 10.33093/ijoras.2024.6.1.3 (2024).
- 8.Sundaresan Geetha, A., Alif, M. A. R., Hussain, M. & Allen, P. Performance metrics and model efficacy. Comparative analysis of yolov8 and yolov10 in vehicle detection. Vehicles6, 1364–1382. 10.3390/vehicles6030065 (2024).
- 9.Liu, C. et al. Single-view measurement method for egg size based on small-batch images. Foods12, 936. 10.3390/foods12050936 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 10.Botta, B., Gattam, S. S. R. & Datta, A. K. Eggshell crack detection using deep convolutional neural networks. J. Food Eng.315, 110798. 10.1016/j.jfoodeng.2021.110798 (2022). [Google Scholar]
- 11.Harnsoongnoen, S. & Jaroensuk, N. The grades and freshness assessment of eggs based on density detection using machine vision and weighing sensor. Sci. Rep.11. 10.1038/s41598-021-96140-x (2021). [DOI] [PMC free article] [PubMed]
- 12.Himel, G. M. S., Islam, M. M., Kader, M. N. & Rahman, M. Artificial intelligence-based smart galliformes farm management system. J. Umm Al-Qura Univ. Eng. Architect.16, 64–77. 10.1007/s43995-024-00089-7 (2025). [Google Scholar]
- 13.Himel, G. M. S. & Islam, M. M. A smart intelligence system for hen breed and disease classification using extra tree classifier-based ensemble technique. J. Electr. Syst. Inf. Technol.12. 10.1186/s43067-025-00191-3 (2025).
- 14.Zhou WeiZhong, Z. W., Feng XinHai, F. X. & Sun GuoJi, S. G. Shape identification of fertile eggs by using computer vision. Trans. CSAE16, 126–130. 10.3321/j.issn:1002-6819.2000.06.032 (2000). [Google Scholar]
- 15.Deng, H., Liu, Y. & Wen, Y. Research on method of detecting egg size by machine vision. J. Huazhong Agric. Univ.25, 452. 10.13300/j.cnki.hnlkxb.2006.04.027 (2006). [Google Scholar]
- 16.Omid, M., Soltani, M., Dehrouyeh, M. H., Mohtasebi, S. S. & Ahmadi, H. An expert egg grading system based on machine vision and artificial intelligence techniques. J. Food Eng.118, 70–77. 10.1016/j.jfoodeng.2013.03.019 (2013). [Google Scholar]
- 17.Redmon, J., Divvala, S., Girshick, R. & Farhadi, A. You only look once: Unified, real-time object detection. In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR). 10.1109/cvpr.2016.91 (IEEE, 2016).
- 18.Sapkota, R. et al. Comprehensive performance evaluation of yolo11, yolov10, yolov9 and yolov8 on detecting and counting fruitlet in complex orchard environments. Qeios. 10.32388/e9y7xi (2024).
- 19.Qiu, X., Chen, Y., Cai, W., Niu, M. & Li, J. Ld-yolov10: A lightweight target detection algorithm for drone scenarios based on yolov10. Electronics13, 3269. 10.3390/electronics13163269 (2024). [Google Scholar]
- 20.Ma, S., Li, W., Wan, L. & Zhang, G. A lightweight fire detection algorithm based on the improved yolov8 model. Appl. Sci.14, 6878. 10.3390/app14166878 (2024). [Google Scholar]
- 21.Ma, N., Wu, Y., Bo, Y. & Yan, H. Chili pepper object detection method based on improved yolov8n. Plants13, 2402. 10.3390/plants13172402 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 22.Wang, A. et al. Yolov10: Real-time end-to-end object detection. arXiv preprint arXiv:2405.14458 (2024).
- 23.Bajpai, M. Yolo models for security and surveillance applications. Int. J. Res. Appl. Sci. Eng. Technol.12, 2513–2518. 10.22214/ijraset.2024.63521 (2024).
- 24.Alif, M. A. R. & Hussain, M. Yolov12: A breakdown of the key architectural features. arXiv:2502.14740v1 (2025).
- 25.Tian, Y., Ye, Q. & Doermann, D. Yolov12: Attention-centric real-time object detectors. arXiv:2502.12524 (2025).
- 26.Tzutalin. Labelimg (2015).
- 27.Ye, Z., Peng, X., Li, D., Zhao, X. & Shi, F. Adaptive multi-scale attention networks fusion in yolov12-lse: A lightweight framework for efficient and robust underwater object detection. Appl. Opt.10.1364/ao.568505 (2025). [DOI] [PubMed] [Google Scholar]
- 28.Ali, S. Methods for Explainable Artificial Intelligence. 139–161 (Institution of Engineering and Technology, 2023).
- 29.Mohaghegh, S. D. Explainable Artificial Intelligence (XAI). 89–122 (CRC Press, 2024).
- 30.Quach, L.-D., Quoc, K. N., Quynh, A. N., Thai-Nghe, N. & Nguyen, T. G. Explainable deep learning models with gradient-weighted class activation mapping for smart agriculture. IEEE Access11, 83752–83762. 10.1109/access.2023.3296792 (2023). [Google Scholar]
- 31.Ganepola, V. et al. Xai-resunet: Analysing the impact of pre-training in resunet architectures for multiple sclerosis lesion segmentation using eigengradcam. IET Conf. Proc.299–302, 2024. 10.1049/icp.2024.3318 (2024). [Google Scholar]
- 32.Selvaraju, R. R. et al. Grad-cam: Visual explanations from deep networks via gradient-based localization. In 2017 IEEE International Conference on Computer Vision (ICCV). 618–626. 10.1109/iccv.2017.74 (IEEE, 2017).
- 33.Jiang, P.-T., Zhang, C.-B., Hou, Q., Cheng, M.-M. & Wei, Y. Layercam: Exploring hierarchical class activation maps for localization. IEEE Trans. Image Process.30, 5875–5888. 10.1109/tip.2021.3089943 (2021). [DOI] [PubMed] [Google Scholar]
- 34.Jia, Z. et al. Adl-yolov8: A field crop weed detection model based on improved yolov8. Agronomy14, 2355. 10.3390/agronomy14102355 (2024). [Google Scholar]
- 35.Huang, Y. et al. Damage detection of unwashed eggs through video and deep learning. Foods12, 2179. 10.3390/foods12112179 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
Associated Data
This section collects any data citations, data availability statements, or supplementary materials included in this article.
Supplementary Materials
Data Availability Statement
The data presented in this study are available on request from the corresponding author.




















