1. Introduction
Microbiology, biotechnology, and clinical diagnostics all include components focused on measuring microbial colonies. A common method to assess microbial growth is to measure bacteria by colony-forming units, which are also used to describe antibiotic susceptibility and contamination. Manual colony counting is tedious and traditionally relies on the observer to provide an accurate count, prompting the need to automate analysis. The initial methods automated colony enumeration by employing thresholding and morphological operators, often coupled with watershed segmentation. The approaches succeeded to a minimal extent and continued to fail due to sensitivity to noise, uneven illumination, and overlapping colonies [
1].
A significant advancement in the analysis of microbial colonies was the introduction of deep learning, especially for its ability to automate end-to-end analysis without hand-crafting features. Convolutional neural networks (CNNs) are the state of the art in segmentation of biomedical images, and, in general, the U-Net architecture and its variants have rendered segmentation in medical and biological imaging, as well as other imaging tasks, highly useful and efficient [
2]. U-Net extensions, such as U-Net++ and Attention U-Net, differ in how they represent features and in how they apply attention mechanisms (both spatial and channel) to enhance expressivity. Models like the Vision Transformer (ViT) and Swin-Unet are recent transformer-based models that can outperform purely CNN-based approaches on challenging computer vision problems, especially by modeling long-range dependencies in image data [
3,
4]. Despite these advantages, the scarcity of large, well-annotated datasets in microbiology will continue to hinder the advancement of these state-of-the-art models.
To address data sparsity, the creation of synthetic data and the development of novel augmentation strategies have emerged as key approaches. Frameworks based on augmentations from transformers and GANs have improved the generalization of artificial colony detection and are good solutions for small data with annotations. Other approaches have been successful in improving the detection of colonies from scarce data, such as a hybrid CNN-MLP network that outperforms standard CNN-based networks. Optimization methods and algorithms improve segmentation reliability. A swarm-optimized microbial colony counter showed that metaheuristic optimization improves deep learning models by tuning hyperparameters and stabilizing convergence. PSO and its derivatives, such as Quantum PSO and DE-PSO, have achieved excellent results in biomedical image segmentation, providing effective optimization across large regions of high-dimensional spaces. Accuracy is one part, but explainability and reliability are key for an automated system in a lab. Using the frameworks of Grad-CAM++, Integrated Gradients, and temperature-scaling uncertainty calibration, a visual explanation of predictions is provided, and their confidence is established. This boosts the confidence of automated colony analysis pipelines.
To address challenges in automated microbial colony analysis, we developed a framework that directly addresses these problems. Images of microbial colonies are typically prone to multiple challenges that elude traditional single-approach segmentation and counting methods. These challenges include colony overlap, uneven illumination, sensor noise, low boundary contrast, colony irregularities, and morphologies. Furthermore, these tend to change from laboratory to laboratory. The proposed framework addresses these challenges by adopting a modular, multi-strategy, integrated approach rather than the traditional, singular, pipeline-based, automated approach. Our approach integrates multiple strategies. In the first stage, variability in the quality of input images is reduced, and the effects of variable laboratory illumination are removed. Attention mechanisms and transformer bottleneck modules, swarm intelligence optimization, and post-processing refinement are used to enhance segmentation and improve counting confidence. Our approach is the first of its kind, a modular, integrated, multi-strategy approach that deals directly with the problems microbial colonies pose to segmentation and counting.
The innovation introduced by this study is a novel swarm-optimized hybrid attention–transformer framework designed for automated microbial colony segmentation and counting. Unlike CNN-based architectures, our solution can address overlapping colony segmentation and illumination variation. This architecture employs nested skip connections, advanced channel–spatial attention, and transformer global context reasoning. Further, in this framework, swarm intelligence optimizers such as Particle Swarm, Quantum-behaved PSO, and Differential Evolution–PSO aid network optimization for stable convergence and effective control in higher-dimensional search spaces. Further, segmentation and morphological enumeration accuracy are refined through the combination of post-processing techniques, including, but not limited to, morphological improvements, watershed segmentation, and graph-based segmentation and enumeration. In addition, to enhance transparency and practicality, the framework employs Grad-CAM++, Integrated Gradients, and trustworthiness calibration to control confidence. The suggested framework was validated through multiple experiments conducted on two benchmark datasets. Improvements in several metrics, including Dice score, Intersection over Union (IoU), and counting error, were observed. The framework has a straightforward solution to automated colony analysis and microbiological diagnostics.
The subsequent sections of this manuscript are as follows:
Section 2 discusses the literature and identifies the gaps this study attempts to address. The details of the proposed hybrid, explainable AI framework, and swarm intelligence optimization are outlined in
Section 3.
Section 4 discusses the experimental results and the assessment of the model’s performance, robustness, and interpretability.
Section 5 presents the conclusion, encapsulating the findings of this study and providing directions for future studies.
2. Literature Review
Breakthroughs in explainable deep learning and ensemble classification have impacted medical imaging, news categorization, and agricultural disease detection domains. In medicine, explainability has been improved by using XGrad-CAM to understand disease classification from medical images [
5] and by leveraging the interpretability of CNNs to analyze brain tumors [
6]. In the non-medical field, explainable systems and intelligent systems were applied to both text data and agricultural data. For example, the online news categorization task was supported by the X-News dataset [
7], which provides news articles; moreover, a multi-stage ensemble of neural networks was employed to classify wheat leaf disease [
8], confirming that deep learning in precision agriculture is useful. Overall, these works show that explainability, ensemble learning, and adaptation to the specific domain in question, which are the main avenues of modern AI, are becoming more and more relevant.
The advancement of biomedical segmentation has come from shifts from rule-based image processing to deep convolutional neural networks. Classical methods of processing, such as thresholding and watershed segmentation, require parameter tuning and will ultimately yield poor results for heterogeneous morphologies. Therefore, many segmentation techniques have come to rely on neural networks. Some of the earliest applications of convolutional neural network segmentation in the biomedical field included the segmentation of embryo nuclei and neuronal cell membranes in Electron Microscopy, as well as the detection of mitosis. This related work showed the benefits of using deep learning frameworks and related fields, such as end-to-end learning and feature learning, in place of hand-crafted features. In medical imaging, convolutional neural networks have been applied to histopathology and radiology workflows for segmentation problems, including breast cancer lesion segmentation, modeling mammographic lesions, and detecting sclerotic spine metastasis. This work demonstrated the benefits of using neural networks as a basis for segmentation.
The impact of explainable artificial intelligence and hybrid deep learning on biomedical image analysis and medical decision-support systems cannot be overstated. With explainability-based frameworks, such as XGrad-CAM, we have begun to understand the pivotal role played by interpretable visualizations in disease classification and the enhancement of clinical trust in medical imaging [
9,
10]. The further development of hybrid attention-guided architectures that integrate convolutional learning and advanced contextual modeling has been shown to improve the robustness of segmentation and classification in challenging biomedical imaging [
11,
12]. Additionally, multimodal transformer-based frameworks have been shown to be highly capable of synthesizing disparate clinical and imaging data within a cohesive diagnostic framework [
13]. Outside the realm of biomedical imaging, the focus on advanced intelligent decision-support systems and AI-based optimization methods have underscored the importance of developing robust, explainable, and cost-effective machine learning systems to address real-world challenges [
14,
15]. These trends combined provide impetus for the incorporation of explainability, hybrid attention mechanisms, transformer-based contextual learning, and optimization-based refinement in the proposed framework for segmentation and counting of microbial colonies.
Encoder–decoder architectures became key to biomedical segmentation. U-Net [
16] added skip connections that combine semantic with spatial information and serve as a baseline for dense biomedical segmentation. Many improvements on segmentation for dense predictions in microscopy and histopathology concentrated on enhancing the network’s capacity and stability during training. Many segmentation-focused deep networks were based on fast-scanning CNNs. Other works on region-based CNN segmentation focused on breast histopathology [
17] and mammography lesion segmentation [
18], and further radiological tasks [
19] observed the same trend and domain generality. All these works show the movement from classical watershed-based segmentation algorithms to CNN-based segmentation frameworks. Modern segmentation is based on robust frameworks that leverage attention mechanisms, multi-scale feature extraction, and transformers.
There has been growing interest in the automated analysis of microbial colonies across fields such as microbiology, clinical diagnostics, and biotechnology. Previous segmentation methods relied on manual counting with basic image processing techniques such as binarization, edge detection, and the watershed algorithm. Even though these methods could segment colonies in controlled lab environments, they were not robust or scalable due to sensitivity to noise and varying illumination, as well as problems with closely spaced or touching colonies [
1]. To overcome these problems, deep learning has been used to learn more robust features for an end-to-end solution for colony detection and counting [
20].
The advancement of self-supervised and few-shot learning has significantly impacted biomedical image segmentation, particularly in settings with limited annotated datasets. Self-supervised learning uses pretext tasks and unannotated biomedical images to construct better representations, improve segmentation performance, and lessen reliance on annotated data [
21,
22]. Likewise, few-shot segmentation leverages metric learning, prototypes, and transformer-based context adaptation to generalize segmentation to an instance from a limited number of annotated examples [
23,
24]. These methods enhance the analysis of biomedical images and segmentation of annotation data, which is often expensive to capture at the pixel level. Few-shot and low-data learning can be applied to microbial colony analysis. This is due to the lack of large-scale, annotated microbial colony datasets and to inconsistent imaging conditions across laboratories. These methods, especially when paired with hybrid attention–transformer segmentation frameworks to bolster performance, are good approaches for maximizing data utility and improving segmentation in automated microbiology analysis systems.
The use of convolutional neural networks in microbiological imaging has made automated colony counting more precise and consistent than manual colony counting [
1]. For biomedical imaging and segmentation of microbial colonies, CNNs like U-Net have become the go-to due to their balance between capturing details and maintaining overall context in the data [
2]. Advancements to U-Net, such as U-Net++ and Attention U-Net, added nested skip connections and attention mechanisms, respectively, improving the model’s ability to focus on and propagate critical features to the output. More recently, models like Swin-Unet and transformer models introduced to the imaging domain, such as the ViTs, have seen success in both medical and biological imaging due to their ability to model long-range dependencies [
3,
4]. However, these models are data hungry, and in the field of microbiology, data scarcity is a common problem.
To address the problem of scarce data, synthetic data augmentation has emerged. A number of methodologies, such as copy–paste augmentation, GANs, and the Segment Anything Model (SAM), have proven effective for generating realistic agar plate images with colony generation, thereby significantly improving model generalization [
25]. The methods highlighted the need for additional data in research on microbial colonies. Colony segmentation methodologies have also seen a significant advancement with a focus on optimization.
A new method in a study proposed a swarm-optimized microbial colony counter. This new method combines SegNet with a blob counter and uses swarm intelligence optimizers, showing several advantages over currently used methods [
26]. Particle Swarm Optimization (PSO), as well as its variants, Quantum-behaved PSO (QPSO) and Differential Evolution-based PSO (DE-PSO), have been used extensively for hyperparameter tuning and convergence adjustment in biomedical image segmentation [
27,
28]. Given their complexity, these types of optimizations are beneficial in the low-data domain, where networks need to be searched over a high-dimensional space.
Alongside accuracy, the other significant features of biomedical AI are interpretability and explainability. Automated colony analysis systems have become more reliable for users as a result of these improvements. Specifically, Grad-CAM and its derivatives, Grad-CAM++ and Integrated Gradients, as well as well-calibrated, temperature-scaled models, all improve confidence in automated systems by aligning predicted confidence with actual outcomes and minimizing overconfident errors [
29]. Other recognized improvements in colony detection with small-sample datasets have utilized CNN-MLP architectural hybrids. These hybrids have achieved results beyond those with traditional CNN baselines, and represent a trend towards systems that integrate the inductive biases of CNNs with the global reasoning capabilities of MLPs or Transformers.
While developing swarm-optimized microbial colony counters and hybrid CNN-based segmentation frameworks has attracted attention in the literature, the frameworks proposed here differ fundamentally from existing approaches in both their count architectures and their functional integration. Microbial colony analysis frameworks designed with swarm optimization techniques typically build on classical encoder–decoder architectures (e.g., SegNet) or standard CNN pipelines. In these swarm-optimized frameworks, swarm intelligence techniques are mainly applied for hyperparameter tuning and weight optimization. Global context modeling through transformers, attention-based feature refinement, uncertainty quantification, and post-calibration interpretability are not addressed in these swarm-optimized systems; as a result, they lack robustness and applicability in unforeseen laboratory conditions, such as varying illumination or densely overlapping colonies.
The same sentiment applies to recent hybrid CNN–transformer frameworks, which have achieved substantial performance gains in biomedical image segmentation by combining modular local feature extraction with a transformer architecture to capture long-range dependencies. Once again, such frameworks leave the majority of issues in microbial imaging unaddressed, including extreme colony clustering, weak and less-defined colonies, agar artifacts, and cross-domain laboratory variability. Lack of swarm intelligence optimization, explainability, and a combination of graph-based refinement and uncertainty calibration are other limitations of the existing hybrid frameworks.
The proposed framework integrates a swarm-optimized, explainable attention–transformer architecture, making it a first for microbial colony segmentation and counting. Nested encoder–decoder representations, channel-spatial attention refinement, Swin Transformer bottleneck representations, PSO/QPSO/DE-PSO optimization, watershed and graph-based colony separation, Grad-CAM++ and Integrated Gradients explainability, Monte Carlo uncertainty estimation, temperature scaling, and cross-dataset robustness validation are fully integrated into an end-to-end modeling approach. The integrated approach described in this framework achieves better segmentation accuracy, colony separation, and robustness across diverse laboratory conditions, and greater explainability than current swarm-optimized or hybrid CNN-transformer frameworks.
While exploring individual strategies such as CNN-based segmentation, transformer architectures, swarm optimization, augmentation, or explainability, prior work focused on specific isolated aspects of microbial colony analysis. Typical segmentation approaches may encounter difficulties handling overlap among colonies when illumination varies. Transformer-based approaches may lack robust optimization in the presence of limited data, whereas optimization-based approaches may rely on relatively simple segmentation backbones with explainability or uncertainty modeling. Unlike the previously mentioned work, the proposed framework offers a problem-driven hybridization approach. This involves integrating colony counting and segmentation with preprocessing, attention refinement, transformer contextual modeling, swarm intelligence optimization, and post-processing, all performed with meticulous attention to detail and adjustment.
4. Results and Discussion
The swarm-optimized hybrid attention–transformer framework was comprehensively analyzed using qualitative and quantitative methods to evaluate segmentation, counting, optimization, and interpretation. The results are organized in a progressive manner, beginning with quantitative approaches using advanced metrics alongside conventional benchmarks, followed by ablation studies that reveal the contributions of the hybrid backbone, swarm optimization, and post-processing improvements. The frameworks are then tested on numerous datasets to verify their versatility in diverse imaging scenarios. The results are then analyzed to present qualitative arrays of segmentation masks, interpretability heatmaps, and colony separation of densely clustered segmentation outputs. This analysis shows the excellent performance of the proposed approach and highlights its simplicity of use and interpretability in both laboratory and clinical settings.
4.1. Dataset Description
To validate the proposed framework, we adopted two publicly available microbial colony datasets. The first is the Kaggle Microbial Colony Recognition Dataset. This dataset contains colonies that differ in size, arrangement, illumination, and abundance, as well as in agar plate diversity. The second dataset is the Figshare Circular Bacteria Colony Dataset. This dataset, which contains irregularly growing colonies, is much more complicated because the colonies have low contrast, high overlap, and different backgrounds. Both datasets (and the images within them) exhibit different imaging conditions and contrast, with highly distinct visual distributions, including colonies that overlap and contain different morphological features. The proposed framework was validated using cross-dataset testing, with particular attention paid to separating the training and test datasets, to assess its robustness and ability to generalize to the challenge of imaging complex, diverse microbial colonies.
Training Dataset: Kaggle Microbial Colony Recognition Dataset: The Kaggle dataset [
30] contains microbial colony images with bounding-box annotations and recognition labels. For segmentation, bounding-box annotations were used to construct approximate region masks, which were then improved through a set of preprocessing steps. This dataset is the primary training dataset and teaches the model colony localization and morphology.
Testing Dataset: Circular Bacteria Colony Dataset (Figshare): The Circular Bacteria Colony Dataset from Figshare [
31] contains pixel-level annotations for colonies of varying densities and morphologies. This dataset is used only for testing, with no overlap during training, thus allowing an unbiased assessment of the model’s generalization capability across different experimental settings.
The datasets used in this work contain many hundreds of culture plate images and thousands of microbial colonies; they also include a wide variety of colony structures and distributions, as well as images showing different appearances for microbial colonies. As such, the datasets contain colonies that are arranged sparsely, densely, and/or overlapping, colonies showing irregular growth, colonies with low contrast, and colonies of all sizes. These images also reflect the variability in the field of microbiology, including background, agar, illumination, reflections, and the conditions under which they are taken.
The different annotation methods across datasets reflect this variability. In the Microbial Colony Recognition Dataset from Kaggle, bounding boxes are provided for colonies. These bounding boxes were used to create colony segmentation masks, which were refined using a processor and morphological techniques to improve colony boundary localization and segmentation quality. On the other hand, in the Figshare Circular Bacteria Colony Dataset, colonies are annotated to the pixel level. This allows for a more accurate assessment of segmentation and colony separation quality. To avoid bias in the datasets, the training and testing datasets were kept completely independent with no overlap, and the evaluation strategy used various colony densities and morphologies to measure the robustness of the methods to variable conditions. In addition, the augmentation strategy involved creating a balanced representation of colonies, accounting for variations in appearance, scale, and illumination, as well as for arrangements across the different phases of the training process.
Using this dual-dataset strategy, the model is assessed on data not used during training, thereby minimizing overfitting and demonstrating the strategy’s soundness. Parts of the Microbial Colony Recognition Dataset and Bacterial Colony Detection Dataset used in this process are presented in
Figure 7. These datasets demonstrate varying levels of colony density, color, and growth conditions for evaluation.
The datasets reflect laboratory situations in microbiology. Microbial colonies can be irregular or neat, and their edges can be clear or fuzzy. Colonies can be high- or low-contrast, with either dense or sparse growth. Datasets can include images of agar plates with varying backgrounds and textures, as well as different colors. Imaging can lead to noise, shadows, and low-contrast regions. Due to the variety of colony appearances across different laboratory and environmental conditions, the cross-dataset strategy was designed to evaluate its applicability in the real world. Training was performed on the Microbial Colony Recognition Dataset, and testing was performed on the independent Circular Bacteria Colony Dataset. This was designed to capture a more rigorous evaluation of the flexible framework, beyond the scope of one dataset, imaging, and colony characteristics, and to be flexible for diverse laboratories with different colony and agar appearances.
The datasets used are independent imaging distributions that were collected using different experimental and collection protocols. These datasets, which are highly heterogeneous in colony morphology, colony density, and several other features, can help capture the variability found in most microbiological laboratories. Although the datasets used come from different sources, they include images of laboratories having very sparse and very dense colonies, as well as very light, very overlapping, and very close colonies, with varying growth rates and in varying lighting conditions. The method was also evaluated in a formal cross-dataset validation. In this case, the Kaggle Microbial Colony Recognition Dataset was used for training, and the independent Figshare Circular Bacteria Colony Dataset for testing, with no overlap between the training and testing samples. In this cross-domain context, the framework attained a Dice score of 94.2%, an IoU of 88.6%, and a mean absolute counting error of 2.7. These outcomes are very promising and attest to the framework’s strength and generalization across largely divergent imaging distributions and conditions.
4.2. Experimental Setup
All experiments were conducted to assess the effectiveness and robustness of the proposed swarm-optimized microbial colony counting framework. The system was implemented in Python (PyTorch 3.10) with MATLAB 2024b-based preprocessing modules, and run on an Ubuntu 22.04 workstation with an NVIDIA RTX A6000 GPU (12 GB VRAM), Intel Xeon Silver 4314 CPU, and 32 GB RAM. Images were resized to , normalized, and augmented using rotations, flips, brightness changes, and elastic deformations. Models were trained with Adam (), batch size 16, and up to 100 epochs with early stopping, using a composite Dice and boundary-aware loss. Swarm intelligence optimizers—PSO (), QPSO ( decreasing from 0.5), and DE–PSO ()—were employed for 50 iterations each to refine hyperparameters and enhance segmentation performance.
The proposed framework and baseline models went through the same end-to-end experimental procedures. The same preprocessing steps were taken to include denoising, illumination normalization, augmentation, and smoothing, which were applied to all the training data for all baseline models before the optimization of segmentation networks. The segmentation network was optimized and trained using PSO, QPSO, and DE–PSO to improve convergence stability and segmentation. After segmentation prediction, a series of post-processing steps, including morphological refinement, watershed separation, and graph-based adjustment, were performed to improve the quality of the final colony count, followed by evaluation of several metrics. For the quantitative assessments, the Dice score, IoU, and MAE were calculated for the test data.
To promote fairness and reproducibility in our evaluation, each independent experimental run required that the associated model be completely retrained from scratch, rather than leveraging previously trained model weights. Therefore, for each run, the proposed framework and all baseline models were retrained under the same training, augmentation, and optimization conditions, using the Kaggle Microbial Colony Recognition Dataset, and subsequently tested on the independent Figshare Circular Bacteria Colony Dataset. For each experimental run and benchmark test, weights were neither shared nor reused. Independent training and testing across three complete cycles were performed to report results with improved statistical confidence, and the results included the mean and standard deviation.
The framework incurs a higher training cost than standard encoder–decoder frameworks because of the integration of hybrid attention modules, transformer bottlenecks, and swarm intelligence optimization. Specifically, swarm intelligence-based optimization adds iterative parameter searches, further complicating and increasing training costs. However, this additional computational cost primarily occurs during the offline training stage. In contrast, the framework is computationally feasible for both practical laboratory applications in colony counting and for inference. The training approach in the framework is centered on strengthening segmentation robustness and enhancing colony separation quality, while also improving generalization across diverse microbiological imaging scenarios.
4.3. Baseline Methods
To evaluate the effectiveness of the proposed swarm-optimized microbial colony counting framework, we compared it with several state-of-the-art deep learning architectures widely used in biomedical image segmentation. The selected baselines were based on their extensive literature prevalence, their flexibility in modeling microbial colonies, and included U-Net [
32], U-Net++ [
33], Attention U-Net [
34], and Swin-Unet [
35]. Due to its encoder–decoder architecture and Skip connections, U-Net remains an important U-Net benchmark for combining semantics with spatial information, and U-Net++ builds upon this with nested Skip pathways and dense connections that narrow the semantic gap and improve boundary definition. Attention U-Net employs U-Net-based attention mechanisms to target colony-relevant areas while ignoring extraneous background features, thereby addressing the problem of varying illumination, a significant issue in imaging colonies. Swin-Unet incorporates hierarchical Swin Transformers with window-based self-attention, thereby capturing, alongside the desired architecture, local and global context, making it suitable for the wide variety of spatial arrangements of colonies. All baseline models were uniformly trained on the Kaggle Microbial Colony Recognition dataset with the same parameters, post-processing, data sample size restrictions (
), and data augmentation (including contrast stretching, flips, and brightness), and they were evaluated on the Figshare Circular Bacteria Colony dataset. Moreover, normalized training used the Adam optimizer with a learning rate of
and early stopping. Testing used the Dice coefficient, Intersection over Union (IoU), and mean absolute error (MAE) for colony counting. All proposed methods in
Table 1 bested all raw U-Net baselines in segmentation, counting, and the other tasks.
4.4. Quantitative Results
Table 2 summarizes the segmentation results of the proposed framework and the established baselines. Among the benchmark models, Swin-Unet, with a 91.4% Dice score and 84.7% IoU, outperformed U-Net and its enhanced versions, namely U-Net++ and Attention U-Net. While U-Net++ exhibited better boundary preservation than the original U-Net and the Attention U-Net reduced background interference, U-Net++ and Attention U-Net still struggled with highly overlapping colonies, leading to higher MAE. The proposed method performed better across all metrics, achieving a Dice score of 94.2% and an IoU of 88.6%, with improvements of almost 3% and 4% in Dice and IoU, respectively, compared to the closest baseline. Further, the counting error, represented by MAE, improved from 3.9 colonies with Swin-Unet to 2.7 colonies, a 30% improvement.
In
Table 2, our framework demonstrates a significant advancement over the baseline in segmentation and counting tasks. Compared to Swin-Unet, the improvement in the Dice score was 3%, and in the IoU, 4%. Also, compared to the best baseline model, the counting error, measured by MAE, improved by 30%. The use of hybrid attention modules, transformer global context modeling, and swarm-based parameter optimization demonstrates complementary effects, as illustrated by the results. To further validate the enhancements, a statistical comparison was performed, and the results are presented in
Table 3. A paired
t-test was performed for each baseline and for each measurement. All
p-values were lower than 0.01, thus validating the statistical significance of the enhancements.
To evaluate the statistical significance of the performance improvements, each baseline model was compared with the proposed method in repeated experiments using a paired t-test. The paired method was preferred because a direct metric comparison between the proposed method and the baseline models was possible, as both methods were subjected to the same training, augmentation, and testing procedures, using the same datasets and evaluation protocol. For segmentation, the statistical tests were conducted on the repeated experiments’ and validation’s Dice and IoU scores. For colony-count analysis, the tests were conducted on the MAE score. The experiments were conducted independently three times, and the resulting score distributions were analyzed for significance. The significance criterion (p < 0.01) was selected. Improvements below this threshold were assumed to reflect random experimental variance and were not statistically significant.
The current framework’s computational burden combines hybrid attention–transformer segmentation, swarm intelligence optimization, uncertainty estimation, and graph refinement within cross-dataset evaluation. While exhaustive stochastic analysis benefits from large independent runs, it would result in high costs. Traditional segmentation frameworks allow independent runs due to fully implemented, time-efficient backward passes; however, each independent run in this research required retraining the framework and a full cycle of the iterative PSO, QPSO, and DE-PSO optimizations. As a practical compromise between time and statistical verifiability, three independent training and evaluation cycles were utilized.
It is noteworthy that the limited number of runs demonstrates consistently low standard deviations across Dice, IoU, and MAE metrics. This indicates stable convergence and reliably repeatable performance. Conducted independently, and on different evaluation samples, paired statistical significance tests were performed to assess if the improvements over the baselines were due to improvements in methods and not random fluctuations due to the initialization. The upcoming larger-scale studies are expected to enable an extensive, repeated-run analysis of stochastic processes over longer time horizons.
The mean absolute error of 2.7 colonies indicates that this framework can be used for sufficiently reliable colony quantification even under difficult imaging conditions, including highly overlapping colonies, oddly shaped colonies, and inconsistent lighting. Typical microbiology workflows often reveal discrepancies in colony counts after manual inspection, due to ambiguous colony boundaries and clustered growth. Given the challenges posed by the datasets, this error rate is low and demonstrates that this framework can yield automated, consistent colony counts. This solution also minimizes the time and effort required to manually count colonies while removing the subjective interpretation boundaries inherent to manual counting.
4.5. Qualitative Results
To further demonstrate the proposed framework’s capabilities, qualitative examples from the Bacterial Colony Detection Dataset and the Microbial Colony Recognition Dataset are provided. Example outputs are given in
Figure 8 and
Figure 9. In addition to the original images and ground-truth masks generated from bounding-box annotations, we provide segmented masks from optimized watershed post-processing, Grad-CAM++, and saliency overlay interpretability masks.
In
Figure 8, the Bacterial Colony Detection Dataset, which contains samples with severe background clutter containing multiple colonies that overlap at different scales, shows the proposed framework’s ability to segment colonies using a refined watershed approach to post-process segmentation with a level of interpretability that is relevant to a laboratory setting and consistently separates touching colonies. This is further supported by Grad-CAM++ heatmaps, which confirm that the network focuses on regions of interest within the colonies.
The same can be said for results on the Microbial Colony Recognition Dataset (
Figure 9). The framework seems quite robust to variations in colony density and plate illumination conditions. The predicted masks closely match the ground truth. The attention-based backbone, combined with swarm-based optimization, enables the model to generalize well to even low-contrast and faintly bordered colonies. The explainability maps show that the model is focusing on the center and edges of the colonies, which aligns with the experts’ intuition, thereby increasing confidence in fully automated predictions.
4.6. Ablation Studies
To analyze the effect of each component within the proposed framework, additional ablation tests were conducted by allowing each module to run in turn, while keeping the training and testing procedures the same. This analysis specifically aims to evaluate the effects of the following: preprocessing enhancement, attention-based feature refinement, transformer-based global context modeling, swarm-based optimization, and post-processing refinement. The effects of each were evaluated using the Dice score, Intersection over Union (IoU), and mean absolute error (MAE), which were used to quantify segmentation and counting performance and to evaluate the effect of each component on colony-counting performance.
4.6.1. Impact of Segmentation Backbone
The first ablation compares the baseline SegNet against the proposed hybrid attention–transformer backbone (HAT-Backbone). As shown in
Table 4, the hybrid architecture yields significant gains in Dice and IoU, demonstrating the importance of attention refinement and transformer-based global context modeling.
Table 5 presents the results of the ablation analysis, where it is evident that all the proposed elements of the framework positively impact the overall framework performance. The first step of the framework (preprocessing) introduced robustness against illumination changes and background noise, and helped accommodate low-contrast colonies. This also benefited the initial segmentation step. After that, attention modules were added, as they helped focus on colonies and suppress background noise, further strengthening discriminative learning. The addition of transformer bottleneck blocks also helped, as they were effective at modeling long-range dependencies and especially at addressing the challenge of separating overlapping, densely distributed colonies. The addition of swarm-based optimization (PSO, QPSO, and DE–PSO) improved convergence and optimization, resulting in better generalization across datasets. Lastly, the addition of post-processing, including watershed and graph-based refinement, greatly reduced counting errors caused by touching colonies and improved segmentation quality.
4.6.2. Effect of Swarm-Based Optimization
The results of our optimization strategy ablation studies are shown in
Table 6. The baseline model, which excludes swarm-based optimization, reports a Dice score of 90.4%, an IoU of 83.1%, and an MAE of 4.8 colonies. These results show the challenges that traditional gradient-based training methods face when dealing with dense/or overlapping colonies. The results show improvements across all three metrics when a traditional Particle Swarm Optimizer (PSO) is employed. The Dice score moves to 92.1%, the IoU score moves to 85.4%, and the MAE reduces to 3.6. This shows the strength of a swarm search method in optimizing model hyperparameters and model weights. The MAE score improves to 3.2, and the Dice and IoU scores improve to 93.0% and 86.5%, respectively, when a Quantum-behaved PSO (QPSO) is used, illustrating the trade-off benefit of a swarm-based optimization approach. Using our Differential Evolution–PSO (DE-PSO) variant, the best scores were achieved with a Dice score of 94.2%, an IoU score of 88.6%, and an MAE of 2.7 colonies. The results presented in this table demonstrate significant improvements in swarm-based optimization for segmentation and reliable colony counting, with DE-PSO clearly dominating the other methods.
4.6.3. Role of Post-Processing
Table 7 shows segmentation and counting performance for various post-processing implementations. When post-processing modules are disabled, our model achieves Dice scores and IoUs of 92.8% and 85.9%, respectively, with an MAE of 4.5 colonies. These numbers indicate relatively high segmentation performance, but the MAE suggests potential difficulty in counting densely clustered colonies. Further, the combination of morphological post-processing, watershed separation, and Graph Attention-based refinement (GAT) leads to an improved performance. A Dice score of 94.2%, an IoU of 88.6%, and an improved MAE of 2.7 colonies show the significant impact post-processing has on improving segmentation of boundaries, separation of touching colonies, and decreasing false collisions of colonies in dense clusters. The combination of Morphology, Watershed, and GAT post-processing ensures accurate segmentation maps and robust colony counting in complex microbial images.
4.6.4. Effect of Explainability and Calibration
Table 8 evaluates the impact of the explainability and calibration modules in the proposed framework. As anticipated, the addition of these modules does not affect raw segmentation and counting results, as Dice, IoU, and MAE remain unchanged compared to the configuration that excludes them. This is expected and intentional for these components. Explainability methods like Grad-CAM++ and Integrated Gradients do not improve pixel-level accuracy. Instead, these methods create visual attributions by marking regions of a visual field that primarily drive a given prediction. This increases explainability for the end-user. The explainability component is achieved through temperature scaling as the calibration module. As a result, confidence scores are more appropriately and accurately calibrated, with less overconfidence in erroneous or doubtful classifications. Though there is no change in Dice or IoU, these changes are necessary and important for building confidence in the framework. They allow domain experts to justify their decisions and to use calibrated confidence scores in a real laboratory setting. Explainability and calibration do not impede the quantitative performance of the framework, and significantly increase its trustworthiness and interpretability.
4.6.5. Cross-Dataset Validation
To assess the generalization capacity of the proposed framework beyond the original dataset, we employed cross-dataset evaluation and trained the model on the Kaggle Microbial Colony Recognition dataset, using the Circular Bacteria Colony dataset available on Figshare as the test set. This scenario is more difficult because the training and test datasets are obtained under different experimental settings, colony morphologies, and imaging protocols. The results in
Table 9 show that the proposed method achieves a Dice score of 91.7%, an IoU of 84.2%, and a mean absolute error (MAE) of 3.4 colonies, demonstrating that it achieves excellent performance on different datasets. In comparison, U-Net and Swin-Unet, as baseline approaches, show a significant performance drop in a cross-domain scenario, with a 5–7% drop in the Dice score. The integration of a hybrid attention–transformer backbone, swarm-based optimization, and newly proposed post-processing techniques yields a flexible and robust framework with built-in protections against a wide range of data distributions. This flexibility shows that the model is not overfit to a particular dataset and can generalize to several laboratory-based, real-world use cases, in which a range of imaging techniques will almost certainly be employed.
4.7. Discussion
Examining the experimental results allows us to identify the advantages, disadvantages, and overarching impact of the proposed framework. The main advantage of the framework is its ability to maintain a high degree of accuracy when placing boundaries in problematic edge cases, such as those with varying illumination conditions and multiple, potentially overlapping colonies. Due to its hybrid attention–transformer backbone and swarm-based optimization, this framework is, by design, more resilient across various datasets. The robustness of the framework is improved with explainability modules such as Grad-CAM++ and Integrated Gradients, and the combination of uncertainty quantification and calibration methodologies provides greater interpretability and transparency, thereby increasing the likelihood of adoption in the lab. This framework also has disadvantages that must be considered. The opacity of the framework as a case example means that pixel-level annotations are required for every training iteration, thereby limiting scalability to fields with abundant, low-cost data-collection resources. The computational burden imposed by transformers means this framework cannot be implemented in low-resource settings without a GPU.
The explainability and uncertainty modules allow lab staff to see the model’s focus and confidence levels, reducing reliance on automation. This supports the human-in-the-loop model and increases confidence in it across clinical and research settings. Future work on this can develop multimodal imaging frameworks to capture colony growth using combined techniques, such as hyperspectral and time-lapse imaging. This can be merged with active learning, reducing reliance on fully manually annotated data. This combo can also speed up the creation of training datasets. This framework can also be adapted to support colony-counting model work on small mobile devices. This would enable even more rapid, real-time colony counting in remote locations with limited resources.