#26409·ultralytics

save_json and save_txt val masks shrink on images larger than imgsz because scale_preds truncates the rescaled mask with .byte()

Author: Nicholas022400701Created Sep 28, 2026Updated Sep 28, 2026
Labelsbugsegment

Search before asking

  • I have searched the Ultralytics YOLO issues and discussions and found no similar bug report.

Ultralytics YOLO Component

Val

Bug

With save_json=True or save_txt=True, SegmentationValidator uses process_mask_native, so predn["masks"] are binary 0/1 masks at the network input size. SegmentationValidator.scale_preds (ultralytics/models/yolo/segment/val.py L300-L307) then rescales them to the original image with

python
"masks": ops.scale_masks(predn["masks"][None], pbatch["ori_shape"], ratio_pad=pbatch["ratio_pad"])[0].byte(),

scale_masks interpolates bilinearly. When the original image is larger than the network input, every object edge of the rescaled mask has fractional values, and .byte() truncates all of them to 0: only pixels that interpolate to exactly 1.0 survive. So every mask written to predictions.json and every save_txt polygon is smaller than what the network predicted, and small objects lose the most. Images that are smaller than or equal to the network input are not affected (COCO val2017 images are at most 640 px on the long side), which is probably why this went unnoticed.

A binary square rescaled from a 640x640 network input to a 1080x1920 image (gain 1/3, script below):

network pixels written by .byte() with a 0.5 threshold exact 3x area
4x4 100 140 144
10x10 784 896 900
30x30 7744 8096 8100

Real data: yolo26n-seg val at imgsz=640 with save_json=True, save_txt=True on coco8-seg with every image upscaled 2x (labels unchanged). All 543 predicted masks in predictions.json are smaller than with a 0.5 threshold: area ratio mean 0.928, median 0.939, min 0.390, and mean 0.861 for the 67 masks under 1024 px. The total mask area is 2.9% lower over all predictions and 1.4% lower over the 10 predictions with conf >= 0.25. The save_txt polygons shrink the same way (normalized polygon area sum 19.313 vs 19.595). The built-in mask mAP is not affected because _process_batch matches masks at the network size, and predict is not affected because Results masks are thresholded on the logits. The COCO segm AP computed by eval_json is affected whenever the dataset images are larger than imgsz.

History: 8.3.225 wrote ops.scale_image(masks_uint8_hwc, ori_shape, ratio_pad) here, which resizes the uint8 masks with cv2.resize(..., INTER_LINEAR) and so rounds, the equivalent of a 0.5 threshold. 8.3.230 replaced it with ops.scale_masks(...).byte() and the truncation came with it; 8.3.235, 8.3.240, 8.3.250, 8.4.0 and main have the same line.

The patch below thresholds at 0.5 before .byte(), like _prepare_batch does for the ground-truth masks (masks.gt_(0.5)) and like the old scale_image path did. With a 2x upscale the thresholded masks are pixel-identical to what the 8.3.225 path wrote; at 3x the only differences are edge pixels at 0.56 to 0.67 that cv2's fixed-point interpolation rounds down.

Environment

Ultralytics 8.4.164 (main at 4604393) Python-3.13.14 torch-2.14.0+cpu CPU (Intel Xeon Processor @ 2.90GHz), Linux. Also checked against the 8.3.225, 8.3.230, 8.3.235, 8.3.240, 8.3.250 and 8.4.0 wheels.

Minimal Reproducible Example

python
from pathlib import Path

import torch

from ultralytics.models.yolo.segment import SegmentationValidator
from ultralytics.utils import ops

validator = SegmentationValidator(save_dir=Path("/tmp/segval"))
ratio_pad = ((1 / 3, 1 / 3), (0, 140))  # a 1080x1920 image letterboxed to 640x640
pbatch = {"imgsz": (640, 640), "ori_shape": (1080, 1920), "ratio_pad": ratio_pad}
for n in (4, 10, 30):
    masks = torch.zeros(1, 640, 640)
    masks[0, 300 : 300 + n, 300 : 300 + n] = 1  # a binary process_mask_native output
    predn = {"bboxes": torch.tensor([[300.0, 300.0, 300.0 + n, 300.0 + n]]), "masks": masks}
    got = validator.scale_preds(predn, pbatch)["masks"].sum().item()
    ref = (ops.scale_masks(masks[None], (1080, 1920), ratio_pad=ratio_pad)[0] > 0.5).sum().item()
    print(f"{n}x{n} network pixels -> {got} original pixels, {ref} with a 0.5 threshold, {9 * n * n} exact")

