Automated detection of defective coffee beans based on improved YOLOv10 framework Authors: Sunyan Hong, Dengji Zhang, Haiyang Chi, Jun He, Xiudong Guo, Hui Fu, Lu Wang Published: 2026 ABSTRACT AbstractCoffee quality assessment is critical to the global agricultural economy, yet traditional manual inspection remains labor-intensive, subjective, and prone to inconsistency. This study presents an improved YOLOv10-based framework specifically engineered for the automated detection of defective green coffee beans, achieving an optimal balance between high-precision localization and real-time edge deployment constraints. The proposed architecture integrates three targeted structural innovations: Depthwise Separable Convolution (DSConv) with distribution shift for lightweight, fine-grained feature extraction; a Spatial Pyramid Pooling Fast with Attention (SPPF_Attention) module for context-aware multi-scale feature refinement; and Partial Convolution (PConv) operators in the detection head to mitigate computational redundancy and enhance robustness against dense occlusions. Comprehensive evaluations utilized a rigorously curated dataset covering seven defect categories compliant with Specialty Coffee Association (SCA) standards. Evaluated under a 5-fold cross-validation protocol, the framework achieved state-of-the-art performance with 99.2% mAP@50, 98.5% precision, and 98.8% recall, alongside a rapid inference latency of merely 2.0 ms. These metrics denote substantial improvements over the advanced YOLOv11 baseline, simultaneously reducing model parameters by 21.6%, decreasing model size by 12.4%, and accelerating inference by 33.3%. Furthermore, systematic ablation studies validate the incremental contributions of each architectural component, while EigenCAM visualizations confirm that the integrated attention mechanisms successfully steer the network toward semantically meaningful defect regions and suppress background interference. Extensive cross-dataset analyses additionally demonstrate the model’s exceptional generalization capability across diverse processing states, establishing this framework as a highly viable, scalable solution for resource-constrained industrial sorting facilities.Keywords: Coffee bean defect detection, Image processing, Object recognition, YOLOv10 Introduction Coffee, as one of the world’s most consumed beverages and economically significant agricultural commodities, plays a vital role in the global economy, particularly for developing nations where it serves as a primary export product. The quality of coffee beans directly influences the flavor profile, market value, and consumer satisfaction of the final product, making accurate quality assessment essential throughout the coffee production chain Hassan (2024). According to the Specialty Coffee Association, even minor defects in green coffee beans can significantly compromise the final cup quality, potentially leading to substantial economic losses for producers and processors. Traditional quality control methods predominantly rely on manual visual inspection by trained experts, a process that is inherently labor-intensive, time-consuming, and subject to human variability due to fatigue, inconsistent lighting conditions, and subjective judgment (García et al., 2019). Moreover, manual handling during the sorting process can cause physical damage to beans, further compromising their appearance quality and commercial value. These limitations have created an urgent need for automated, objective, and reliable coffee bean quality assessment systems that can maintain consistent standards while improving operational efficiency and reducing production costs. Early attempts at automating coffee bean classification primarily employed traditional machine learning approaches combined with handcrafted feature extraction techniques. For example, Arboleda et al. (2018) developed a classification system using Artificial Neural Networks (ANN) and K-Nearest Neighbor (KNN) algorithms, extracting morphological features such as area, perimeter, shape descriptors, and color attributes from coffee bean images to achieve a classification accuracy of 96.66%. While demonstrating the feasibility of automated classification, these traditional methods remained heavily dependent on manually designed feature extractors, required extensive domain expertise for feature engineering, and exhibited limited robustness when confronted with varying imaging conditions or complex defect patterns (de Oliveira et al., 2016). The fundamental limitation of these early approaches lay in their inability to automatically learn hierarchical feature representations (Chi et al., 2020, Chi et al., 2025c), necessitating careful manual design of feature extraction pipelines that often failed to capture the subtle visual characteristics distinguishing different quality grades or defect types. The emergence of deep learning, particularly Convolutional Neural Networks (CNNs), has revolutionized computer vision applications in agriculture, offering the ability to automatically extract hierarchical features from raw image data without requiring manual feature engineering (Chen et al., 2025). In coffee bean quality assessment, several studies have demonstrated the superior performance of CNN-based approaches over traditional methods. For instance, Huang et al. (2020) proposed a real-time CNN-based classification method that expanded the dataset to 72,000 images through data augmentation techniques, ultimately attaining a classification accuracy of 93.34%. This approach not only enhanced classification precision but also reduced computational costs through model architecture optimization, enabling deployment in resource-constrained environments. Additionally, Gope and Fukai (2022) implemented CNNs on Raspberry Pi platforms to distinguish normal coffee beans from flat beans, achieving accuracy surpassing 98%. Furthermore, Korkmaz et al. (2025) conducted a comprehensive comparison of deep learning models for automatic classification of coffee bean species, employing five CNN-based architectures on a dataset comprising 1554 coffee bean images across three species, with InceptionV3 achieving the highest classification accuracy of 93% and precision of 95%. These studies collectively demonstrate the promising applications of deep learning techniques in coffee bean classification and detection. While CNN-based classification models have achieved remarkable success in coffee bean quality assessment, the industry increasingly demands real-time detection capabilities that can identify and localize defects within complex production environments. This requirement has driven attention toward object detection frameworks, with the You Only Look Once (YOLO) series emerging as the predominant paradigm due to its exceptional balance between detection accuracy and computational efficiency (Badgujar et al., 2024). The YOLO family has undergone continuous evolution, with each iteration introducing architectural innovations to improve both performance and efficiency. YOLOv7 (Wang et al., 2023) introduced trainable bag-of-freebies that set a new state-of-the-art for real-time object detectors, YOLOv8 (Sohan et al., 2024) enhanced the framework with improved C2f modules and anchor-free detection heads, while YOLOv9 (Chien-Yao Wang et al., 2024) introduced Programmable Gradient Information (PGI) to address information loss in deep networks and Generalized Efficient Layer Aggregation Network (GELAN) for improved feature aggregation. Most recently, YOLOv10 (Ao Wang et al., 2024) achieved state-of-the-art performance by introducing Non-Maximum Suppression (NMS)-free training through consistent dual assignments, eliminating the post-processing bottleneck that has long hampered real-time deployment, and implementing holistic efficiency-accuracy driven model design strategies, including lightweight classification heads, spatial-channel decoupled downsampling, and rank-guided block design. Ao Wang et al. (2024) demonstrated that YOLOv10-S is 1.8 times faster than RT-DETR-R18 under similar Average Precision (AP) on the COCO dataset, while having 2.8 times fewer parameters and floating-point operations (FLOPs). Several studies have successfully applied YOLO variants to coffee bean detection and classification tasks (Adiwijaya et al., 2024, Gope et al., 2025), demonstrating their practical applicability in agricultural settings. More recently, comprehensive comparative analyses of YOLO models have been conducted for coffee bean applications, highlighting the effectiveness of customized architectures for specific detection tasks. These applications demonstrate the growing maturity and practical viability of YOLO-based approaches for coffee bean quality control in industrial production environments (Ruangsang et al., 2026). Despite these advances, several challenges remain: (1) balancing detection accuracy with inference speed for real-time processing, (2) achieving sufficient model compactness for deployment on low-power embedded systems, (3) maintaining robust performance across varying lighting conditions and bean orientations, and (4) accurately detecting subtle defects that may have similar visual characteristics to normal bean features. In response to these challenges, this study proposes an improved YOLOv10 framework tailored specifically for defective coffee bean detection, with a strong emphasis on practical deployment. The proposed methodology pursues three core objectives: improving detection accuracy across diverse defect categories via targeted architectural refinements, sustaining real-time inference capabilities for industrial environments, and designing a lightweight architecture highly compatible with resource-constrained embedded systems. The primary contributions of this work are summarized as follows: •We address the stringent computational constraints of industrial edge deployment by incorporating Depthwise Separable Convolution (DSConv) (Howard et al., 2017, Nascimento et al., 2019) into the backbone network. Through the decomposition of standard convolutions into depthwise and pointwise operations, this architecture substantially reduces the parameter count and memory access overhead while preserving foundational feature representation capabilities. We address the stringent computational constraints of industrial edge deployment by incorporating Depthwise Separable Convolution (DSConv) (Howard et al., 2017, Nascimento et al., 2019) into the backbone network. Through the decomposition of standard convolutions into depthwise and pointwise operations, this architecture substantially reduces the parameter count and memory access overhead while preserving foundational feature representation capabilities. •We propose an enhanced module that integrates Spatial Pyramid Pooling Fast (SPPF) with context-aware attention mechanisms. By systematically extracting hierarchical features and adaptively reweighting spatial and channel dimensions, this module significantly improves the model’s discriminative capacity against complex backgrounds and visually similar defect patterns. We propose an enhanced module that integrates Spatial Pyramid Pooling Fast (SPPF) with context-aware attention mechanisms. By systematically extracting hierarchical features and adaptively reweighting spatial and channel dimensions, this module significantly improves the model’s discriminative capacity against complex backgrounds and visually similar defect patterns. •We introduce Partial Convolution (PConv) into the detection head to selectively process informative spatial channels while deliberately bypassing redundant ones. This strategic occlusion-aware design not only minimizes unnecessary computational burden but also greatly enhances the model’s sensitivity to irregular geometric boundaries and subtle localized defects. We introduce Partial Convolution (PConv) into the detection head to selectively process informative spatial channels while deliberately bypassing redundant ones. This strategic occlusion-aware design not only minimizes unnecessary computational burden but also greatly enhances the model’s sensitivity to irregular geometric boundaries and subtle localized defects. •We establish a robust evaluation protocol utilizing a strict 5-fold cross-validation scheme. On our self-built dataset, the proposed framework achieves state-of-the-art performance with a peak mAP@50 of 99.2% and an inference latency of only 2.0 ms, surpassing recent baselines including YOLOv11 in both accuracy and computational efficiency. Furthermore, extensive evaluations across three independent public datasets demonstrate the model’s exceptional generalization capability, confirming its viability as a highly accurate and deployable solution for real-time industrial coffee grading. We establish a robust evaluation protocol utilizing a strict 5-fold cross-validation scheme. On our self-built dataset, the proposed framework achieves state-of-the-art performance with a peak mAP@50 of 99.2% and an inference latency of only 2.0 ms, surpassing recent baselines including YOLOv11 in both accuracy and computational efficiency. Furthermore, extensive evaluations across three independent public datasets demonstrate the model’s exceptional generalization capability, confirming its viability as a highly accurate and deployable solution for real-time industrial coffee grading. Related work The automated detection of defective coffee beans remains a critical challenge in agricultural computer vision, where methodologies have transitioned from labor-intensive manual inspection to sophisticated deep learning paradigms. This section systematically reviews the progression of these techniques, categorized into four primary research domains: the transition from traditional machine learning to deep learning models, the evolution of YOLO-based object detection architectures, the integration of attention mechanisms and multi-scale feature fusion, and lightweight network design strategies tailored for edge deployment. From traditional methods to deep learning The automation of coffee bean quality assessment has evolved significantly over the past decade, transitioning from traditional image processing techniques to sophisticated deep learning architectures. Early research predominantly relied on handcrafted feature extraction combined with shallow machine learning algorithms. de Oliveira et al. (2016) developed a computer vision system for coffee bean classification based on computational intelligence techniques, extracting color, morphology, and texture features from bean images. Their system achieved classification accuracies exceeding 90% under controlled conditions, demonstrating the feasibility of automated quality assessment. García et al. (2019) proposed a quality and defect inspection system for green coffee beans using k-nearest neighbor algorithms, successfully identifying various defect types through morphological and color descriptors. However, these traditional approaches exhibited fundamental limitations: they required extensive domain expertise for feature engineering, remained sensitive to imaging condition variations, and struggled to capture subtle defect characteristics that distinguish quality grades (Santos et al., 2020). The dependence on manually designed features inherently constrained their generalization capability across diverse coffee varieties and defect manifestations. The advent of deep convolutional neural networks marked a transformative shift in coffee bean quality assessment methodologies. Chang and Huang (Chang and Huang, 2021) developed a deep learning model based on AlexNet for coffee bean defect inspection across eight defect categories, achieving 95.2% overall accuracy and 100% binary classification accuracy for defective versus non-defective beans. This work demonstrated that CNNs could automatically learn hierarchical feature representations superior to handcrafted features. Hsia et al. (2022) proposed an explainable lightweight deep CNN incorporating depthwise separable convolution and squeeze-and-excitation blocks for green coffee bean quality detection, achieving an F1-score of 97.21% while maintaining model interpretability. The integration of semi-supervised learning with attention mechanisms enabled their model to leverage both labeled and unlabeled data effectively, addressing the challenge of limited annotated datasets in specialized agricultural domains. More recently, Ke et al. (2023) introduced shift-invariant features combined with non-local blocks for green coffee bean defect detection, enhancing the model’s ability to capture long-range dependencies within bean surface patterns. Recent comprehensive reviews have systematically analyzed the landscape of machine learning applications in coffee classification. Motta et al. (2024) conducted an extensive review of machine learning techniques for coffee classification, analyzing studies spanning various aspects, including roast level classification, species identification, and quality grading. Their analysis revealed that pre-trained CNN architectures, particularly when fine-tuned with transfer learning strategies, consistently outperform models trained from scratch, especially when dealing with limited dataset sizes. Hassan (Hassan, 2024) performed a comparative analysis of ten pre-trained deep learning models, including AlexNet, LeNet, HRNet, GoogLeNet, MobileNetV2, ResNet-50, VGG, EfficientNet, DarkNet, and DenseNet for coffee bean classification, demonstrating that model selection significantly impacts classification performance, with certain architectures achieving substantially higher accuracy and better generalization capabilities (Chi et al., 2025b). These comparative studies collectively establish that deep learning approaches have fundamentally surpassed traditional methods, motivating the research community to focus on optimizing neural network architectures for specific deployment scenarios, including real-time processing, resource-constrained environments, and edge computing applications prevalent in industrial coffee processing facilities (Xie et al., 2024, Lu et al., 2023, Wu et al., 2025). The rise of YOLO architectures While classification models have achieved remarkable success in coffee bean quality assessment, industrial applications increasingly demand real-time object detection capabilities that can simultaneously identify, localize, and classify defects within complex production environments. The YOLO series has emerged as the predominant paradigm for agricultural object detection due to its exceptional balance between detection accuracy, inference speed, and computational efficiency (Badgujar et al., 2024). Unlike two-stage detectors such as Faster R-CNN (Ren et al., 2015) that separate region proposal and classification, YOLO performs detection in a single forward pass, making it particularly suitable for real-time applications. Badgujar et al. (2024) conducted a comprehensive bibliometric and systematic literature review analyzing 257 articles on YOLO algorithm applications in agriculture, identifying key advantages including real-time detection capabilities essential for automated harvesting and sorting systems, favorable accuracy-efficiency trade-offs suitable for resource-constrained embedded devices, and extensive community support providing pre-trained models and implementation frameworks. The YOLO architecture has undergone continuous evolution, with each iteration introducing significant innovations to address performance bottlenecks and expand applicability. Several studies have successfully adapted YOLO variants specifically for coffee bean detection and classification tasks. Luis et al. (2022) utilized YOLO for classifying defects in Robusta green coffee beans, successfully identifying multiple defect categories, including black beans, broken beans, and insect-damaged beans in real-time processing scenarios. Muchtar et al. (2025) developed an edge AI-based detection system for defective coffee beans using deep learning and the Streamlit framework, achieving high detection performance with a mean Average Precision (mAP) of 87.3% while maintaining compatibility with resource-constrained edge computing devices. Their deployment on Raspberry Pi 4B demonstrated the feasibility of implementing sophisticated deep learning models in industrial settings with limited computational resources. A recent study introduced an automated deep learning framework employing YOLOv8 architecture to identify and quantify defective beans across five key defect categories (Broken, Sour, Water-Faded, Immatured, and Black), achieving strong detection performance with high precision, recall, and mean average precision while providing interpretability through Gradient-weighted Class Activation Mapping (Grad-CAM) visualizations. These applications collectively demonstrate the maturity and practical viability of YOLO-based approaches for coffee bean quality control in industrial production environments. However, challenges remain in balancing detection accuracy with inference speed, achieving sufficient model compactness for deployment on low-power embedded systems, and maintaining robust performance across varying environmental conditions. These limitations motivate the development of improved architectures specifically optimized for coffee bean defect detection scenarios. Attention mechanisms and multi-scale feature fusion for enhanced detection performance Attention mechanisms have emerged as a critical component in modern deep learning architectures, enabling models to selectively focus on discriminative features while suppressing irrelevant information (Vaswani et al., 2017, Wang et al., 2025, Chi et al., 2025a). Woo et al. (2018) introduced the Convolutional Block Attention Module (CBAM), which sequentially applies channel and spatial attention mechanisms to refine feature maps along both dimensions. CBAM achieves this through a two-stage process: the channel attention module first adaptively recalibrates channel-wise feature responses by explicitly modeling interdependencies between channels using both global average pooling and global maximum pooling to capture richer statistical information, followed by the spatial attention module that emphasizes spatially informative regions by computing attention weights across spatial dimensions. Extensive experiments on ImageNet-1K, MS COCO detection, and VOC 2007 detection datasets demonstrated that CBAM consistently improves classification and detection performance across various base architectures with negligible computational overhead, validating its wide applicability as a plug-and-play module (Woo et al., 2018). Building upon foundational attention mechanisms, researchers have developed specialized variants optimized for specific detection scenarios. Hu et al. (2018) proposed Squeeze-and-Excitation Networks (SENet) that explicitly model channel-wise dependencies through a squeeze operation using global average pooling followed by an excitation operation using a small fully-connected network, enabling the network to adaptively recalibrate channel-wise feature responses. Wang et al. (2020) introduced Efficient Channel Attention (ECA-Net) that avoids dimensionality reduction in the channel attention mechanism by employing one-dimensional convolution for local cross-channel interaction, achieving comparable or superior performance to SENet with significantly lower computational complexity. Recent work by Ma et al. (2024) proposed an Adaptive Attention Module that dynamically adjusts the weights of features extracted from average pooling and max pooling operations across different network stages, addressing the limitation that these complementary features should not occupy equal weights throughout the network hierarchy. Their experiments on CIFAR-100 demonstrated that the adaptive mechanism achieves better performance with smaller parameters and computational overhead compared to CBAM and SENet. These attention mechanisms have been successfully integrated into agricultural detection tasks, with studies demonstrating significant improvements in plant disease identification (Duhan et al., 2024) and crop quality assessment, proving particularly effective for distinguishing subtle defect patterns from complex background textures inherent to natural agricultural products. Multi-scale feature fusion mechanisms play a crucial role in object detection by enabling models to capture contextual information across different resolutions, which is particularly important for detecting defects of varying sizes on coffee beans. He et al. (2015) introduced Spatial Pyramid Pooling (SPP) that aggregates features at multiple scales by applying pooling operations with different window sizes, generating fixed-length representations regardless of input size. The SPPF module, introduced in YOLOv5, simplifies the pooling process compared to the original SPP while significantly improving computational efficiency by replacing multiple parallel pooling operations with sequential pooling layers, maintaining the ability to fuse feature maps from different receptive fields (Xia et al., 2023). Xia et al. (2023) proposed mixed receptive fields augmented YOLO with multi-path spatial pyramid pooling for steel surface defect detection, demonstrating that strategic placement of enhanced SPPF modules significantly improves detection accuracy for objects with varying scales. They introduced a re-parameterized large kernel C3 module combined with a multi-path spatial pyramid pooling feature fusion structure in the neck network, enabling the model to obtain larger effective receptive fields while adapting to scale variations of surface defects. Dong et al. (2024) developed a simplified SPPF with hybrid pooling and channel attention mechanisms for industrial product defect detection, integrating both average pooling and max pooling within the SPPF structure and adding channel attention to emphasize important feature channels, achieving 17.4% improvement in mAP while maintaining real-time processing speeds. Zhao (2025) proposed an enhanced SE-SPPF module that combines squeeze-and-excitation mechanisms with spatial pyramid pooling for fabric defect detection, fully integrating important defect information from both spatial and channel perspectives. These architectural innovations demonstrate that the synergistic combination of attention mechanisms with multi-scale feature fusion significantly enhances detection performance for small and irregularly shaped defects, providing a strong foundation for developing specialized architectures for coffee bean defect detection where defects exhibit substantial scale variation and often appear against complex surface textures. Lightweight network design strategies for edge deployment The deployment of deep learning models on resource-constrained embedded devices commonly used in agricultural settings necessitates lightweight network designs that maintain high accuracy while minimizing computational complexity, memory footprint, and power consumption. Depthwise separable convolution has emerged as a fundamental technique for building efficient neural networks. Howard et al. (2017) introduced MobileNets that pioneered the use of depthwise separable convolutions, factorizing standard convolutions into depthwise convolutions (applying a single filter per input channel) and pointwise convolutions (1 × 1 convolutions for channel mixing). This factorization achieves approximately 8–9 times reduction in computational cost compared to standard convolutions while maintaining comparable representational capacity. Sandler et al. (2018) proposed MobileNetV2, introducing inverted residual structures and linear bottlenecks that further improve efficiency by expanding low-dimensional compressed representations to high-dimensional space for feature transformation, then projecting back to low-dimensional space, preventing ReLU activations from destroying information in low-dimensional manifolds. Chollet (Chollet, 2017) introduced Xception that replaces Inception modules with depthwise separable convolutions, demonstrating that this modification achieves better performance than Inception V3 with comparable parameter count. These foundational works established depthwise separable convolutions as a cornerstone technique for efficient network design, enabling deployment on mobile and embedded devices while maintaining competitive accuracy on challenging computer vision tasks (Xie et al., 2024). Recent research has explored novel convolution operations that further push the efficiency frontier. Chen et al. (2023) proposed PConv in FasterNet, a simple yet fast and effective convolution operation that addresses the low computational speed issues prevalent in existing efficient networks. PConv leverages redundancy within feature maps by systematically applying regular convolution to only a portion of input channels while leaving remaining channels untouched, reducing both computational complexity and memory access frequency. Unlike depthwise convolution, which suffers from frequent memory access and thus low computational efficiency, PConv reduces memory access and achieves higher hardware utilization while maintaining lower computational cost than standard convolution. For contiguous memory access, PConv processes the first or last consecutive channels as representatives of the entire feature map. Extensive experiments demonstrated that FasterNet built with PConv achieves superior speed-accuracy trade-offs compared to existing efficient networks across various hardware platforms, including CPU, GPU, and ARM processors. Pan et al. (2024) applied PConv in a lightweight network for wheat variety classification in field environments, demonstrating its effectiveness for agricultural applications. Peng et al. (2024) integrated PConv with residual connections in an improved YOLOv7 model for real-time meter reading, achieving reduced parameters and FLOPs while maintaining high detection accuracy. Recently, Huang et al. (2025) proposed Partial Attention Convolution (PAT) that integrates visual attention mechanisms into PConv, introducing Gaussian channel attention to infuse global distribution information into untouched channels and spatial-wise attention to improve model accuracy, achieving 1.3% higher accuracy than FasterNet-T2 while exhibiting 25% higher GPU throughput and 24% lower CPU latency. These innovations demonstrate that carefully designed lightweight convolution operations can significantly reduce computational requirements while maintaining or even improving detection performance. The integration of lightweight architectural components with attention mechanisms has shown particular promise for resource-constrained deployment scenarios. Hu et al. (2023) developed a hybrid convolutional network combining multiscale 3D depthwise separable convolution with CBAM residual dilated convolution for hyperspectral image classification, demonstrating that careful integration of efficient convolutions with attention mechanisms achieves high accuracy with minimal computational overhead. Pan et al. (2024) proposed G-PPW-VGG11 that combines partial convolution with partially mixed depthwise separable convolution for field wheat variety classification, reducing computational complexity and feature redundancy while improving classification accuracy. Qiu et al. (2022) developed ASFF-YOLOv5 that incorporates SPPF structure with adaptive spatial feature fusion for multielement detection in UAV images, achieving 93.1% mAP, which is 19.2% higher than original YOLOv5 while maintaining real-time processing capabilities. Peng et al. (2024) proposed PDSI-RTDETR that merges PConv with residual blocks for lightweight tomato ripeness detection, optimizing the backbone network for efficient feature extraction with reduced computational burden while achieving 1.3 percentage point improvement in mAP50. These studies collectively demonstrate that the synergistic combination of lightweight convolution operations, multi-scale feature fusion mechanisms, and attention modules enables the development of efficient detection models suitable for deployment on resource-constrained embedded devices in agricultural settings. The strategic integration of these components addresses the competing demands of detection accuracy, inference speed, and model compactness that are critical for practical industrial deployment of automated coffee bean quality assessment systems. Building upon these foundational techniques, our work introduces targeted architectural improvements to YOLOv10, specifically optimized for defective coffee bean detection, achieving superior performance while maintaining compatibility with low-power embedded systems commonly employed in coffee processing facilities. Preliminaries This section establishes the theoretical foundation for the proposed defective coffee bean detection framework. A comprehensive overview of the fundamental mechanisms driving the baseline YOLOv10 architecture is presented, focusing specifically on its end-to-end dual assignment strategy and efficiency-driven design principles. YOLOv10 architecture The YOLOv10 framework fundamentally resolves the latency bottleneck inherent in real-time object detectors by completely eliminating the reliance on Non-Maximum Suppression (NMS) during inference. Traditional YOLO architectures depend heavily on one-to-many (o2m) label assignments during training. While this approach generates abundant supervisory signals, it necessitates NMS to filter redundant bounding boxes during deployment, thereby increasing inference latency. YOLOv10 circumvents this limitation by introducing a consistent dual assignment strategy coupled with a holistic structural design. The dual assignment mechanism dynamically balances the richness of training supervision with the efficiency of end-to-end inference. During the training phase, the network simultaneously optimizes a one-to-many branch and a one-to-one (o2o) branch. The matching metric regulating the assignment quality for both branches is mathematically defined as: where p represents the predicted classification confidence score; IoU(bˆ,b) denotes the Intersection over Union between the predicted bounding box bˆ and the corresponding ground truth box b. The variable s functions as a spatial prior indicator that equals 1 when the anchor point of the prediction resides strictly within the ground truth instance, and 0 otherwise. The hyperparameters α and β dynamically modulate the relative influence of classification accuracy and spatial localization alignment in the final matching score. A critical challenge arises when the o2m and o2o branches utilize inconsistent (α,β) configurations, causing their respective rankings of optimal predictions to diverge. This divergence creates a supervision gap, preventing the o2o branch from effectively inheriting the rich gradient representations learned by the o2m branch. Letting Ω denote the positive sample set selected by the one-to-many assignment, the supervision gap Ai for a given prediction i can be formalized as: where tio2o and tio2m represent the target scalars generated under the respective assignment strategies, and II(⋅) serves as an indicator function equaling 1 if the condition is met and 0 otherwise. Minimizing this supervision gap Ai requires enforcing strict mathematical consistency between the matching metrics of both branches through proportional scaling: where r is an empirically derived scaling factor. This architectural alignment guarantees that the o2o branch preferentially selects predictions that are simultaneously highly ranked by the o2m branch. Consequently, the network generates high-quality, unique bounding boxes during inference without requiring any NMS post-processing. Efficiency-accuracy driven baseline design Beyond the label assignment strategy, YOLOv10 incorporates a holistic structural optimization paradigm. The backbone utilizes spatial-channel decoupled downsampling to prevent information loss during dimensionality reduction, while the macroscopic architecture employs rank-guided block configurations to eliminate redundant computational stages. Furthermore, the integration of Partial Self-Attention (PSA) and large-kernel depthwise convolutions enhances the global receptive field. These baseline features provide a robust starting point, yet detecting fine-grained agricultural defects on edge devices necessitates further targeted architectural modifications. Methodology Standard object detection models frequently struggle in industrial coffee sorting environments due to the extreme scale variations of defects and the severe computational limitations of edge deployment hardware. Optimizing the YOLOv10 framework for this specific application demands targeted structural modifications that enhance feature extraction while strictly controlling computational complexity. Overall network architecture The proposed detection network builds upon the YOLOv10 baseline through a tri-fold architectural enhancement strategy. Fig. 1 illustrates the complete topology of our improved framework, which consists of three principal macroscopic components: an enhanced lightweight backbone, a context-aware bottleneck and neck, and an occlusion-robust detection head. Improved YOLOv10 Model Framework. Processing begins as the backbone ingests raw 640 × 640 RGB images. Depthwise Separable Convolution with Distribution Shift (DSConv) operators are integrated into the early and middle stages of this backbone network. This strategic placement drastically reduces the memory access burden while reliably extracting foundational geometric and textural features from the coffee beans. High-level feature maps subsequently pass into the proposed Spatial Pyramid Pooling Fast with Attention (SPPF_Attention) bottleneck. This specialized module aggregates multi-scale receptive fields and adaptively recalibrates spatial and channel weights before feeding the refined data into the neck network. Finally, the detection head utilizes Partial Convolution (PConv) operators to execute efficient bounding box regression and defect classification, maintaining high sensitivity to local features while effectively suppressing irrelevant background noise. Lightweight feature extraction via DSConv Extracting fine-grained textural anomalies from coffee bean surfaces typically requires deep convolutional stacks, which inevitably inflate the parameter count and processing latency. Replacing standard spatial convolutions with DSConv operators in the backbone effectively resolves this efficiency bottleneck. Standard floating-point convolutions impose substantial memory bandwidth requirements. DSConv addresses this by decomposing convolutions into a low-bit Variable Quantized Kernel (VQK) and dynamic distribution shift mechanisms. Letting the original standard floating-point convolution kernel be defined as a tensor W∈RCout×Cin×k×k, DSConv factorizes W into an integer-valued tensor Wq∈ZCout×Cin×k×k, a Kernel Distribution Shifter (KDS), and a Channel Distribution Shifter (CDS). The core quantization rule relies on a block-level scaling factor s: The distribution shift operators are subsequently applied to guarantee that the quantized convolution maintains an output distribution mathematically equivalent to the original floating-point operation. Defining ξR and ξs,R as the KDS parameters expanded to match the shape of Wq, and letting ϕ and ϕs denote the channel-wise scale and bias parameters from the CDS, the reconstructed floating-point weight Wr is formulated as: where ⊙ denotes element-wise multiplication with broadcasting. Exploiting the associative property of the convolution operator allows the network to prioritize integer-domain matrix multiplication during inference. Given an input feature map X, the equivalent high-speed computation flow executes as follows: where ∗ denotes the standard convolution operator, A represents the intermediate integer-domain output, and ξR′ and b are the aggregated spatial transformations of the original shift parameters. Deploying this module after the initial C2f blocks allows the backbone to capture critical low-level visual cues, such as subtle fungal growths or color gradients on immature beans, while maintaining an exceptionally low latency profile. Context-aware SPPF_Attention module Aggregating contextual information across varying scales is essential for detecting defects that range vastly in physical size. The standard concatenation of multi-scale features, however, inherently requires identical spatial resolutions across all concatenated layers. Designing the SPPF_Attention module guarantees strict spatial alignment while dramatically expanding the effective receptive field, fully validating the integrity of the subsequent fusion operations. Given a high-level input feature map X∈RC×H×W extracted from the final stage of the backbone, a 1 × 1 convolution first halves the channel dimension to generate a base feature representation F0. The network then applies three successive Max Pooling operations. Crucially, every pooling layer employs a fixed kernel size of k=5, an enforced stride of s=1, and dynamic zero-padding of p=⌊k/2⌋=2. This specific mathematical configuration guarantees that the output spatial dimensions exactly match the input dimensions at every pooling stage: The sequential pooling results, denoted as F1,F2, and F3, all perfectly maintain the H×W spatial resolution. These aligned features are concatenated along the channel dimension, followed by a 1 × 1 projection layer ϕ designed to restore the original channel count: Adaptive filtering mechanisms subsequently refine this multi-scale representation. A channel attention vector sc∈RC×1×1 is generated by compressing spatial information via Global Average Pooling (GAP) and processing it through a Multi-Layer Perceptron (MLP) activated by a Sigmoid function σ: Spatial attention ss∈R1×H×W is computed by applying channel-wise Average and Max Pooling, concatenating the intermediate results, and passing them through a 7 × 7 spatial convolution: The final enhanced feature output Fout is formed by sequentially scaling the base features with these attention maps, concluding with a residual connection to stabilize gradient flow: This structured module forces the network to concentrate on irregular defect contours while suppressing the repetitive background textures of the conveyor belt. Table 1Definitions and characteristics of defective coffee bean categories.Table 1Defect typeDefinition and characteristicsBlack BeanCoffee beans exhibiting black spots or discoloration on the surface due to over-ripening or improper storage conditions.Float BeanLightweight beans with reduced moisture content that typically float on water surfaces during processing.Immature BeanIncompletely matured beans characterized by uneven surface coloration, typically greenish or pale yellow in appearance.Moldy BeanBeans infested by fungi, displaying mold spots or white fungal growth on the surface.Shell BeanBeans that failed to fully develop during growth due to various factors such as pest infestation or water deficiency, resulting in hollow or incomplete kernels.Shrink BeanBeans that have shrunk and deformed due to improper drying or poor storage conditions, exhibiting a shriveled or flattened appearance.Sour BeanBeans exhibiting sour taste characteristics due to insufficient roasting or improper processing methods. Definitions and characteristics of defective coffee bean categories. Occlusion-robust detection head via PConv Industrial coffee bean sorting frequently results in dense physical clusters where beans partially occlude one another. Standard convolutions in the detection head apply uniform computational filters across the entire spatial grid, wasting massive FLOPs on redundant channel data and diminishing performance under severe occlusion. Replacing the standard 3 × 3 convolutions within the YOLOv10 detection heads (across the P3, P4, and P5 downsampling scales) with PConv modules directly mitigates this inefficiency. The fundamental principle of PConv exploits channel redundancy by performing spatial convolution exclusively on a subset of the input channels. Given an input feature map X∈Rc×h×w, PConv splits the channel dimension c into two distinct subsets based on a predefined partial ratio r=cp/c. Defining Πp(⋅) as the selection operator extracting the first cp participating channels, and Πu(⋅) as the operator isolating the remaining c−cp untouched channels yields: A standard k×k spatial convolution operator Ck is exclusively applied to the participating subset Xp: The intermediate representation is constructed by concatenating the convolved channels directly with the untouched channels: Enabling cross-channel information exchange for the bypassed channels requires a subsequent Pointwise Convolution (PWConv) layer. A 1 × 1 convolutional kernel processes Y~ to generate the final fused output. By forcing the spatial filters to operate strictly on one-quarter of the channel dimension (r=1/4), the PConv head isolates defect-specific structural patterns within the active channels. Simultaneously, the untouched channels act as an identity mapping, preserving low-frequency contextual information that standard convolutions might otherwise distort. This modification drastically cuts the computational memory access cost while demonstrating marked robustness against partial occlusion. Optimization objective Training the proposed end-to-end framework relies on a composite objective function specifically tailored for the NMS-free dual assignment mechanism. Both the one-to-one and one-to-many branches utilize identical loss formulations during the training phase, comprising Classification Loss (Lcls), Bounding Box Regression Loss (Lbox), and Distribution Focal Loss (Ldfl). The classification loss employs Binary Cross-Entropy (BCE) to strictly penalize incorrect defect categorization. The bounding box loss utilizes Complete Intersection over Union (CIoU) to measure the overlap area, aspect ratio, and central distance alignment between the predicted bounding boxes and the ground truth annotations. DFL optimizes the continuous distribution of box boundaries, vastly enhancing localization precision for extremely small or irregularly shaped anomalies (e.g., shell beans). The total loss Ltotal is formally defined as: where λcls, λbox, and λdfl serve as dynamic weighting coefficients that balance the three optimization objectives. Discarding the one-to-many branch entirely during inference allows the network to generate definitive object predictions directly from the one-to-one branch, thereby achieving zero post-processing latency. Experiments and analysis Dataset Dataset construction. Yunnan small-grain coffee is renowned for its superior quality and distinctive flavor profile. This study focuses on small-grain coffee beans produced in Baoshan and Pu’er cities, Yunnan Province, China, with particular emphasis on detecting defective beans that compromise coffee quality. Following local standards and industry specifications, we systematically categorized defective coffee beans into seven types based on their visual characteristics and formation mechanisms. Table 1 provides detailed definitions of each defect category, which forms the basis for our quality control framework. To ensure the scientific validity and industrial applicability of our detection framework, the categorization of these seven defective types strictly adheres to the defect grading specifications outlined in the Arabica Green Coffee Defect Handbook by the Specialty Coffee Association (SCA, formerly SCAA) (Kosalos et al., 2013). The mapping relationship between our dataset categories, the SCA primary/secondary defect classifications, and the equivalent full defect counts is detailed in Table 2. Table 2Mapping relationship between the defective bean categories in this study and the SCA defect standards.Table 2Dataset categoryEquivalent SCA defectDefect levelCount for 1 full defectRemarksBlack BeanFull/Partial BlackPrimary/Secondary1 bean (Full)/3 beans (Partial)Both full and partial black beans correspond to different defect levels; unified into ’Black Bean’ in this study.Float BeanFloaterSecondary5 beansLightweight, floats on water; 5 beans equal 1 full defect.Immature BeanImmature BeanSecondary5 beansShriveled surface, silverskin attached; 5 beans equal 1 full defect.Moldy BeanFungus DamagePrimary1 beanBeans with visible mold spots; belongs to primary defects.Shell BeanShellSecondary5 beansHollow or severely deformed; 5 beans equal 1 full defect.Shrink BeanWithered BeanSecondary5 beansSignificantly smaller than normal beans, shriveled surface; 5 beans equal 1 full defect.Sour BeanFull/Partial SourPrimary/Secondary1 bean (Full)/3 beans (Partial)Differentiated by sourness degree; full sour is a primary defect, partial is secondary. Mapping relationship between the defective bean categories in this study and the SCA defect standards. Image acquisition. Image acquisition was performed using a KS2A543-3.0 camera in a controlled laboratory environment, capturing 1344 raw images. The imaging setup simulated realistic sorting scenarios: coffee beans were positioned on a conveyor belt serving as the background, with a fixed rectangular frame maintaining a consistent spatial arrangement. Two strip LED lights were mounted on a steel frame, with the camera centrally positioned and the lens aligned perpendicular to the conveyor centerline. This configuration ensures image data integrity and uniform illumination distribution, meeting practical quality inspection requirements. During sampling, we rigorously controlled the quantity and balance of each defect category to ensure dataset comprehensiveness and representativeness. Fig. 2 illustrates representative images of partial defect categories for visual reference. It is worth noting that hulled green coffee beans possess an asymmetrical morphology, featuring a flat inner ventral groove and a rounded outer dorsal surface. To simulate realistic industrial sorting, beans were imaged in random orientations to comprehensively capture both surfaces. This ensures the network learns to robustly detect defects located on either side, irrespective of the bean’s physical posture. Representative images of partial defective coffee bean categories in the dataset. Data augmentation. Data augmentation serves dual purposes: enhancing dataset diversity and significantly improving model generalization and robustness. We applied four augmentation techniques to expand the raw coffee bean image dataset: horizontal flipping, vertical flipping, blur processing, and Gaussian noise injection. As illustrated in Fig. 3, horizontal and vertical flipping simulate viewing angle variations, enhancing directional invariance. Blur processing emulates focus variations and motion artifacts common in industrial conveyor systems, while Gaussian noise injection simulates sensor noise and ambient lighting fluctuations. These transformations simulate real-world variations in imaging conditions, enabling the model to develop invariant feature representations that generalize effectively to practical deployment scenarios with varying lighting, orientations, and image quality degradation. Through these strategies, the original 1344 images were expanded to 6695 images. Data augmentation techniques applied to the defective coffee bean dataset. Experimental setup and hyperparameter configuration Implementation environment All experiments were implemented in the PyTorch framework using YOLOv10 with our proposed modifications. The model was trained on a server equipped with an Intel Xeon 6226R CPU and six Tesla V100 GPUs. For the embedded experiments, the system utilized an NVIDIA Volta GPU with a computational performance of 21 TOPS. Furthermore, we conducted practical testing and deployment in real-world scenarios, and Fig. 4 illustrates our actual experimental environment and testing apparatus in our laboratory. Laboratory environment for detection of defective coffee beans. Training protocol and five-fold cross-validation We implemented a 5-fold cross-validation scheme with an internal validation set to rigorously evaluate the model’s performance and mitigate the randomness inherent in a single data split. The complete dataset of 6695 images was first randomly divided into five mutually exclusive subsets of approximately 1339 images each. Over five experimental rounds, each subset served once as the isolated test set, while the remaining four subsets were aggregated into a comprehensive training pool. Because the early stopping strategy necessitates an independent validation set, we randomly extracted approximately 12.5% (around 670 images) of the training pool (5356 images) for validation purposes, leaving 4686 images as the final training set. This approach strictly maintained a consistent data distribution ratio of 70% (training), 10% (validation), and 20% (testing) throughout every round. Upon completing all five iterations, the final performance metrics were computed as the Mean ± Standard Deviation (SD) for precision, recall, F1-score, and mAP@50. This identical data flow and early stopping criterion, terminating training after 30 consecutive epochs without validation improvement, were applied uniformly across all evaluated models. Table 3Structural parameters of the improved YOLOv10 network.Table 3StageModule nameOutputOutputNumber ofParametersDescriptionsizechannelsmodules(M)Input LayerInput640 × 64031–RGB 3-channel coffee bean imageBackboneCBS320 × 3201610.0004Initial Conv + BatchNorm + SiLUC2f320 × 3203210.021Cross-stage partial connection feature fusionDSConv160 × 1606410.037Lightweight extraction via dist-shift convC2f160 × 1606420.142Deep feature enhancementDSConv80 × 8012810.147Spatial and channel downsamplingC2f80 × 8012820.815Medium-scale feature extractionDSConv40 × 4025610.590Deep lightweight convolutionC2f40 × 4025611.183High-level semantic feature extractionSPPF_attention40 × 4025610.372Multi-scale pooling + Context aggregation attentionPSA40 × 4025610.411Partial self-attention global modelingNeckUpsample80 × 801281–Upsample to medium scaleConcat + C2f80 × 8012810.348Cross-layer feature concatenation and fusionUpsample160 × 160641–Upsample to shallow scaleConcat + C2f160 × 1606410.092Shallow feature enhancementDSConv80 × 8012810.147Downsampling recoveryConcat + C2f80 × 8012810.348Multi-scale fusionDSConv40 × 4025610.590Downsample to deep layerConcat + C2f40 × 4025611.183Deep feature fusionDetection HeadPConv_Detect(P3)80 × 806410.042Small object detection branch (8×downsampled)PConv_Detect(P4)40 × 4012810.089Medium object detection branch (16×downsampled)PConv_Detect(P5)20 × 2025610.284Large object detection branch (32×downsampled) Structural parameters of the improved YOLOv10 network. Network configuration and hyperparameter optimization The hyperparameter configuration was meticulously optimized to address the specific challenges inherent in defective coffee bean detection. The improved YOLOv10 network adopts a scaling configuration with a depth multiple of 0.4 and a width multiple of 0.3, ensuring robust feature extraction while effectively controlling the model scale. The specific structural parameters for each stage of the network are detailed in Table 3. To establish a robust baseline training environment, we adopted an input resolution of 640 × 640 and employed Stochastic Gradient Descent (SGD) with a momentum of 0.937 as the optimizer. The 640 × 640 resolution aligns seamlessly with official pre-trained weights while providing sufficient multi-scale adaptation for defective beans, achieving a 4.2% mAP@50 improvement over 320 × 320 with optimal inference speed. For the optimizer, official YOLO implementations inherently default to SGD, as its convergence stability and final accuracy on object detection tasks often surpass adaptive optimizers like AdamW. Moreover, the implicit regularization effect of SGD effectively mitigates data imbalance issues, which is critical for facilitating better feature learning of tail categories (e.g., immature and shrink beans) in our dataset. Building upon this foundation, we conducted systematic hyperparameter sensitivity analysis on the initial learning rate and weight decay under a 5-fold cross-validation framework to determine the optimal training dynamics for our specific architecture. As shown in Table 4, an initial LR of 0.008 provided the best convergence stability, yielding a peak mAP@50 of 98.8%. Similarly, Table 5 reveals that a weight decay of 0.0006 effectively minimizes the generalization gap to 0.002, achieving the highest mAP@50 of 99.2%. This marginally stronger regularization compared to the YOLOv10 default (0.0005) is explicitly tailored to our improved architecture: it prevents overfitting on a relatively smaller dataset while providing necessary optimization constraints for the newly introduced learnable shift parameters in the DSConv modules and the attention weights within the SPPF_Attention block. Table 4Hyperparameter Sensitivity Analysis on Initial Learning Rate (5-fold cross-validation, Mean ± SD).Table 4Learning ratePrecision (%)Recall (%)F1 (%)mAP@50 (%)EpochsFinal loss0.00195.2±0.594.8±0.695.0±0.596.3±0.4850.0420.00396.8±0.496.5±0.496.6±0.497.8±0.3720.0280.00597.6±0.397.3±0.397.4±0.398.4±0.2580.0190.00898.2 ± 0.398.0 ± 0.398.1 ± 0.398.8 ± 0.2450.0150.01097.9±0.397.6±0.397.7±0.398.5±0.2410.0180.02095.4±0.694.1±0.794.7±0.696.0±0.5380.035 Hyperparameter Sensitivity Analysis on Initial Learning Rate (5-fold cross-validation, Mean ± SD). Table 5Hyperparameter Sensitivity Analysis on Weight Decay (5-fold cross-validation, Mean ± SD).Table 5Weight decayPrecision (%)Recall (%)F1 (%)mAP@50 (%)Train lossVal loss0.000197.1±0.496.8±0.496.9±0.498.0±0.30.0060.0220.000598.2±0.398.0±0.398.1±0.398.8±0.20.0080.0150.000698.5 ± 0.298.8 ± 0.298.6 ± 0.299.2 ± 0.10.0090.0110.001098.1±0.397.8±0.397.9±0.398.5±0.20.0120.0140.005096.3±0.595.9±0.596.1±0.597.2±0.40.0250.026 Hyperparameter Sensitivity Analysis on Weight Decay (5-fold cross-validation, Mean ± SD). Evaluation metrics To comprehensively evaluate detection model performance, we employ the following standard metrics with precise mathematical definitions: Precision: quantifies the proportion of true positives among all positive predictions: where TP (True Positives) denotes correctly identified defective beans and FP (False Positives) represents non-defective beans incorrectly classified as defective. Recall: measures the proportion of actual positives that are correctly detected: where FN (False Negatives) denotes defective beans that were missed by the detector. F1-Score: provides the harmonic mean of Precision and Recall, balancing both metrics: Mean Average Precision: mAP@50 and mAP@50-95: These metrics compute average precision at IoU (Intersection over Union) thresholds of 0.5 and across the range [0.5, 0.95] with 0.05 increments, respectively. These metrics reflect model detection accuracy under varying localization precision requirements, providing a comprehensive assessment of detection performance across different overlap criteria. Under the 5-fold cross-validation protocol, all metrics are rigorously reported as Mean ± Standard Deviation to reflect statistical stability. Results and discussion In agricultural object detection, generic deep learning frameworks have become the mainstream paradigm. While some prior studies have utilized classification networks (e.g., ResNet, EfficientNet) for coffee bean grading, they fundamentally lack the capability for fine-grained, instance-level localization of individual defective beans. Regarding detection tasks, existing literature predominantly relies on transfer learning using generic architectures like YOLOv5 or Faster R-CNN. However, these methods lack specialized structural designs tailored to the unique morphological characteristics of coffee beans. Although hybrid approaches combining hyperspectral imaging with Support Vector Machines (SVMs) exist, they depend on expensive optical equipment, significantly hindering large-scale industrial deployment. Therefore, comparing our method against dominant generic detection models serves as a rigorous and objective benchmark, highlighting the necessity and superiority of exploring dedicated network optimizations. Overall performance Table 6 presents a comprehensive performance comparison of our improved YOLOv10-based framework against representative state-of-the-art object detectors under the strict 5-fold cross-validation protocol. Traditional single-stage and two-stage models, represented by SSD and Faster R-CNN, respectively, exhibit mAP@50 scores below 90% (85.7% and 88.9%) with relatively large standard deviations (±0.8% to ±1.2%), indicating limited generalization capabilities in complex coffee bean scenarios. The YOLO series demonstrates progressive enhancements, with YOLOv11 achieving a high mAP@50 of 98.0%±0.3%. However, our improved model surpasses all baselines, elevating the mAP@50 to 99.2%±0.1%, Precision to 98.5%±0.2%, and Recall to 98.8%±0.2%. Crucially, the exceptionally small standard deviations (≤0.2%) obtained across the 5 folds provide strong statistical evidence that our model maintains highly consistent detection capabilities regardless of data partitioning. Simultaneously, our model achieves the highest computational efficiency, requiring only 6.99M parameters, 15.6MB model size, and a mere 2.0 ms inference time per image. Table 6Performance comparison of different object detection models under 5-fold cross-validation.Table 6ModelPrecision (%)Recall (%)F1 (%)mAP@50 (%)Params (M)Model size (MB)Time (ms)SSD79.3±1.281.2±1.180.2±1.285.7±1.028.4112.625.0Faster R-CNN82.1±1.083.5±0.982.8±0.988.9±0.842.6170.420.0YOLOv886.5±0.887.8±0.787.1±0.793.2±0.611.222.45.0YOLOv987.3±0.789.1±0.788.2±0.794.5±0.59.8519.74.5YOLOv1194.0±0.495.3±0.494.6±0.498.0±0.38.9217.83.0YOLOv10 (Baseline)89.6±0.691.7±0.590.6±0.696.6±0.48.0418.04.0Ours98.5 ± 0.298.8 ± 0.298.6 ± 0.299.2 ± 0.16.9915.62.0 Performance comparison of different object detection models under 5-fold cross-validation. Comparative analysis Comparison with SSD and faster R-CNN. Our method demonstrates overwhelming superiority over traditional architectures. Compared to SSD and Faster R-CNN, our model achieves an improvement of 11.6% to 15.8% in mAP@50, alongside a precision increase of 20.0% to 24.2%. Furthermore, Faster R-CNN’s Region of Interest mechanism and SSD’s dense anchor generation cause severe computational redundancy, requiring 20.0 ms and 25.0 ms per image, respectively. By contrast, our streamlined architecture achieves 2.0 ms inference latency using less than a quarter of their parameters, successfully overcoming the limitations of earlier frameworks for dense object detection. Comparison with earlier YOLO baselines. When evaluated against YOLOv8 and YOLOv9, our framework improves mAP@50 by 5.0% to 6.4% while reducing model parameters by 29.0% to 37.6%. Against our direct baseline, YOLOv10, the proposed modifications yield a 9.9% boost in precision and a 2.7% increase in mAP@50. Additionally, the inference latency is successfully halved from 4.0 ms to 2.0 ms. This proves that our integrated enhancements provide substantial structural benefits beyond the inherent advantages of a standard non-maximum suppression-free architecture. Comparison with state-of-the-art YOLOv11. Despite YOLOv11’s advanced feature pyramids and refined blocks, our customized framework maintains a distinct edge in both accuracy and deployment efficiency. We achieve an increase of 4.8% in precision, 3.7% in recall, and 1.2% in mAP@50. Moreover, our model utilizes 21.6% fewer parameters, features a 12.4% smaller model size, and executes 33.3% faster. This comprehensive superiority is driven by our domain-specific innovations: (1) DSConv preserves fine-grained discriminative features to distinguish visually similar defects (e.g., moldy vs. immature beans); (2) PConv strategically exploits spatial redundancy to drastically cut computational overhead; and (3) SPPF-Attention provides context-aware multi-scale aggregation for robust detection across various defect sizes without heavy parameter burdens. Cross-dataset generalization analysis We further verified the generalization capability of the proposed model by expanding our evaluation to include three publicly available datasets: RoastedCoffeeDefectDataset,1 Coffee Bean Classification Dataset,2 and Green Coffee Beans Dataset.3 Specifically, the RoastedCoffeeDefectDataset contains images of roasted beans categorized into 6 defect classes; the Coffee Bean Classification Dataset focuses on generic defect categories for green beans; and the Green Coffee Beans Dataset provides a detailed classification of green beans across 7 distinct defect types. All images were uniformly resized to 640 × 640 resolution to guarantee input compatibility with our framework. For images featuring sparsely distributed or exceedingly small beans, random cropping and rotation augmentations were applied, and samples with a bean area ratio below 5% were discarded. Additionally, YOLO-format bounding boxes were generated for the classification-only datasets (Coffee Bean Classification Dataset and Green Coffee Beans Dataset) based on their category labels. Following these augmentations, the effective training sets for the three public datasets comprised 5786, 6411, and 6050 images, respectively. The strict 5-fold cross-validation protocol (7:1:2 split) was maintained to align with our primary evaluation framework. Table 7 demonstrates that our improved model consistently outperforms the original YOLOv10 across all external datasets. On our self-built dataset, the improved model achieves a peak mAP@50 of 99.2%, alongside 98.5% precision and 98.8% recall. Notably, when migrated to the RoastedCoffeeDefectDataset, which involves roasted beans with fundamentally different color profiles, our model retains an impressive mAP@50 of 93.5%. This represents a 10.9% relative increase over the baseline, demonstrating excellent cross-processing-stage adaptability. On the two generic green bean datasets, our model achieves mAP@50 scores of 97.2% and 96.1%, reflecting relative improvements of 5.9% and 6.5%, respectively. Furthermore, inference speeds remain highly stable across all datasets at approximately 2.0 to 2.1 ms. These results confirm that our triple architectural enhancement strategy not only maximizes detection accuracy on the primary dataset but also significantly bolsters generalization robustness across diverse coffee bean sources and processing states. Table 7Cross-dataset generalization performance comparison (5-fold cross-validation, Mean ± SD).Table 7Evaluation datasetModelPrecision (%)Recall (%)F1 (%)mAP@50 (%)Inference time (ms)RoastedCoffeeDefectDataset (Roasted, 6 classes)YOLOv1078.4±1.380.1±1.279.2±1.284.3±1.04.2Ours88.7 ± 0.790.2 ± 0.689.4 ± 0.693.5 ± 0.52.1Coffee Bean Classification (Green, Generic defects)YOLOv1085.2±0.987.0±0.886.1±0.891.8±0.64.1Ours94.3 ± 0.495.1 ± 0.494.7 ± 0.497.2 ± 0.32.0Green Coffee Beans Dataset (Green, 7 classes)YOLOv1083.8±1.085.6±0.984.7±0.990.2±0.74.0Ours92.5 ± 0.593.3 ± 0.592.9 ± 0.596.1 ± 0.42.0Self-built Dataset (Green, 7 classes)YOLOv1089.6±0.691.7±0.590.6±0.696.6±0.44.0Ours98.5 ± 0.298.8 ± 0.298.6 ± 0.299.2 ± 0.12.0 Cross-dataset generalization performance comparison (5-fold cross-validation, Mean ± SD). Computational efficiency and practical implications The computational efficiency of our framework merits particular attention, as it directly determines the feasibility of deployment in industrial quality control systems. Operating at an inference latency of just 2.0 ms per image, our model delivers processing speeds that are 10 times faster than Faster R-CNN (20.0 ms), 2.5 times faster than YOLOv8 (5.0 ms), and 1.5 times faster than the state-of-the-art YOLOv11 (3.0 ms). Furthermore, the compact 15.6 MB model size facilitates seamless integration into edge computing devices with strict memory constraints, representing a critical advantage over the cumbersome 170.4 MB footprint of Faster R-CNN. These efficiency breakthroughs are rooted in our architectural design principles: DSConv minimizes memory access and accelerates computation via integer-domain operations; SPPF-Attention ensures targeted feature enhancement without the prohibitive overhead of full self-attention mechanisms; and PConv systematically eliminates redundant channel-wise computations. These performance and efficiency metrics translate directly into substantial economic and operational benefits for coffee bean processing facilities. By achieving a 99.2% mAP@50 alongside a 98.8% recall rate, the framework restricts the false negative rate to approximately 1.2%, meaning fewer than 12 defective beans per 1000 will evade detection. Beyond high precision, the exceptional computational efficiency guarantees cost-effective scalability. A single mid-range GPU can reliably support four to six parallel sorting lines operating concurrently at standard industrial throughput rates. Consequently, deploying this automated inspection system drastically reduces capital expenditure for agricultural facilities while simplifying long-term hardware maintenance. Ablation study A series of ablation experiments was systematically conducted under the strict 5-fold cross-validation framework, isolating the individual and cumulative effects of each proposed module. This incremental evaluation identifies the specific performance gains generated by the lightweight DSConv, context-aware SPPF_Attention, and occlusion-robust PConv modules, while effectively ruling out random data fluctuations. Four network configurations were evaluated sequentially: (1) Baseline YOLOv10, (2) YOLOv10 with DSConv, (3) YOLOv10 with DSConv and SPPF_Attention, and (4) Our complete framework incorporating all three modules. Performance evolution. Table 8 shows that the progressive integration of the three modules yields a monotonic improvement across all evaluation metrics, accompanied by a continuous narrowing of the standard deviations. Compared to the baseline, adding DSConv initially increases the average precision, recall, and F1 scores by 7.3%, 4.6%, and 6.0%, respectively. The subsequent addition of SPPF_Attention provides a stable secondary enhancement of approximately 1.0% to 1.4% across these metrics. Incorporating PConv ultimately achieves the highest overall performance, delivering cumulative relative gains of 9.9% in precision, 7.7% in recall, and 8.8% in F1 score over the baseline. Table 8Ablation study results illustrating incremental performance gains (5-fold cross-validation, Mean ± SD).Table 8MethodDefect typePrecision (%)Recall (%)F1 (%)mAP@50 (%)YOLOv10Black Bean86.5±1.395.2±0.890.6±1.096.8±0.5Float Bean86.1±1.495.7±0.990.5±1.196.7±0.6Immature Bean93.9±0.770.0±2.180.2±1.593.2±0.9Moldy Bean94.6±0.693.8±0.894.2±0.697.7±0.4Shell Bean96.2±0.592.2±1.094.2±0.798.6±0.3Shrink Bean78.9±1.897.0±0.687.1±1.294.8±0.7Sour Bean90.9±0.997.9±0.594.3±0.698.6±0.3Average89.6 ± 1.191.7 ± 1.090.6 ± 1.096.6 ± 0.5YOLOv10 + DSConvBlack Bean94.2±0.696.6±0.595.4±0.597.9±0.3Float Bean97.4±0.494.6±0.696.0±0.499.0±0.2Immature Bean97.9±0.394.8±0.596.3±0.398.8±0.2Moldy Bean98.5±0.296.2±0.497.3±0.398.6±0.2Shell Bean94.2±0.793.8±0.694.0±0.698.3±0.3Shrink Bean91.5±0.895.4±0.593.4±0.698.4±0.3Sour Bean99.0±0.2100.0±0.099.5±0.199.5±0.1Average96.1 ± 0.595.9 ± 0.596.0 ± 0.498.7 ± 0.2YOLOv10 + DSConv + SPPF_AttentionBlack Bean96.8±0.496.9±0.496.8±0.399.0±0.2Float Bean96.3±0.597.0±0.496.6±0.498.5±0.3Immature Bean94.8±0.593.7±0.694.2±0.598.5±0.2Moldy Bean96.1±0.499.5±0.297.8±0.399.2±0.2Shell Bean100.0±0.095.9±0.597.9±0.399.4±0.1Shrink Bean95.5±0.597.9±0.496.7±0.499.1±0.2Sour Bean99.6±0.199.6±0.199.6±0.199.5±0.1Average97.0 ± 0.497.2 ± 0.497.1 ± 0.399.0 ± 0.2YOLOv10 + DSConv + SPPF_Attention + PConv (Ours)Black Bean97.7±0.397.4±0.497.5±0.398.9±0.2Float Bean97.5±0.399.3±0.298.4±0.298.6±0.2Immature Bean97.9±0.297.5±0.397.7±0.299.3±0.1Moldy Bean96.8±0.399.6±0.198.2±0.299.4±0.1Shell Bean100.0±0.099.7±0.199.8±0.199.5±0.1Shrink Bean99.9±0.199.2±0.299.6±0.199.5±0.1Sour Bean99.6±0.198.6±0.399.1±0.299.5±0.1Average98.5 ± 0.298.8 ± 0.298.6 ± 0.299.2 ± 0.1 Ablation study results illustrating incremental performance gains (5-fold cross-validation, Mean ± SD). •DSConv: Incorporating DSConv markedly boosts the model’s discriminative capacity while preserving computational efficiency. The baseline YOLOv10 struggled significantly with the immature bean category, exhibiting a low recall of 70.0±2.1%. Integrating DSConv drives this metric up to 94.8±0.5%, achieving a dramatic relative improvement of 35.4%. Such a gain confirms the module’s exceptional sensitivity in capturing subtle spectral variations and incomplete maturation features. DSConv: Incorporating DSConv markedly boosts the model’s discriminative capacity while preserving computational efficiency. The baseline YOLOv10 struggled significantly with the immature bean category, exhibiting a low recall of 70.0±2.1%. Integrating DSConv drives this metric up to 94.8±0.5%, achieving a dramatic relative improvement of 35.4%. Such a gain confirms the module’s exceptional sensitivity in capturing subtle spectral variations and incomplete maturation features. •SPPF_Attention: The context-aware SPPF_Attention module provides consistent refinement, particularly for structurally defective beans. The shell bean class achieves a perfect precision score of 100.0±0.0% under this configuration. Expanding the receptive fields and applying adaptive spatial-channel weighting clearly capture the shape irregularities and contextual cues critical for identifying hollow or partially deformed beans. SPPF_Attention: The context-aware SPPF_Attention module provides consistent refinement, particularly for structurally defective beans. The shell bean class achieves a perfect precision score of 100.0±0.0% under this configuration. Expanding the receptive fields and applying adaptive spatial-channel weighting clearly capture the shape irregularities and contextual cues critical for identifying hollow or partially deformed beans. •PConv: Adding PConv introduces the most balanced stabilization across all categories by effectively handling irregular geometric boundaries and partial occlusions. It elevates the shrink bean precision from 95.5% to a near-perfect 99.9%, and pushes the F1 scores for both shrink and shell beans above 99.6% with minimal variance (≤0.1%). PConv: Adding PConv introduces the most balanced stabilization across all categories by effectively handling irregular geometric boundaries and partial occlusions. It elevates the shrink bean precision from 95.5% to a near-perfect 99.9%, and pushes the F1 scores for both shrink and shell beans above 99.6% with minimal variance (≤0.1%). These findings confirm that each module serves a distinct and complementary function: DSConv extracts fine-grained features with lightweight efficiency, SPPF_Attention enriches multi-scale contextual representation, and PConv strengthens robustness against complex boundaries. Their synergistic combination yields a highly reliable detector capable of maintaining exceptional accuracy and statistical stability across diverse defect manifestations. Performance visualization and interpretability analysis To gain a deeper understanding of the model’s decision behavior and feature sensitivity, we conducted a comprehensive visualization analysis using both activation mapping and confusion matrix diagnostics. Activation visualization via EigenCAM. We employ the EigenCAM technique to visualize the attention distribution of the convolutional layers during inference. EigenCAM, a class activation mapping (CAM) method, highlights discriminative regions contributing most to classification decisions, offering an intuitive interpretation of how the model focuses on relevant features. In the generated heatmaps, warm colors (e.g., red and yellow) denote regions of strong activation, while cool colors (e.g., blue) correspond to weak or background responses. Fig. 5 presents representative visualization results across seven major defect types. The first row displays the original images, the second shows the baseline YOLOv10 activation maps, and the third visualizes those generated by our model. Comparison of class activation distributions generated by the YOLOv10 and our model using EigenCAM. The improved model exhibits stronger and more localized activations corresponding to defect regions, validating its enhanced discriminative focus. A clear contrast emerges between the two models. The baseline YOLOv10 tends to produce dispersed activations with notable background interference, suggesting that early convolutional layers attend to non-salient textures. After integrating the attention-enhanced modules (SPPF-Attention and PConv), the activations become more spatially compact and align closely with the target bean regions. The refined focus along bean boundaries and texture-rich zones demonstrates that the improved architecture not only enhances feature selectivity but also suppresses irrelevant background cues. This visualization evidence corroborates the quantitative gains observed in Section 5.6, confirming that attention mechanisms effectively guide the network toward semantically meaningful representations. Confusion matrix analysis. To further assess classification reliability and inter-class confusion, we analyze the normalized confusion matrix shown in Fig. 6. Diagonal values indicate correctly classified samples, whereas off-diagonal elements represent misclassifications. Overall, the model achieves consistently high recognition rates along the diagonal, ranging from 0.89 to 1.00, reflecting strong discriminative capacity across most defect categories. Among all classes, the immature bean category exhibits the lowest recognition rate (0.89), with dispersed misclassifications toward black, sour, and shell classes. This pattern suggests visual similarity and intra-class heterogeneity, likely caused by subtle color gradients and incomplete texture development during maturation. In contrast, shell and shrink beans show nearly perfect separability (0.99–1.00), validating the model’s robustness in recognizing structurally distinctive defects. Normalized confusion matrix of the proposed model across seven categories. Interpretability and model behavior insights. The combined visualization findings reveal that the improved YOLOv10 framework achieves both enhanced accuracy and interpretability. The EigenCAM maps demonstrate that the model learns to emphasize semantically meaningful bean structures while suppressing irrelevant backgrounds. Concurrently, the confusion matrix analysis validates the model’s ability to maintain high intra-class confidence and inter-class separation. These visual diagnostics substantiate that performance gains observed in the ablation study stem from genuine improvements in feature representation and decision robustness rather than overfitting or random variance, representing key characteristics of trustworthy and deployable AI systems. Conclusion This study establishes a highly efficient paradigm for automated coffee bean quality assessment by systematically innovating upon the YOLOv10 framework. To resolve the critical bottleneck between detection accuracy and computational constraints in industrial edge environments, we integrated three complementary modules: DSConv for lightweight feature extraction, SPPF-Attention for adaptive multi-scale context aggregation, and PConv for occlusion-robust processing. Rather than relying on computationally exhaustive architectures, this research demonstrates that strategically customized feature refinement can capture subtle, highly variable defect morphologies at a fraction of the typical computational cost. The empirical evidence confirms the superiority and synergistic complementarity of these modifications. Evaluated under a rigorous 5-fold cross-validation protocol, the framework achieves a peak mAP@50 of 99.2%, with 98.5% precision and 98.8% recall, effectively restricting the false negative rate to 1.2%, ensuring that very few defective beans evade detection, while the 98.5% precision minimizes unnecessary rejection of high-quality beans. Systematic ablation studies quantify this success, demonstrating a cumulative 9.9% precision and 8.8% F1 score improvement over the baseline YOLOv10. Crucially, these accuracy gains do not compromise deployment viability; the model achieves 33.3% faster inference and a 21.6% parameter reduction compared to the state-of-the-art YOLOv11. Furthermore, extensive cross-dataset evaluations on three independent public datasets verify that the network learns intrinsic, invariant defect characteristics rather than merely overfitting to specific laboratory conditions. For the coffee processing industry, these metrics translate directly into a scalable, high-throughput automated sorting solution that substantially surpasses human inspection capabilities without fatigue-induced degradation. Limitations and future work Despite these advances, several limitations warrant acknowledgment and provide clear directions for future research. The current evaluation focuses predominantly on seven major defect categories specific to Yunnan small-grain coffee. Furthermore, while the laboratory setup simulates realistic sorting scenarios, actual factory deployments introduce dynamic physical disruptions, including high-speed conveyor vibration, ambient illumination shifts, and sensor degradation from dust accumulation. Future research will focus on unsupervised domain adaptation to seamlessl bridge the distribution gap between controlled laboratory data and complex industrial production lines. Additionally, investigating transfer learning and few-shot learning strategies will be critical for rapidly scaling the framework to recognize long-tail defect categories, distinct processing methods, and novel global coffee varieties without requiring exhaustive manual re-annotation. CRediT authorship contribution statement Sunyan Hong: Methodology, Software, Visualization, Writing – original draft, Writing – review & editing. Dengji Zhang: Methodology, Data curation, Software, Writing – original draft. Haiyang Chi: Conceptualization, Methodology, Formal analysis, Writing – original draft, Writing – review & editing. Jun He: Conceptualization, Funding acquisition, Validation. Xiudong Guo: Data curation, Validation. Hui Fu: Formal analysis, Validation. Lu Wang: Conceptualization, Data curation. Declaration of competing 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. Acknowledgments This research was supported by the Yunnan Science and Technology Innovation Base Construction Project (Grant No. 202407AB110006), the Project of Yunnan Daguan Laboratory (Grant No. YNDG202401ZN01), and the Yunnan Science and Technology Talent Program Project (Grant No. 202305AC160049), all of which were funded by the Science and Technology Department of Yunnan Province . Handling editor Georgios Leontidis Footnotes https://github.com/dont-text-me/RoastedCoffeeDefectDataset. https://www.kaggle.com/datasets/ardiyanto24/coffee-bean-classification-dataset. https://github.com/j4ckdev/greencoffeebeansdataset. Data availability Data will be made available on request. References Associated Data Data Availability Statement Data will be made available on request.