huggingface/pytorch-image-models · error · ValueError

Input image must have positive dimensions, got H={height}, W

Error message

Input image must have positive dimensions, got H={height}, W={width}

What it means

Thrown by RandomAspectRatioCrop.get_params when the input tensor/PIL image reports height or width <= 0. The crop parameter solver (which iterates over crop_attempts using log-ratio math) cannot operate on a degenerate image, so the transform validates dimensions up front.

Source

Thrown at timm/data/naflex_transforms.py:604

    @staticmethod
    def get_params(
            img: torch.Tensor,
            scale: Tuple[float, float],
            ratio: Tuple[float, float],
            crop_attempts: int = 10,
            patch_h: int = 16,
            patch_w: int = 16,
            max_seq_len: int = 1024,
            divisible_by_patch: bool = True,
            max_ratio: Optional[float] = None,
            final_scale_range: Optional[Tuple[float, float]] = None,
            interpolation: Union[List[InterpolationMode], InterpolationMode] = _RANDOM_INTERPOLATION,
    ) -> Tuple[Tuple[int, int, int, int], Tuple[int, int], InterpolationMode]:
        """ Get parameters for a random sized crop relative to image aspect ratio.
        """
        _, height, width = F.get_dimensions(img)
        if height <= 0 or width <= 0:
             raise ValueError(f"Input image must have positive dimensions, got H={height}, W={width}")

        area = height * width
        orig_aspect = width / height
        log_ratio = (math.log(ratio[0]), math.log(ratio[1]))

        for _ in range(crop_attempts):
            target_area = area * random.uniform(scale[0], scale[1])
            aspect_ratio_factor = math.exp(random.uniform(log_ratio[0], log_ratio[1]))
            aspect_ratio = orig_aspect * aspect_ratio_factor

            # Calculate target dimensions for the crop
            # target_area = crop_w * crop_h, aspect_ratio = crop_w / crop_h
            # => crop_h = sqrt(target_area / aspect_ratio)
            # => crop_w = sqrt(target_area * aspect_ratio)
            crop_h = int(round(math.sqrt(target_area / aspect_ratio)))
            crop_w = int(round(math.sqrt(target_area * aspect_ratio)))

            if 0 < crop_w <= width and 0 < crop_h <= height:

View on GitHub (pinned to 9a5261e31b)

Solutions

  1. Inspect/fix the upstream source of the image — print F.get_dimensions(img) before the transform to find where the size became 0.
  2. If images come from a dataset, remove or repair corrupt files producing empty decodes.
  3. Check any Resize/crop parameters in your pipeline for a 0 or negative size value.
  4. Add a pre-transform guard that skips or replaces images with non-positive dimensions.

Example fix

// before
img = Image.open(path).convert('RGB')
out = RandomAspectRatioCrop()(img)

// after
img = Image.open(path).convert('RGB')
_, h, w = F.get_dimensions(img)
if h <= 0 or w <= 0:
    raise IOError(f'decoded empty image from {path}')
out = RandomAspectRatioCrop()(img)
Defensive patterns

Strategy: validation

Validate before calling

from timm.data import transforms_factory  # or torchvision.transforms.functional as F
h, w = img.height, img.width  # PIL
if h <= 0 or w <= 0:
    raise IOError('empty image')

Prevention

When it happens

Trigger: Passing a zero-sized tensor (e.g. shape (3,0,0) or (3,H,0)), a PIL image created with 0 width/height, or an image produced upstream by a broken decode/crop step into RandomAspectRatioCrop.forward.

Common situations: Corrupt or truncated image files that decode to empty arrays; unit tests using dummy zero-size tensors; a preceding transform (Resize with size 0, or a pad/crop with inverted coords) silently producing an empty image.

Related errors


AI-assisted analysis of huggingface/pytorch-image-models@9a5261e31b (2026-08-27). Data as JSON: /api/errors/a5eef3da0376d900. Report an issue: GitHub.