Output on main:

4x4 network pixels -> 100 original pixels, 140 with a 0.5 threshold, 144 exact
10x10 network pixels -> 784 original pixels, 896 with a 0.5 threshold, 900 exact
30x30 network pixels -> 7744 original pixels, 8096 with a 0.5 threshold, 8100 exact

Additional

The patch adds tests/test_python.py::test_segment_val_scale_preds_thresholds_upscaled_masks, which runs SegmentationValidator.scale_preds on two binary squares with the letterbox ratio_pad above and checks the result equals the 0.5-thresholded scale_masks output with areas 140 and 896. It fails on main (assert False on the equality, areas 100 and 784) and passes with the patch; pytest tests/test_python.py -k "scale_preds_thresholds or scale_masks" gives 2 passed, ruff check and ruff format --check are clean.

Are you willing to submit a PR?

  • Yes I'd like to help by submitting a PR!

Patch

Branch: https://github.com/Nicholas022400701/ultralytics/tree/fix/segment-val-mask-threshold (commit 00aee57)

Patch
diff
diff --git a/tests/test_python.py b/tests/test_python.py
index 82339f4..8fb2dfe 100644
--- a/tests/test_python.py
+++ b/tests/test_python.py
@@ -2420,3 +2420,21 @@ def test_load_yolo_dota_whitespace_lines(tmp_path):
     )
     annos = load_yolo_dota(str(tmp_path), split="train")
     assert len(annos) == 1 and annos[0]["label"].shape == (2, 9)  # both rows parsed
+
+
+def test_segment_val_scale_preds_thresholds_upscaled_masks(tmp_path):
+    """Binary val masks scaled up to the original image must be thresholded, not truncated to zero, by scale_preds."""
+    from ultralytics.models.yolo.segment import SegmentationValidator
+    from ultralytics.utils import ops
+
+    validator = SegmentationValidator(save_dir=tmp_path)
+    ratio_pad = ((1 / 3, 1 / 3), (0, 140))  # a 1080x1920 image letterboxed to 640x640: 140 padded rows top and bottom
+    pbatch = {"imgsz": (640, 640), "ori_shape": (1080, 1920), "ratio_pad": ratio_pad}
+    masks = torch.zeros(2, 640, 640)
+    masks[0, 300:304, 300:304] = 1  # 4x4 network pixels cover 12x12 original pixels
+    masks[1, 200:210, 200:210] = 1  # 10x10 network pixels cover 30x30 original pixels
+    predn = {"bboxes": torch.tensor([[300.0, 300.0, 304.0, 304.0], [200.0, 200.0, 210.0, 210.0]]), "masks": masks}
+    scaled = validator.scale_preds(predn, pbatch)["masks"]
+    assert scaled.dtype == torch.uint8 and scaled.shape == (2, 1080, 1920)
+    assert torch.equal(scaled.bool(), ops.scale_masks(masks[None], (1080, 1920), ratio_pad=ratio_pad)[0] > 0.5)
+    assert scaled.sum((1, 2)).tolist() == [140, 896]  # the 12x12 and 30x30 squares minus their four 4/9 corners
diff --git a/ultralytics/models/yolo/segment/val.py b/ultralytics/models/yolo/segment/val.py
index 82f6609..6981aeb 100644
--- a/ultralytics/models/yolo/segment/val.py
+++ b/ultralytics/models/yolo/segment/val.py
@@ -301,9 +301,10 @@ class SegmentationValidator(DetectionValidator):
         """Scale predictions to the original image size."""
         return {
             **super().scale_preds(predn, pbatch),
-            "masks": ops.scale_masks(predn["masks"][None], pbatch["ori_shape"], ratio_pad=pbatch["ratio_pad"])[
-                0
-            ].byte(),
+            # The masks are binary at the network input size; threshold the bilinear rescale instead of truncating it
+            "masks": ops.scale_masks(predn["masks"][None], pbatch["ori_shape"], ratio_pad=pbatch["ratio_pad"])[0]
+            .gt_(0.5)
+            .byte(),
         }
 
     def eval_json(self, stats: dict[str, Any]) -> dict[str, Any]: