Automated stomatal traits measurement in melon (Cucumis melo L.) based on vision transformers with dynamically composable multi-head attention Authors: Yao Huang, Lelong Yan, Jiaxi Yang, Chunyan Cheng, Yuhui Wang, Ji Li, Qunfeng Lou, Yongbing Zhang, Chuntao Qian Published: 2026 ABSTRACT AbstractStomatal trait analysis is essential for optimizing crop photosynthesis and transpiration, yet deep learning studies have focused mainly on monocotyledons, leaving dicotyledonous crops such as melon (Cucumis melo L.) understudied. To bridge this gap, we established a dedicated melon stomatal dataset comprising 5,708 training images, 1,631 validation images, and 815 test images. On this basis, we developed an improved Mask R-CNN framework using Vision Transformer (ViT) as the backbone. Specifically, standard Multi-Head Attention (MHA) was replaced with Dynamically Composable Multi-Head Attention (DCMHA), which enhances information exchange across attention heads and alleviates the low-rank limitation of conventional attention. In addition, a modified effective Squeeze-and-Excitation (eSE) module was incorporated into the Feature Pyramid Network (FPN) to strengthen channel dependency modeling and multi-scale feature representation. On the melon dataset, the proposed model achieved a mean average precision (mAP) of 72.40 ± 0.09%, with AP50 and AP75 of 91.93 ± 0.14% and 84.59 ± 0.19%, respectively. Repeated-run statistical analyses showed that eSE significantly and consistently improved the main detection metrics across backbones, whereas DCMHA provided a more moderate gain within the ViT-based setting, with clearer support for AP50 than for mAP or AP75 under the baseline FPN setting. Overall, the combined configuration remained among the top-performing models for stomatal instance segmentation. Ellipse fitting further enabled automated quantification of stomatal length, width, count, area, and circumference, showing strong agreement with manual measurements (Pearson r = 0.978). The model also showed preliminary transferability to cucumber, watermelon, pumpkin, and loofah, with an average species-specific R² of 0.86, although each species was evaluated on a limited sample set.Supplementary InformationThe online version contains supplementary material available at https://doi.org/10.1186/s13007-026-01558-x.Keywords: Melon, Stomata, Vision transformers, Effective squeeze and excitation, Dynamically composable multi-head attention Introduction Leaf stomata, which are micropores in the leaf epidermal tissue bounded by two guard cells, regulate gas and water vapor exchange between plants and the external environment [1]. Through dynamic regulation of their opening and closure, stomata enable plants to coordinate photosynthesis and transpiration [2]. This mechanism directly impacts CO₂ uptake, water metabolism, and light energy conversion efficiency. Stomatal trait parameters (e.g., stomatal density, pore size) exhibit significant correlations with photosynthetic capacity and water use efficiency. These traits can serve as phenotypic markers for screening germplasm resources with high photosynthetic efficiency [3] or drought resistance [4], thereby providing a theoretical foundation for molecular design breeding. The detection and measurement of stomatal features can be achieved through various methods. Conventional manual approaches, however, are often labor-intensive, prone to error, and lack scalability [1], making them increasingly inadequate for the precision and high-throughput demands of modern breeding programs. In response, automated systems based on Deep Learning (DL) and Machine Learning (ML) have emerged as powerful alternatives for stomatal phenotyping [5]. Research in this area has grown rapidly, with publications peaking in 2021 [6]. These approaches encompass object detection methods, such as AlexNet [7], R-CNN [8], VGG [9], Faster R-CNN [10], SSD [11], YOLO [12], MobileNet [5], R3DET [13] and DeepRSD [1], as well as semantic segmentation approaches, including U-Net [14] and Mask R-CNN [15]. Although significant progress has been made in stomatal studies using deep learning (DL) approaches, most models have primarily focused on woody plants and monocotyledons [5, 7]. These studies mainly adopted the nail polish imprinting method for dataset construction. However, this method presents significant limitations when applied to dicotyledonous plants, as their tender leaves frequently result in incomplete stomatal impressions [1]. To address this, we applied the I2-KI impregnation method. Stomatal images acquired through these two methods, however, exhibit substantial inconsistencies in morphology, color, and background characteristics. Moreover, existing stomatal detection studies are mainly based on CNN-, YOLO-, or U-Net-style frameworks and are often tailored to specific species or imaging settings, as summarized in Supplementary Fig. 1. This comparison suggests that current methods are still largely application-specific and do not adequately address dicotyledonous stomatal detection under I2-KI staining conditions. The backbone of most current models relies on Convolutional Neural Networks (CNNs), but state-of-the-art instance segmentation models with higher accuracy are increasingly based on Transformer architectures [16, 17]. This shift underscores the necessity of updating existing stomatal detection models to enhance their performance, particularly for dicots. A critical limitation of Transformer-based models lies in their Multi-Head Attention (MHA) mechanism, which faces the issues of low-rank bottlenecks in the attention score matrices and redundancy among the attention heads [18]. To address this issue, Xiao et al. proposed the Dynamically Composable Multi-Head Attention (DCMHA) mechanism as a replacement for the original MHA [18], a design that enables adaptive interactions among attention heads and thereby improves the expressive capacity of attention modeling. Their results showed that DCMHA significantly outperforms MHA across various architectures and model scales in language modeling tasks. Building on this advancement, we applied DCMHA to enhance the performance of the Vision Transformer (ViT) on our dataset [19], aiming to overcome the limitations of traditional MHA and achieve more accurate stomatal detection. Given that stomatal detection is a single-goal task involving objects of nearly uniform size, the required receptive field remains relatively consistent. To further improve performance without significantly increasing computational overhead, we incorporated an efficient Squeeze-Excitation (eSE) channel attention module [20], which is a lightweight channel-attention mechanism that recalibrates the importance of different feature channels. This lightweight modification enables the model to focus more effectively on specific-scale feature maps within the Feature Pyramid Network (FPN), a multi-scale feature fusion architecture that integrates feature maps of different resolutions, thereby enhancing detection accuracy while maintaining computational efficiency. Accordingly, this study presents a stomata-oriented adaptation of Mask R-CNN for dicot stomatal detection under I2-KI staining conditions. Our contribution is twofold: first, we provide a melon stomatal dataset comprising 8,154 images for this application; second, we evaluate two targeted architectural modifications, namely DCMHA in the ViT backbone and an eSE-enhanced FPN, within a stomata-oriented Mask R-CNN framework under this imaging condition. Our results show that these two modules provide complementary but unequal benefits, with eSE contributing a broader and more consistent gain across backbones and DCMHA providing a more moderate refinement within the ViT-based setting. Therefore, the main contribution of this study lies in application-oriented adaptation and evaluation rather than in proposing a fundamentally new detection architecture. Related work Recent reviews have shown that deep learning has substantially advanced stomatal phenotyping, but current methods still face persistent trade-offs among throughput, morphological precision, annotation cost, and generalizability across species, imaging devices, and acquisition conditions [6, 21]. These reviews also emphasize that object detection is generally more suitable for counting and density estimation, whereas semantic and instance segmentation provide richer boundary-level morphology at the cost of denser annotation, higher computational demand, and stronger sensitivity to image quality and environmental variation. CNN-based stomatal detection remains the most widely adopted paradigm. Early and influential tools such as StomataCounter [22] and LabelStoma [23] focused mainly on rapid stomatal localization and counting, while later studies extended CNNs toward broader applicability and stronger morphology awareness. For example, Jayakody et al. used Mask R-CNN with FPN and a statistical filter to detect individual boundaries across 16 datasets from 12 sources containing more than 60,000 stomata, reaching 95.10% precision, 83.34% recall, and an IoU of 0.70 [24]. Likewise, Kwong et al. showed that a MobileNetV1-SSD detector can achieve 96% mAP and maintain high precision and recall across several independent test sets [25], whereas Meng et al. demonstrated that Mask R-CNN can jointly support stomatal counting and aperture-related measurements [15]. These studies confirm that CNN-based models are efficient, mature, and practical for high-throughput stomatal analysis. However, their limitations are equally clear: many CNN detectors still rely primarily on local feature extraction, remain sensitive to blur and dataset shift, and often struggle when stomata vary strongly in size or appear in heterogeneous backgrounds. Jayakody et al. explicitly identified image quality as the major factor affecting recall and boundary estimation [24], while the haskap (Lonicera caerulea L.) study showed that blur degrades aperture measurement much more than stomatal counting [15]. Transformer-based stomatal studies remain limited in the current literature, and existing evidence is still concentrated mainly on semantic segmentation. Zhou et al. used a SegFormer-based architecture together with cross-layer feature fusion to improve stomatal semantic segmentation [26]. WSF explicitly argues that conventional object detectors mark stomata with bounding boxes and still require downstream image processing to recover pixels, while UNet and Mask R-CNN remain limited by insufficient boundary precision, weak long-range dependency modeling, and reduced effectiveness on small stomata. By contrast, SegFormer-style self-attention can capture global contextual information and improve small-target boundary delineation in complex backgrounds. In experiments, WSF outperformed SegFormer, DeepLabv3+, and UNet, achieving 93.6% precision and 91.2% mIoU. Nevertheless, transformer-based stomatal work remains limited in number and is still concentrated mainly on semantic segmentation rather than instance-level detection and segmentation. WSF itself also notes that performance is affected by field noise, uneven illumination, and cross-species variation, indicating that transformer-based stomatal phenotyping is promising but not yet mature. Hybrid approaches combine deep detection with segmentation, classical computer vision, geometric measurement, or task-specific post-processing, and are especially common when the final objective is a biological trait rather than stomatal counting alone. Liang et al. integrates FPN-based counting, Faster R-CNN-based open/closed recognition, and pore segmentation to extract six pore traits with R² values above 0.85 [27]. Zhu et al. combines Faster R-CNN, U-Net, and image processing to estimate stomatal index, reaching 98.03% counting accuracy for stomata, 95.03% for epidermal cells, and 95.35% for stomatal index [28]. Takagi et al. combines YOLOX-based detection with U-Net-based pore segmentation and achieves a stomatal aperture error of only 0.2 ± 0.2 μm, but the authors explicitly state that the pipeline is not a generalized module and requires further fine-tuning for images from other devices [14]. More recently, Wang et al. used YOLOv8 segmentation and geometric algorithms to quantify over 30 stomatal and guard-cell metrics and was tested on over 100 species [29], while Xu et al. reported high SI reliability even under complex pavement-cell morphology [30]. These studies show that hybrid pipelines are highly valuable for stomatal index, pore traits, guard-cell morphometry, and phenotype-oriented analysis. However, they are often modular and condition-specific, so errors can accumulate across stages and cross-device or cross-species transfer remains limited. Overall, the existing literature reveals a clear gap. CNN-based methods are efficient and practical, but often remain limited by local feature extraction, sensitivity to blur, and insufficient robustness for small and densely distributed stomata under complex backgrounds. Transformer-based methods offer stronger global context modeling and better potential for handling scale variation and boundary ambiguity, but current stomatal applications are still sparse and focus mainly on semantic segmentation. Hybrid approaches can extract richer trait information, but they typically rely on multi-stage pipelines whose robustness and transferability remain constrained by device, species, and imaging condition. Therefore, there is still a need for an instance-level stomatal detection and segmentation framework that retains the practicality of Mask R-CNN while enhancing global context modeling and multi-scale feature fusion for complex-background, multi-scale stomatal images. Materials and methods Acquisition of data, semi-automated labeling of images, and data augmentation Acquisition of data Melon microscopic images were captured using an optical microscope (Olympus CX300). Because melon leaves are tender, peeling the epidermis using tweezers or transparent adhesive tape, as used in some other crops, is challenging. Therefore, we used an I2-KI staining method to prepare the leaves for microscopic observation. Melon leaves from different positions were treated with a decolorizing solution consisting of anhydrous ethanol and glacial acetic acid in a 3:1 ratio until the green pigmentation completely faded. The decolorized leaves were then rinsed in sterile water for 3–5 min, followed by gentle blotting with filter paper to remove excess moisture. Next, the leaves were stained with a 1% I₂-KI solution for 1–5 min, mounted with a coverslip, and imaged under a ‘20×’ or ‘40×’ objective lens (Fig. 1). A total of 8,154 images were collected and subsequently divided into training (5,708), validation (1,631), and test sets (815). Additionally, microscopic images of other Cucurbitaceae crops including cucumber, watermelon, pumpkin, and loofah were acquired to evaluate the generalization ability of our model. Details were provided in Supplement Table 5Supplement Table 6. Microscopic images of melon leaf sections captured under different objective magnifications for stomatal observation. a Image acquired under a ‘20×’ objective, showing multiple stomata and surrounding epidermal cells (scale bar = 15 μm). b Image acquired under a ‘40×’ objective, showing enlarged stomatal structures with clearer local details (scale bar = 7.5 μm) Semi-automated labeling of images To improve labeling efficiency, a semi-automatic image annotation method was developed (Fig. 2). Specifically, an initial set of 1,000 images was selected from the dataset and manually annotated using the ‘anylabeling’ software. These annotated images were then used to train a Mask R-CNN model with a ResNet34 backbone. ResNet34 was selected as the backbone because it provides a good balance between feature extraction capability and computational efficiency, making it suitable for preliminary stomatal annotation. Next, 2,000 unlabeled images were processed using the trained model to generate preliminary annotations. These annotations served only as initial labeling results rather than final annotations and were manually corrected using ‘anylabeling’ to ensure accuracy. The corrected images, along with the previously labeled data, were then used for further model training. This iterative process was repeated five times, with the number of annotated images increasing sequentially to 1,000, 3,000, 5,000, 7,000, and finally 8,154. After each iteration, all model-generated annotations were manually reviewed and corrected image by image, and the time required for manual correction was recorded to evaluate the efficiency of the semi-automatic annotation process. Flowchart of the semi-automated labeling process. Unlabeled microscopic images were processed by Mask R-CNN to generate preliminary annotations, which were then manually corrected and saved as .json files. The manually corrected annotations were added back to the training set for the next round of model training. This procedure was repeated for five iterations to progressively expand the labeled dataset Data augmentation During deep learning training, data augmentation is crucial for improving the quality and diversity of microscopic stomatal images. By applying minor transformations or generating synthetic variations, this process expands the dataset, enhances model robustness, and reduces the risk of overfitting. In this study, the dataset was first divided into training, validation, and test sets, and all augmentation operations were applied only to the training set to avoid potential data leakage. The validation and test sets were not augmented, except for image resizing used as a preprocessing step for input standardization. Four augmentation techniques were employed: (1) Random Cropping, where images were cropped by 20% of their original area to simulate different viewpoints and improve feature recognition; (2) Random Rotation, with predefined angles (0.2, 0.5, 0.78, and 0.1 radians) to enhance rotational invariance; (3) Random Lighting, adjusting brightness with a ratio of 0.5 to improve adaptability under varying illumination; and (4) Resizing, standardizing images to 240 × 360 pixels for consistency in training and testing. These augmentations collectively strengthen the model’s generalization ability for microscopic stomatal detection. However, for the 25-epoch backbone comparison experiments reported in Sect. 2.2, only resizing was applied to ensure fair comparison across backbones. Enhanced mask R-CNN architecture In this study, we developed an enhanced Mask R-CNN framework (eMask R-CNN) for stomatal detection and instance segmentation in melon microscopic images (Fig. 3). Relative to the standard Mask R-CNN framework, the main modifications in our model are twofold: (1) the use of a ViT backbone with Dynamically Composable Multi-Head Attention (DCMHA) to enhance global contextual modeling; and (2) the integration of an effective Squeeze-and-Excitation (eSE) module into the Feature Pyramid Network (FPN) to improve channel-wise feature recalibration and multi-scale representation. Specifically, the ViTDC backbone uses the final high-level feature map as the primary feature source, from which multi-scale feature maps are generated through parallel convolution and deconvolution operations [16, 31]. In addition, the FPN channels were reduced from 256 to 128, and local window attention was adopted to improve computational efficiency. The Region Proposal Network (RPN), RoIAlign, and parallel prediction heads follow the standard Mask R-CNN design [32]. Architecture overview of the proposed ViT-based Mask R-CNN framework. The input microscopic image is first divided into patches and linearly projected as tokens, which are then processed by a Transformer encoder with DCMHA to enhance global attention modeling. The output feature maps are fed into the Feature Pyramid Network (P1–P4), where the effective Squeeze-and-Excitation (eSE) module is introduced to recalibrate channel-wise responses and improve multi-scale feature representation. The refined features are subsequently used for stomatal detection and instance segmentation Backbone with DCMHA In our research, we selected the ViT as the backbone of our eMask R-CNN model, as depicted in Fig. 3. The conventional Transformer processes inputs as a sequence of 1-dimensional token embeddings. To adapt to 2D images, we convert the image x (240 × 360 × 3) into a sequence of 2D patches Xp∈ℝn×(p2·c), where (h, w) denotes the dimensions of the original image, C is the channel count, (p, p) is the size of each patch, and n = hw/p2 represents the number of patches, which also acts as the sequence length for the Transformer. The MHA mechanism is central to the Transformer’s functionality. However, the independent operation of attention heads in MHA can lead to issues such as the low-rank bottleneck in attention score matrices and redundancy among heads. To address these issues, we have implemented the DCMHA mechanism, as shown in Fig. 4, in place of the traditional attention heads. DCMHA is a more efficient attention architecture in terms of parameters and computations, in which different attention heads can interact adaptively rather than remain fully independent, and thus enhances the model’s expressive capacity by dynamically combining attention heads [18]. The DCMHA was defined as follows: Schematic illustration of the Dynamically Composable Multi-Head Attention (DCMHA) module. The input queries (Q), keys (K), and values (V) are first projected and split into multiple heads. The attention scores are then dynamically composed, normalized by Softmax, and used for matrix multiplication with the value features. The outputs of all heads are finally merged and projected to produce the final attention representation. H denotes the number of heads, L denotes the vector length, D denotes the dimension of each head, and where Q, K, and denote the query, key, and value feature matrices, respectively; L is the sequence length; is the feature dimension; H is the number of attention heads; is the feature dimension of each head, with ; and is the scaling factor used for attention normalization. , , and are the projection matrices of the i-th head. represents the attention score matrix of the i-th head, and is the stacked attention tensor of all heads. The stacked attention scores are then refined by the first Compose operation before normalization: where Compose denotes the proposed dynamic composition operation, as shown in Fig. 4, and represents its trainable parameters before the Softmax normalization. Next, the refined attention tensor is normalized by the Softmax function and further processed by a second Compose operation: where the Softmax function is applied along the last dimension to obtain normalized attention weights, and denotes the trainable parameters of the post-normalization composition step. is the final weighted attention tensor. Finally, the output of each attention head is computed by multiplying the weighted attention tensor with the projected value features: where is the output of the i-th attention head, denotes concatenation across all heads, and is the output projection matrix. The final output feature is . As illustrated in Fig. 4, the DCMHA module consists of projection and split operations, matrix multiplication, two Compose blocks, Softmax normalization, value interaction, and merge-and-project steps, which together enhance the representation ability of multi-head attention. The core of DCMHA is the Compose function, as illustrated in Fig. 5. Given an input attention tensor , where His the number of attention heads and Lis the sequence length, the Compose module transforms the input through five parallel branches and sums their outputs to generate a new attention tensor. Schematic illustration of the Compose function in the DCMHA module. Starting from the input attention tensor , the module refines it through five parallel branches, namely key-wise dynamic gating, key-wise dynamic projection, base projection, query-wise dynamic projection, and query-wise dynamic gating. The outputs of these branches are summed to produce a new KV matrix for subsequent attention composition. This process enables more flexible interaction among attention heads and improves the adaptivity of attention modeling. Here, H denotes the number of heads and L denotes the sequence length These five branches include key-wise dynamic gating, key-wise dynamic projection, base projection, query-wise dynamic projection, and query-wise dynamic gating. Among them, the base projection branch applies an independent learnable matrix to provide a shared basal composition, while the other four branches introduce content-adaptive refinements from the query and key sides. For the query-wise dynamic projection branch, KVis first projected to a lower-rank space of dimension R by , and then projected back to the original head space by . Both and are generated from the query feature Q, allowing adaptive information exchange across different attention heads. For the query-wise dynamic gating branch, KVis modulated element-wise by a gate computed from Q, which controls the degree to which each head preserves or suppresses its original attention response. Similarly, the key-wise dynamic projection and key-wise dynamic gating branches are symmetrically generated from the key feature K, producing , , and , respectively. In this way, the Compose module jointly models dynamic interactions and adaptive gating effects from both the query side and the key side. The query-dependent parameters are computed as follows: where , , and are learnable parameter matrices used to generate , , and , respectively; is the feature dimension; I=2HR is the intermediate hidden dimension; Chunk splits the projected feature into two parts; and Reshape rearranges the tensor into the required form for low-rank projection. RMSNorm without scaling is applied to along the head dimension to stabilize training. The query-dependent gating vector is computed as . The key-dependent parameters are computed in the same way from K. Finally, the outputs of the five branches are summed to obtain the new attention tensor: where denotes element-wise multiplication. This formulation shows that the new attention tensor is jointly determined by one static base projection and four dynamic branches conditioned on the query and key features. FPN adding effective SE-module FPN is a multi-scale feature representation framework in deep convolutional networks that combines low-resolution features with large receptive fields and high-resolution features with small receptive fields. However, stomatal detection is essentially a single-object detection task in which the target size is relatively uniform, and therefore the required receptive field remains comparatively consistent. To improve feature selection without introducing substantial computational overhead, we incorporated a lightweight eSE channel attention module into FPN, which adaptively recalibrates channel responses so that more informative features can be emphasized. This modification enables the network to emphasize more informative feature maps at an appropriate scale. The eSE module is a representative channel attention mechanism widely used in CNN-based architectures. It explicitly models channel interdependencies to enhance feature representation while avoiding the information loss caused by dimensionality reduction in the original SE module. In addition, the original sigmoid activation was replaced by the Swish function. Therefore, the eSE module is defined as: and denotes the learnable weight of the fully connected layer. represents the Swish activation function. The Swish activation is defined as: where denotes the sigmoid activation function applied to X. Furthermore, the feature maps generated by FPN are recalibrated one by one through the eSE module to produce refined feature maps. More details of this process are illustrated in Fig. 6. Schematic illustration of the modified eSE module applied to the FPN feature maps. For each pyramid level (P1–P5), the input feature map is first compressed by global average pooling () to generate a channel descriptor of size . The descriptor is then transformed by a fully connected layer () and the Swish activation function to produce channel-wise weights. These weights are multiplied with the corresponding input feature map for channel recalibration, and the recalibrated features are added back to the original features through a residual connection to obtain the refined output feature maps. Here, C denotes the number of channels, and Hand W denote the height and width of the feature map, respectively Loss function To train the object detection model, the network parameters were optimized by minimizing the corresponding loss functions. Since Mask R-CNN is a multi-task framework, the overall loss is defined as: where , , and denote the classification loss, bounding-box regression loss, and mask prediction loss, respectively. The regression loss is formulated as: where tand represent the predicted and ground-truth bounding-box coordinates, respectively. The smooth L1 loss is defined as: where x denotes the coordinate difference between prediction and ground truth. The mask loss is defined as: where denotes the ground-truth binary mask and s denotes the predicted binary mask. Implementation details, hyper-parameter setting, and model comparison The experiments were conducted on two GeForce RTX 2080 Ti GPUs (11 GB each). The software environment included VS Code 1.91.1, Miniconda3, Python 3.10.12, PyTorch-GPU 1.11.0, Detectron2 v0.6, and Linux with CUDA 11.3 and cuDNN 8.0. Unless otherwise specified, all models were trained using the AdamW optimizer, and the detailed hyperparameter settings are listed in Table 1. For fair backbone comparison, the batch size was set to 2 and the training schedule was 25 epochs. The selected final model was further trained for 300 epochs under the same basic framework. The feature extractor was initialized with ImageNet1K pre-trained weights. Table 1Hyperparameter configurations of different Mask R-CNN backbonesHyper-parametersResnet50Resnet101ConvNextMobileNetV3RegNetViTViTDCTypeAdamWAdamWAdamWAdamWAdamWAdamWAdamWBase LR2.5e-52.5e-5--1.6e-3--betas(0.9, 0.99)(0.9, 0.99)(0.9, 0.99)(0.9, 0.99)(0.9, 0.99)(0.9, 0.99)(0.9, 0.99)Weight decay0.10.10.10.10.10.10.1LR scheduler----WarmupCosineLR--Base LR end----1.6e-6--Gamma0.10.10.10.10.10.10.1Table 1 summarizes the main reproducibility-related training settings of the compared Mask R-CNN backbones, including optimizer type, learning rate, betas, weight decay, learning-rate scheduler, and gamma. Unless otherwise specified, the same basic settings were used across backbones. The batch size, training schedule, pre-training initialization, and hardware/software environment are described in Sect. 1.2.4 Hyperparameter configurations of different Mask R-CNN backbones Table 1 summarizes the main reproducibility-related training settings of the compared Mask R-CNN backbones, including optimizer type, learning rate, betas, weight decay, learning-rate scheduler, and gamma. Unless otherwise specified, the same basic settings were used across backbones. The batch size, training schedule, pre-training initialization, and hardware/software environment are described in Sect. 1.2.4 We performed a thorough comparison on Mask R-CNN in different backbones, including Resnet50, Resnet101, RegNet [33], ConvNext [34], MobileNetV3 [35], ViT and ViTDC (our). Additionally, we applied the FPN with modification eSE module on the above backbones to evaluate the eSE module performance. The concrete hyper-parameters setting is listed in Table 1. For fair backbone comparison, we disabled all augmentations except resize (see 1.1.3), and initialized the feature extractor with the model pre-trained on ImageNet1K. The epoch number and batch size were 25 and 2, respectively. Each backbone comparison experiment was independently repeated three times using different random seeds, and the results are reported as mean ± standard deviation across runs. For quantitative comparison, we primarily used the PASCAL-style metrics mAP, AP50, and AP75. AP50 and AP75 were calculated at IoU thresholds of 0.5 and 0.75, respectively, whereas mAP was computed as the mean AP over IoU thresholds from 0.1 to 0.9. In addition, Precision, Recall, and F1 were used as auxiliary instance-level metrics, whereas mIoU and Dice were used as complementary overlap-based metrics to assess mask quality. These additional metrics were mainly used to examine the stability of backbone ranking and module effects across repeated runs, whereas the main conclusions of this study were based on mAP, AP50, and AP75. Statistical analysis Each backbone comparison experiment was independently repeated three times using different random seeds, and the seed-matched results were used for repeated-run statistical analysis. To evaluate the effect of eSE across backbones, a two-way repeated-measures ANOVA was performed with backbone and method (FPN vs. FPN + eSE) as within-subject factors, using seed as the repeated-measures subject. Post hoc comparisons between FPN and FPN + eSE within each backbone were conducted using paired t-tests with Holm correction for multiple comparisons. To compare backbones under the same method setting, Friedman tests were performed separately for the baseline FPN and the eSE-enhanced FPN setting, using seed-matched results as paired observations. Post hoc pairwise comparisons were then conducted using Holm-corrected paired t-tests. To compare different pre-trained weight initialization strategies, a one-way repeated-measures ANOVA was performed with pre-trained weight as the within-subject factor, again using seed as the repeated-measures subject, followed by Holm-corrected paired t-tests for pairwise comparisons. Unless otherwise noted, statistical significance was defined as P < 0.05. Stomatal traits measurement Stomatal trait measurement The test set (186 images, 960 × 1280) was fed into the trained Mask R-CNN model for inference. The model generated predicted stomatal masks, bounding-box coordinates, and confidence scores. Individual stomatal regions were then cropped according to the predicted bounding boxes. Pore boundaries were extracted from the masks and fitted with ellipses using the least-squares method (0.125 μm pixel⁻¹). Based on the fitted ellipses, we calculated stomatal length, width, circumference, area, and pore number per image using the formulas for pore area and circumference shown below. The detailed process is presented in Fig. 8. Training curves of the final ViTDC + eSE model over 300 epochs. A Detection performance during training, evaluated by mAP, AP50, and AP75, showing that the model gradually converged and achieved stable accuracy in later epochs. B Training loss across 300 epochs, showing an overall downward trend with minor fluctuations, indicating stable model optimization A random selection of 100 images from the test set is made. Utilizing “ImageJ (version 1.8.0)” software, the major and minor axes, circumference, area, and eccentricity of the pores in the images are manually measured, as well as the number of pores per image (excluding those on the image edges). The Pearson correlation coefficient is employed to assess the discrepancy between the predicted and manually measured values. The consistency between manual and automated measurements was evaluated using agreement analysis, including linear relationship assessment, Bland–Altman analysis, and distribution analysis of the measurement differences. Performance of ViTDC on other cucurbitaceae species To evaluate the predicted effect of ViTDC on stomatal datasets of other Cucurbitaceae plants, we collected stomatal images from watermelon, cucumber, pumpkin, and loofah using the same method (1.1.1). The numbers of images for each plant were 50, 52, 58, and 61 respectively. Results Datasets, semi-automated labeling, and data augmentation In this study, we employed semi-automated labeling to complete data annotation across five iterations (Fig. 7). Starting from an initial set of 1,000 manually labeled images, the labeled dataset was gradually expanded to 3,000, 5,000, 7,000, and finally 8,154 images through iterative model-assisted annotation and manual correction. As the iterations progressed, the manual labeling speed increased from 1.04 to 6.41 images per minute (Fig. 7A). Meanwhile, the mAP improved from 82.53 to 90.53, and both AP50 and AP75 showed similar upward trends (Fig. 7B). These results indicate that the semi-automated labeling strategy effectively improved annotation efficiency while supporting iterative model refinement. Finally, all images and their corresponding annotations were prepared for subsequent analysis. Effect of semi-automated labeling over six iterations. A Change in labeling speed, measured as the number of images annotated per minute, from iteration 1 to iteration 6. B Change in model accuracy across iterations, evaluated by mAP, AP50, and AP75 The melon dataset was divided into three subsets: 5,708 training images, 1,631 validation images, and 815 test images. Before training, we applied several augmentation methods to the training set, including random cropping, random rotation, random lighting, and resizing. Comparison to other backbones In this study, two training schedules were used for different purposes: 25 epochs for fair backbone comparison and 300 epochs for final training of the selected model. DCMHA provided a modest but consistent gain in the ViT-based framework We compared ViTDC and ViT as backbones for Mask R-CNN under the same 25-epoch training setting in Tables 1 and 2. Across repeated runs, ViTDC showed higher mean performance than ViT in the baseline FPN setting, with mAP, AP50, and AP75 increasing from 69.09 ± 0.18%, 90.01 ± 0.04%, and 80.55 ± 0.21% to 70.36 ± 0.09%, 91.24 ± 0.07%, and 81.34 ± 0.12%, respectively. These results indicate that DCMHA provides a modest but consistent gain within the ViT-based Mask R-CNN framework. In addition, the four ViT-based configurations in Table 2—iT, ViT + eSE, iT + DCMHA, and ViT+ DCMHA + eSE—contitute a structred ablation study f the proposed method. Adding eSE on top of ViTDC further increased mAP and AP50 to 72.40 ± 0.09% and 91.93 ± 0.14%, respectively, while maintaining a high AP75 of 84.59 ± 0.19%. Table 2Effects of different backbones and eSE-enhanced FPN on stomatal detection performanceBackboneFPNFPN with modification eSEmAPmask/%AP50mask/%AP75mask/%mAPmask/%AP50mask/%AP75mask/%Resnet5067.79 ± 0.1490.46 ± 0.1177.58 ± 0.2271.43 ± 0.1192.48 ± 0.1782.08 ± 0.22Resnet10169.32 ± 0.1188.33 ± 0.0980.29 ± 0.2471.48 ± 0.1391.70 ± 0.1284.60 ± 0.23ConvNext70.19 ± 0.1290.79 ± 0.0581.90 ± 0.2772.91 ± 0.1092.74 ± 0.0383.39 ± 0.23MobileNetV369.73 ± 0.0189.33 ± 0.2079.59 ± 0.0872.60 ± 0.0891.54 ± 0.1383.55 ± 0.07RegNet66.08 ± 0.2288.95 ± 0.0477.41 ± 0.1166.60 ± 0.2488.73 ± 0.0378.48 ± 0.10ViT-Window769.09 ± 0.1890.01 ± 0.0480.55 ± 0.2171.96 ± 0.1291.70 ± 0.1584.60 ± 0.16ViTDC-Window7(Ours)70.36 ± 0.0991.24 ± 0.0781.34 ± 0.1272.40 ± 0.0991.93 ± 0.1484.59 ± 0.19The first five rows compare the stomatal detection performance of different backbone networks and evaluate the effect of introducing the eSE module into the FPN. For the proposed ViT-based framework, the four corresponding configurations in Table 2 constitute a structured ablation study: ViT, ViT + eSE, ViT + DCMHA, and ViT + DCMHA + eSE. Here, ViTDC-Window7 denotes the ViT-Window7 backbone equipped with the proposed DCMHA module. Because DCMHA is a ViT-specific modification of the attention mechanism, its contribution is evaluated within the ViT-based Mask R-CNN framework. Values are reported as mean ± standard deviation over three independent runs with different random seeds. Statistical significance for the FPN versus FPN + eSE comparison within each backbone is provided in Supplementary Fig. 1, and overall backbone-wise repeated-run comparisons under each method setting are shown in Supplementary Fig. 2 and Supplementary Fig. 3. Complete multi-metric results for all compared backbones and settings are provided in Supplement Table 3 Effects of different backbones and eSE-enhanced FPN on stomatal detection performance ViTDC-Window7 (Ours) The first five rows compare the stomatal detection performance of different backbone networks and evaluate the effect of introducing the eSE module into the FPN. For the proposed ViT-based framework, the four corresponding configurations in Table 2 constitute a structured ablation study: ViT, ViT + eSE, ViT + DCMHA, and ViT + DCMHA + eSE. Here, ViTDC-Window7 denotes the ViT-Window7 backbone equipped with the proposed DCMHA module. Because DCMHA is a ViT-specific modification of the attention mechanism, its contribution is evaluated within the ViT-based Mask R-CNN framework. Values are reported as mean ± standard deviation over three independent runs with different random seeds. Statistical significance for the FPN versus FPN + eSE comparison within each backbone is provided in Supplementary Fig. 1, and overall backbone-wise repeated-run comparisons under each method setting are shown in Supplementary Fig. 2 and Supplementary Fig. 3. Complete multi-metric results for all compared backbones and settings are provided in Supplement Table 3 This tendency was further supported by the repeated-run post hoc analysis in Supplementary Fig. 2 Statistical comparison of different backbones under the baseline FPN setting across repeated runs. The evaluated metrics include (a) mAP (mask), (b) AP50 (mask), (c) AP75 (mask), (d) Precision, (e) Recall, (f) F1, (g) mIoU, and (h) Dice. For each metric, the backbones are ordered according to their mean performance. Bar heights indicate the mean values across independent runs, and error bars indicate standard deviation. The brackets indicate pairwise post hoc comparisons among backbones based on the corresponding repeated-run statistical analysis. Under the baseline setting, ViTDC generally showed a moderate but consistent advantage over ViT in the main detection-oriented metrics, whereas the differences among backbones were smaller for overlap-based mask metrics such as mIoU and Dice. Significance levels are indicated as follows: P < 0.05 (), P < 0.01 (), P < 0.001 (), and not significant (ns). A Friedman test was performed within each method to assess overall differences among backbones, using seed-matched results as paired observations. Post hoc comparisons between ViT-Window7 and each of the other backbones were conducted using paired t-tests with Holm correction for multiple comparisons. and by the complementary PR/ROC comparisons in Supplementary Fig. 5. Under the baseline FPN setting, ViTDC showed a slight but reproducible advantage over ViT in threshold-dependent detection metrics as well as in curve-based evaluation. Taken together, these results suggest that DCMHA improved the ViT-based framework in a stable but non-dominant manner, with its clearest support appearing in detection-oriented metrics rather than in overlap-based mask metrics. FPN with eSE module To further improve stomatal segmentation performance, we incorporated the eSE module into the FPN to enhance feature representation. As shown in Table 2, introducing eSE consistently increased the mean values of mAP and AP50 across all tested backbones, and also improved AP75 for most of them. Repeated-run statistical analysis further confirmed that this effect was robust (Supplementary Fig. 1). In particular, the eSE-enhanced setting significantly improved mAP across all tested backbones, and the gains in AP50 and AP75 were also statistically supported for most backbone configurations after Holm correction. By contrast, the effect of eSE on overlap-based mask metrics such as mIoU and Dice was more limited, with statistical support observed mainly in the ViT-based setting. The gain was particularly evident for the ViT-based configurations, where mAP increased from 69.09 ± 0.18% to 71.96 ± 0.12% for ViT and from 70.36 ± 0.09% to 72.40 ± 0.09% for ViTDC. Notably, after introducing eSE, the gap between ViT and ViTDC became smaller, and the difference between the two ViT-based variants was no longer statistically clear for the primary detection-oriented metrics (Supplementary Fig. 3), suggesting that stronger multi-scale feature recalibration can partly compensate for the baseline difference between the two variants. Overall, the eSE-enhanced models formed the top-performing group in Table 2, with ConvNeXt + eSE achieving the highest mAP (72.91 ± 0.10%), while ViT + eSE and ViTDC + eSE showed similarly strong AP75 performance (84.60 ± 0.16% and 84.59 ± 0.19%, respectively). Beyond the primary metrics mAP, AP50, and AP75,Supplementary Fig. 1 and Supplementary Fig. 3 showed that the eSE module also improved PR-AUC, Precision, Recall, and F1 for most backbones, whereas gains in mIoU and Dice were smaller and more backbone-dependent. This pattern suggests that eSE mainly strengthened feature selection and prediction stability at the detection level, while its contribution to stricter overlap-based mask quality was more limited. In the ViT-based setting, however, the improvement extended to both detection-oriented and mask-quality-related metrics, indicating that channel-wise recalibration and multi-scale feature fusion were especially beneficial when combined with transformer-derived features. Complementary PR and ROC analyses (Supplementary Fig. 5) were broadly consistent with the ranking inferred from mAP/AP50/AP75, indicating that the observed module effects were not limited to a single decision threshold. This additional evidence strengthens the robustness of the repeated-run comparison across backbone and module settings. Comparison of pre-trained weight We selected IN-1 K as the default pre-trained initialization, under which the proposed framework achieved mAP, AP50, and AP75 values of 72.40 ± 0.09%, 91.94 ± 0.12%, and 84.73 ± 0.07%, respectively. To further assess the effect of initialization strategy, we compared three pre-training schemes: IN-1 K, IN-2 K, and MAE (IN-1 K). Among them, MAE (IN-1 K) yielded the highest mean performance, reaching 72.74 ± 0.20% for mAP, 91.99 ± 0.09% for AP50, and 85.91 ± 0.07% for AP75 (Table 3). Repeated-measures statistical analysis showed that the advantage of MAE (IN-1 K) was not statistically clear for mAP, whereas its improvement in AP75 was supported relative to both supervised initialization strategies. Its AP50 advantage was also more evident relative to IN-2 K than to IN-1 K (Supplementary Fig. 4Supplementary Fig. 4). These results suggest that self-supervised pre-training primarily improved the stricter localization- and segmentation-related metrics, rather than producing a uniform gain across all primary detection metrics. Table 3Effects of different pre-trained weights on ViTDC performancePre-trained weightmAPmask/%AP50mask/%AP75mask/%IN-1 K72.40 ± 0.0991.94 ± 0.1284.73 ± 0.07IN-2 K72.15 ± 0.1091.24 ± 0.0984.93 ± 0.17MAE (IN-1 K)72.74 ± 0.2091.99 ± 0.0985.91 ± 0.07To evaluate the effect of weight initialization on the proposed ViTDC framework, we compared three different pre-training strategies under identical experimental settings. IN-1 K and IN-2 K represent supervised pre-trained weights derived from ImageNet-1 K and ImageNet-22 K, respectively, whereas MAE (IN-1 K) represents self-supervised pre-trained weights obtained using the Masked Autoencoder (MAE) approach on ImageNet-1 K. Therefore, this table highlights the impact of different pre-training schemes on the stomatal detection performance of ViTDC. Statistical significance for the repeated-run comparison among pre-trained initialization strategies is provided in Supplementary Fig. 4. Complete multi-metric results for all compared backbones and settings are provided in Supplement Table 4 Effects of different pre-trained weights on ViTDC performance To evaluate the effect of weight initialization on the proposed ViTDC framework, we compared three different pre-training strategies under identical experimental settings. IN-1 K and IN-2 K represent supervised pre-trained weights derived from ImageNet-1 K and ImageNet-22 K, respectively, whereas MAE (IN-1 K) represents self-supervised pre-trained weights obtained using the Masked Autoencoder (MAE) approach on ImageNet-1 K. Therefore, this table highlights the impact of different pre-training schemes on the stomatal detection performance of ViTDC. Statistical significance for the repeated-run comparison among pre-trained initialization strategies is provided in Supplementary Fig. 4. Complete multi-metric results for all compared backbones and settings are provided in Supplement Table 4 This interpretation was further supported by the supplementary multi-metric comparison. As shown in Supplementary Fig. 4 and Supplement Table 4, MAE (IN-1 K) also achieved the best or near-best performance in mIoU and Dice, indicating that its main benefit lay in improving mask quality and stricter overlap-related performance, rather than broadly enhancing every evaluation dimension. Table 4Stomatal trait measurements of plants with different ploidy levels using Mask R-CNNImagesAverageLength(µm)AverageWidth(µm)NumbersAverageArea(µm2)AverageCircumference(µm)116.4812.3012169.2047.00215.3211.1512134.1743.37316.5712.4314161.7647.33424.7214.368278.7965.83525.6716.219326.8069.85625.7815.4411312.6169.19732.3426.435671.3094.85831.2124.314595.8890.17933.3825.676672.9696.06In this table, Images 1–3, 4–6, and 7–9 represent haploid, diploid, and tetraploid leaf samples, respectively. Based on the stomatal instances detected and segmented by Mask R-CNN, the average values of stomatal length, width, number, area, and circumference were calculated for each image. These results were used to compare stomatal morphological traits among plants with different ploidy levels Stomatal trait measurements of plants with different ploidy levels using Mask R-CNN In this table, Images 1–3, 4–6, and 7–9 represent haploid, diploid, and tetraploid leaf samples, respectively. Based on the stomatal instances detected and segmented by Mask R-CNN, the average values of stomatal length, width, number, area, and circumference were calculated for each image. These results were used to compare stomatal morphological traits among plants with different ploidy levels Stomatal trait measurement After the backbone comparison and module selection, the final ViTDC + eSE model was further trained for 300 epochs using the hyperparameters listed in Table 1. The training loss decreased to 0.065 (Fig. 8B), and the final mAP, AP50, and AP75 reached 72.52, 91.97, and 84.31, respectively (Fig. 8A). Subsequently, the trained model was applied to the test images. The original images were fed into the model to obtain predicted bounding boxes, masks, and confidence scores (Fig. 9A). The masks were then cropped according to the predicted box coordinates to obtain individual pore images (Fig. 9B) according to box coordinates and obtained the small pictures with pores (Fig. 9C). Finally, the boundary of each mask was fitted by the least-squares method to derive stomatal traits (Fig. 9D; Table 4). Workflow of ellipse fitting for stomatal trait extraction. A Predicted stomatal instances generated by Mask R-CNN. B Binary masks of the predicted stomata. C Cropped mask images for individual stomatal instances. D Ellipse fitting applied to each cropped mask, where 2a and 2b denote the major and minor axes of the fitted ellipse, respectively To further evaluate the consistency between automated and manual measurements, 100 images were randomly selected from the test dataset for agreement analysis. As shown in Fig. 10, the automated measurements showed good consistency with the manual measurements. The Bland–Altman plot showed a mean bias of 0.154, with the 95% limits of agreement ranging from − 0.148 to 0.455. In addition, the distribution of the differences was approximately normal (Shapiro–Wilk, p = 0.085), indicating that the automated measurements were generally consistent with the manual measurements, although a slight positive bias remained. Agreement analysis between automated inference and manual measurements of stomatal traits. a Scatter plot of inference values versus manual values, showing the line of equality and the fitted regression line. b Bland–Altman plot showing the difference between inference and manual values against their mean; the solid red line indicates the mean bias, and the dashed lines indicate the 95% limits of agreement. c Histogram and kernel density curve of the measurement differences. d Boxplot of the differences between inference and manual values. e Q–Q plot of the ordered differences, showing the approximate normality of the error distribution. f Empirical cumulative distribution of the differences compared with the theoretical normal distribution. Overall, the results indicate good agreement between automated and manual measurements, although a slight positive bias remains Preliminary cross-species validation on other cucurbitaceae plants Our model showed good performance on melon stomatal images, which motivated a preliminary cross-species evaluation on other Cucurbitaceae plants. Given the morphological similarity among stomata in these species ( Fig. 11 ), we applied the model to cucumber, watermelon, pumpkin, and loofah. In this preliminary experiment, the model achieved R² values of 0.89, 0.88, 0.84, and 0.86, respectively ( Table 5 ). However, because only 50–61 images were used for each species, these results should be interpreted as preliminary evidence of transferability rather than a statistically conclusive evaluation of generalization. Larger and more diverse cross-species datasets will be needed in future studies. Representative stomatal images of other Cucurbitaceae plants and the corresponding inference results. From left to right, the columns show watermelon, pumpkin, luffa, and cucumber. The upper panels present the original microscopic images, and the lower panels show the corresponding inference results generated by the proposed model. Scale bar = 7.5 μm Table 5Preliminary cross-species evaluation of stomatal traits on different Cucurbitaceae plantsCropsAverageLength(µm)AverageWidth(µm)NumbersAverageArea(µm2)AverageCircumference(µm) R 2 Cucumber27.2319.007.10406.3473.760.89Watermelon33.5325.009.32646.7292.910.88Pumpkin30.5121.118.13505.8582.420.84Loofah30.6325.004.56601.2287.830.86Mean-----0.86Note: Each species was evaluated using a limited sample set (50–61 images), and the results should therefore be interpreted as preliminary Preliminary cross-species evaluation of stomatal traits on different Cucurbitaceae plants Note: Each species was evaluated using a limited sample set (50–61 images), and the results should therefore be interpreted as preliminary Discussion I In this study, we developed a stomata-oriented Mask R-CNN framework by integrating a ViT backbone with DCMHA and an eSE-enhanced FPN [18–20]. Together with the ablation results in Table 2 and the repeated-run backbone comparisons, these results indicate that the two modules contributed unequally to the final performance. The more consistent gain came from the eSE-enhanced FPN, which improved the main detection metrics across all tested backbones and therefore appears to play the dominant role in strengthening feature representation for stomatal images. By contrast, DCMHA provided a more moderate but reproducible benefit within the baseline ViT-based framework, suggesting that adaptive interaction and dynamic composition across attention heads can still improve global contextual modeling. After introducing eSE, the gap between ViT and ViTDC became smaller, implying that feature representation and selection within the FPN may be a more important bottleneck for stomatal instance segmentation than attention redesign alone. Nevertheless, the combined ViTDC + eSE configuration remained among the top-performing settings and maintained strong AP75 performance, which is particularly relevant for downstream contour-based phenotyping. Supported by the ellipse-fitting workflow in Fig. 9 and the agreement analysis in Fig. 10, these findings further indicate that the improvement in segmentation accuracy translated into biologically meaningful gains in trait extraction rather than remaining only a detection-level advantage. Together with the methodological comparison in Supplementary Fig. 1 and Supplementary Fig. 2, these results suggest that the main contribution of the present study lies not in proposing a fundamentally new universal architecture, but in building a task-oriented framework that integrates global context modeling, instance-level segmentation, and downstream trait extraction for dicot stomatal phenotyping under I2-KI imaging conditions. This positioning is also consistent with recent reviews showing that stomatal deep-learning workflows still face challenges related to dataset heterogeneity, transferability, and variation in image acquisition conditions [6, 21], as well as with previous studies that identified cross-species generalization as a key performance issue [23, 24]. Although the overall performance was strong, the failure cases in Fig. 12 indicate that false positives and missed detections remain practical challenges. These errors are likely associated with the biological and imaging characteristics of the present dataset rather than with a complete lack of recognizable stomatal features. Cucurbit leaves commonly bear glandular and non-glandular trichomes, which can introduce local occlusion and irregular background interference around stomata [36, 37]. In addition, the I2-KI staining procedure used here mainly enhances starch-related contrast rather than directly delineating stomatal contours, so variations in staining uniformity, chloroplast condition, blur, and weak local contrast may reduce boundary clarity. This interpretation is consistent with earlier studies showing that image quality is a major determinant of stomatal recall and boundary estimation, and that blur affects morphology-related measurements more strongly than stomatal counting alone [15, 24, 38]. In this sense, the major challenge revealed by Fig. 12 is not simply detection failure, but the sensitivity of instance-level segmentation to subtle local degradation in biologically complex images. Representative failure cases in stomatal detection. A Example of false-positive detection, where the blue box indicates a non-stomatal region incorrectly identified as a stomatal object. B Example of missed detection, where the red boxes indicate stomata that were not detected by the model. Green boxes indicate correctly detected stomata with confidence scores. Scale bar = 7.5 μm Another notable aspect of this study is that the proposed detection framework was integrated with downstream ellipse fitting to support trait extraction rather than stomatal counting alone. As shown in Fig. 9; Table 4, the segmentation results enabled automated quantification of stomatal length, width, number, area, and circumference, and the agreement analysis in showed strong consistency with manual measurements. This is important because many existing stomatal pipelines focus primarily on detection and counting or rely on multi-stage post-processing workflows, in which cumulative errors may compromise phenotypic robustness. By contrast, the present framework provides a relatively direct path from instance segmentation to morphological quantification. In this sense, the study is closer to phenotype-oriented stomatal analysis while still retaining the practicality of a single segmentation backbone. Similar trends have been reported in recent hybrid pipelines, where the biological value of the framework lies not only in identifying stomata, but also in enabling reliable extraction of quantitative morphology traits [27, 29]. Several limitations should nevertheless be acknowledged. First, the dataset was collected under relatively consistent staining, imaging, and sample-preparation conditions, which may limit its representativeness beyond the current experimental setting. Although Table 5; Fig. 11 provide encouraging preliminary evidence of transferability, broader validation across more species, devices, and preparation protocols is still needed. Second, annotation uncertainty cannot be completely excluded. As shown in Fig. 2, the dataset was built using a semi-automated labeling workflow, and Fig. 7 shows that this iterative strategy substantially improved labeling efficiency and dataset construction. However, the present study did not include a separate quantitative analysis of corrected-label accuracy, labeling error rate, or inter-annotator agreement. Even with manual correction, minor inaccuracies may still remain in regions with blurred boundaries, trichome interference, or weak local contrast, and such errors may propagate into ellipse fitting and downstream trait quantification. Future work should therefore include dedicated validation of corrected labels, for example through double-annotator verification or evaluation against a manually established gold-standard subset. Third, the framework still entails non-negligible computational cost. According to the implementation details and Table 1, model training required two GeForce RTX 2080 Ti GPUs and a batch size of 2, indicating that the current implementation may be less convenient in resource-limited settings. Similar constraints have also been reported in related studies on stomatal detection under complex imaging conditions [39]. Taken together, these limitations define the scope of the present study rather than undermine its main findings. Under the current experimental conditions, the proposed framework still provides an effective solution for automated stomatal detection, segmentation, and phenotypic trait measurement in melon. Future work should focus on improving robustness, generalizability, and deployment efficiency while preserving the trait-oriented strengths of the current framework. From a data perspective, expanding the dataset to include more species, imaging conditions, and sample-preparation scenarios will be important for a stronger assessment of transferability and practical applicability [25, 40]. From a model perspective, subsequent optimization should continue to enhance small-object perception, boundary preservation, and multi-scale feature representation without relying solely on larger architectures. More efficient backbones and lightweight feature-fusion strategies may further improve usability in routine phenotyping environments while reducing computational cost [41, 42]. Such advances are expected not only to improve detection robustness under complex imaging conditions, but also to further stabilize the contour-based trait extraction process illustrated in Figs. 9 and 10, thereby supporting more reliable high-throughput stomatal phenotyping in routine applications. Supplementary Information Below is the link to the electronic supplementary material. Supplementary Material 1. Author contributions Huang Yao:​​ Methodology, Software, Writing - Original Draft. Yan LeLong: ​​ Methodology, Software, Writing - Original Draft. Yang Jiaxi:​​ Data Curation. Cheng Chunyan:​​ Writing - Review & Editing. Wang Yuhui:​​ Writing - Review & Editing. ​​ Li Ji:​​ Writing - Review & Editing. ​​ Lou Qunfeng:​​ Writing - Review & Editing. Qian Chuntao :​​ Conceptualization, Supervision, Writing - Review & Editing. Zhang Yongbing:​​ Conceptualization, Supervision, Writing - Review & Editing. All authors have read and approved the final version of the manuscript. Funding This work was supported by the Tianshan Elite Project [grant numbers 2023TSYCLJ0015]; the Fundamental Research Funds for the Central Universities [grant numbers KJYQ2024026, KJYQ2025022]; Lhasa Municipal Science and Technology Plan [grant numbers LSKJ202549]. Data availability Upon acceptance of this paper, the source code and database will be made publicly available at Github. Code availability The source code for model training and inference, including the implementation of the key modules, is publicly available at: https://github.com/huangyao110/qk_maskrcnn_trsv2.git. Declarations Ethics approval and consent to participate Not applicable. Consent for publication All authors have reviewed the final manuscript and consent to its publication. No individual person’s data are included that would require additional consent. 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. Yao Huang and Lelong Yan have contributed equally to this work. Contributor Information Yongbing Zhang, Email: hamimelon@xaas.ac.cn. Chuntao Qian, Email: chuntaoq@njau.edu.cn. References Associated Data Data Citations Supplementary Materials Supplementary Material 1. Data Availability Statement Upon acceptance of this paper, the source code and database will be made publicly available at Github. The source code for model training and inference, including the implementation of the key modules, is publicly available at: https://github.com/huangyao110/qk_maskrcnn_trsv2.git.