At a glance
A Benha University team compared five CNNs and two Vision Transformers on 976 thermal udder images from Egyptian dairy farms. DenseNet-121 led with 0.914 cross-validated AUC, but accuracy fell to 60% on an independent farm.
A thermal camera pointed at a cow's udder took a fraction of a second to produce each of the 976 images in a new Egyptian study. A fine-tuned deep learning model, DenseNet-121, learned to sort those images into two piles and caught nine out of every ten mastitis cases in testing.
Then the researchers carried the same trained model to a different farm and ran it on 85 cows it had never encountered. Accuracy fell to 60%. Cohen's kappa, a measure of agreement that corrects for chance, came out at 0.199, which is barely past guessing for a two-class problem.
That gap between 82.2% and 60.0% is the most useful thing in the paper, published in Veterinary Sciences by Alaa T. Elmaria, Elsayed Badr, Sobhy M. A. Sallam, Marwa F. A. Attia and Sara Sweidan of Benha University's Department of Artificial Intelligence.
A cheap test for an expensive disease
Mastitis, an inflammation of the udder usually triggered by bacteria, is the bill the dairy industry keeps paying. A 2024 economic simulation covering 183 milk-producing countries put total annual losses from 12 dairy cattle diseases at US$65 billion, with clinical mastitis accounting for roughly US$13 billion and subclinical mastitis another US$9 billion (Rasmussen and colleagues, Journal of Dairy Science). Subclinical cases are the sneaky ones. The cow looks fine, the milk looks fine, and the somatic cell count quietly climbs.
The standard pen-side check is the California Mastitis Test (CMT), in which a detergent reagent is mixed with milk from each quarter and the thickness of the resulting gel is scored by eye. It's cheap and fast, but it needs someone to squirt, squirt, swirl, read and record, cow after cow. Infrared thermography (IRT) offers something different: a camera that reads surface temperature from a metre away and never touches the animal. Inflamed quarters run hotter.
Reading a thermal image by eye is unreliable, though. Ambient temperature, fur, moisture, camera angle and the cow's own movement all shift the picture. That's where the Benha group's work sits: if a neural network can absorb those nuisance variations, a farmhand with a thermal camera becomes a screening device.
Seven architectures, one dataset, one recipe
The team took a thermal image archive built for an earlier companion study on the same animals and ran a proper bake-off. Five convolutional neural networks (CNNs), the image-recognition workhorses that learn by sliding small filters across a picture, went up against two Vision Transformers (ViTs), which chop an image into patches and let an attention mechanism decide which patches matter to which.
- CNNs: ResNet-50, DenseNet-121, EfficientNet-B0, MobileNetV2, Inception-V3
- Transformers: ViT-B/16, Swin-Tiny
All seven started from ImageNet-pretrained weights. Images were contrast-normalised with CLAHE, resized to 224 by 224 pixels, and split 684 for training, 146 for validation and 146 for testing, with a healthy-to-mastitic ratio of about 2.6 to 1. Every architecture got the same hyperparameters: a learning rate of 3 × 10⁻⁴, no warm-up, 20 epochs.
The labels came from CMT results at the cow level, meaning both left- and right-side images of a cow inherited a single verdict. Clinical and subclinical cases were pooled, and quarter-level diagnosis was not attempted. The authors are explicit that CMT reflects inflammation rather than a confirmed bacterial infection, so the models were learning to recognise an inflammatory response, not a pathogen.
To judge each model, they used two yardsticks: a held-out test set, and five-fold cross-validation grouped so that images from one cow stayed in one fold. That grouping is meant to stop a model from memorising an individual animal and calling it skill — a failure mode the authors point out is common in the thermal-imaging literature, where image-level or herd-level splits can inflate results through pseudoreplication.
Photo by Daniel Quiceno M on Unsplash
DenseNet-121 wins, and the transformers fall behind
DenseNet-121 led on both yardsticks. On the held-out set it reached 82.2% accuracy, an area under the curve (AUC) of 0.922, 90.0% sensitivity and 79.2% specificity. Under five-fold cross-validation its mean AUC was 0.914 ± 0.019.
| Model and test | Key result |
|---|---|
| DenseNet-121, held-out test set | 82.2% accuracy, AUC 0.922, 90.0% sensitivity, 79.2% specificity |
| DenseNet-121, five-fold cow-level cross-validation | Mean AUC 0.914 ± 0.019 |
| ViT-B/16, pooled out-of-fold | AUC 0.700 |
| Swin-Tiny, pooled out-of-fold | AUC 0.638 |
| DenseNet-121 on 85 cows at a different farm, no retraining | 60.0% accuracy, Cohen's kappa 0.199 |
Statistics matter more than the leaderboard here. DenseNet-121 was statistically indistinguishable from Inception-V3 on both tests (pooled difference in AUC of 0.012, Holm-adjusted DeLong p = 0.265). Against ResNet-50 the picture is murkier: significant under a DeLong test (p = 0.033) but not under the more conservative corrected resampled t-test (p = 0.116), which the authors describe as unresolved. What did survive every test was the broader claim — all five CNNs beat both transformers, and DenseNet-121 beat EfficientNet-B0, MobileNetV2 and both ViTs.
The transformers didn't just score lower; they wobbled. Sensitivity standard deviations across folds exceeded 0.34, meaning a single split could make Swin-Tiny look either respectable or broken. The authors are careful not to declare attention-based models unsuited to the task. They trained the transformers on a recipe tuned for much smaller networks, with no learning-rate warm-up or longer schedule, and say so plainly: transformers replace the built-in spatial priors of convolutions with learned attention, and learned attention needs a lot more data to get there. With fewer than a thousand images, the CNNs' head start held.
One comparison deserves its own line. The group's earlier pipeline, which froze an EfficientNetB3 feature extractor and handed the features to classical classifiers, scored 86.2% accuracy on a held-out split but 74.1% sensitivity. End-to-end fine-tuning dropped accuracy slightly to 82.2% and lifted sensitivity to 90.0%. For screening, that's the right trade. A missed case costs a quarter, a lactation, sometimes the cow. A false alarm costs a confirmatory test.
The trade-off shows up in precision, which sat around 0.66 at the default operating point: roughly one in three positive flags was a healthy cow. The paper's out-of-fold confusion matrix for DenseNet-121 covers all 976 images — 594 of 708 healthy images correctly cleared, 221 of 268 mastitic images caught, 47 missed. Negative predictive value is the strong suit, which is what a triage tool needs.
Checking the machine's reasons
Explainable AI is the part of this literature that often gets skipped. The team used Grad-CAM, which back-propagates a prediction through the network to produce a heat map of the image regions that pushed the answer one way or the other. Think of it as asking the model to circle its evidence.
Mostly it circled the udder. The authors report that heat patterns in the udder region partly drove predictions, which supports the biological plausibility of what the network latched onto. But they also note that attention was occasionally influenced by background regions — stall rails, flooring, whatever else sat in the frame. That single sentence is a caution for anyone planning to bolt a camera to a milking parlour wall. A model can learn the barn instead of the animal, and Grad-CAM is how you catch it.
A related limitation is baked into the image format. The archive stores rendered BMP palettes rather than calibrated radiometric matrices, and the palette may have been auto-scaled per capture. Emissivity settings, camera distance and angle, ambient temperature and humidity, time relative to milking, udder cleaning protocol and post-handling acclimatisation time were not recorded and could not be reconstructed. The authors describe their inputs as exploratory classification of rendered-palette images rather than calibrated temperature measurement. Some of what the model learned may reflect per-image contrast rather than absolute udder heat.
The second farm, and what broke
External validation is where most agricultural AI papers stop short, and this one didn't. The best model was applied without retraining to 85 cows at a different farm. Accuracy landed at 60.0% with a kappa of 0.199.
The authors attribute the drop to domain shift, the ordinary consequence of a model meeting cameras, lighting, animals and handling routines it wasn't trained on. They also flag a mechanical contributor: the external cohort went through the same rendered-BMP pipeline, so part of the fall may reflect cross-site palette scaling rather than a failure of the thermal signal itself.
Here's the finding that keeps the story alive. Within that same external cohort, somatic cell count was significantly higher in CMT-positive cows (p < 0.001, AUC 0.783). The biology travelled even when the model's accuracy didn't. Whatever the network had learned about heat still lined up with a recognised marker of inflammation on unfamiliar ground.
There's a stranger result buried in the discussion. DenseNet-121's predictions agreed with the group's earlier machine learning pipeline at a kappa of 0.647, but agreed with CMT itself at only 0.199. Two models built in very different ways converged on the same thermal signal, and that signal only partly overlapped with the cow-side reference test. The authors read this as evidence that surface temperature carries information that somatic cell counts and CMT scores don't fully capture. They also note the paired-measurement subsets ran from 77 to 85 animals, which is thin enough to warrant caution.
Photo by Carolien van Oijen on Unsplash
What the authors say they can't yet claim
The most consequential limitation is administrative. The preprocessing was designed to keep all images of a cow in the same fold, but the per-image identifier used for that grouping could not be checked against a ground-truth cow roster, because no acquisition logbook or metadata file linking images to animals existed for the archive. The results are therefore nominally, not verified, animal-level. Because each cow contributed a fixed pair of left- and right-side images, residual clustering within cows may have inflated precision. The team ran a design-effect correction across a range of plausible intraclass correlations: the CNN-over-transformer advantage and DenseNet-121's edge over EfficientNet-B0 and MobileNetV2 held, while the DenseNet-121 versus ResNet-50 comparison did not.
Other caveats stack up honestly. The dataset comes from a small number of farms in one region. The external cohort was a single centre of 85 cows, which establishes transportability to one new site rather than generalisable performance. The held-out results come from a single seed and a single split. Cow-level CMT labelling injects noise when only one quarter is inflamed, though the authors note that kind of noise would bias performance downward rather than flatter the model. Model attention was not constrained to an udder region of interest.
Where a 90% sensitivity tool actually fits
Not in the diagnosis slot. The paper positions these models as supportive screening: a camera flags a cow, and a recognised test confirms it. The threshold is adjustable, so a farm can dial sensitivity up or down depending on whether it fears missed cases or wasted confirmatory tests. That flexibility is the practical argument for the whole approach. A thermal camera and a phone can do the first pass without a lab, a reagent or a veterinarian on site, and the model's high negative predictive value means a clean flag is usually worth trusting.
For Egypt's dairy sector and similar settings, that arithmetic matters. Laboratory culture and somatic cell counting don't scale to continuous herd-wide surveillance, as the paper's introduction notes. A screening step that costs almost nothing per cow and shaves the number of animals needing a manual check is a different kind of intervention than a new diagnostic test.
What comes next is unglamorous and necessary. The authors call for domain adaptation and multi-farm validation before any deployment claim, and for recovering or reconstructing a verified cow identifier if the dataset is reused. They point toward quarter-level relabelling, attention constrained to the udder, and larger multicentre datasets that would give transformers a fair shot. Sweidan's group at Benha has already shown it will run the comparison rather than assume the fashionable architecture wins. The next paper worth reading from this line of work will be the one where 90% sensitivity survives the drive to a second farm.
- deep-learning
- explainable-ai
- dairy-science
- infrared-thermography
- veterinary-ai

