roboflow/supervision · error · ValueError

image_shape must contain positive height and width.

Error message

image_shape must contain positive height and width.

What it means

Raised by CompactMask.from_coco_rle when image_shape[0] (height) or image_shape[1] (width) is zero or negative. The image shape defines the canvas the RLE must cover and is validated before any mask parsing, since a non-positive canvas makes area checks and cropping meaningless.

Source

Thrown at src/supervision/detection/compact_mask.py:784

            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> # 4x4 image with a 2x2 True block at the top-left corner.
            >>> # Uncompressed F-order COCO counts: F=0, T=2, F=2, T=2, F=10
            >>> # (column-major: col0=[T,T,F,F], col1=[T,T,F,F], cols2-3 all F).
            >>> rles = [{"size": [4, 4], "counts": [0, 2, 2, 2, 10]}]
            >>> xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32)
            >>> cm = CompactMask.from_coco_rle(rles, xyxy, image_shape=(4, 4))
            >>> cm.shape
            (1, 4, 4)
            >>> cm.area.tolist()
            [4]

            ```
        """
        img_h, img_w = (int(image_shape[0]), int(image_shape[1]))
        if img_h <= 0 or img_w <= 0:
            raise ValueError("image_shape must contain positive height and width.")
        if img_h > _MAX_IMAGE_DIMENSION or img_w > _MAX_IMAGE_DIMENSION:
            raise ValueError(
                f"image_shape {(img_h, img_w)} exceeds the maximum allowed dimension "
                f"of {_MAX_IMAGE_DIMENSION} pixels per side."
            )

        xyxy_arr = np.asarray(xyxy)
        if xyxy_arr.shape != (len(rles), 4):
            raise ValueError(
                "xyxy must have shape (N, 4), where N matches the number of RLEs."
            )

        if len(rles) == 0:
            return cls(
                [],
                np.empty((0, 2), dtype=np.int32),
                np.empty((0, 2), dtype=np.int32),
                (img_h, img_w),

View on GitHub (pinned to 7f254d9784)

Solutions

  1. Verify the source of image_shape — read the actual image with cv2.imread and use img.shape[:2] (h, w order).
  2. Check for failed image loads before computing the shape (if img is None: handle missing file).
  3. Confirm you pass (height, width), not (width, height) with a stray zero.

Example fix

# before
image_shape = (img_w, img_h) if img is not None else (0, 0)

# after
img = cv2.imread(path)
if img is None:
    raise FileNotFoundError(path)
image_shape = img.shape[:2]  # (h, w)
Defensive patterns

Strategy: validation

Validate before calling

h, w = image_shape
assert h > 0 and w > 0, f"image_shape must be positive, got {(h, w)}"

Type guard

def is_valid_image_shape(shape) -> bool:
    return (
        isinstance(shape, (tuple, list))
        and len(shape) == 2
        and all(isinstance(v, (int, np.integer)) and v > 0 for v in shape)
    )

Try / catch

try:
    cm = sv.CompactMask.from_coco_rle(rles, xyxy, image_shape=shape)
except ValueError as e:
    if "positive height and width" in str(e):
        shape = cv2.imread(path).shape[:2]
    else:
        raise

Prevention

When it happens

Trigger: Calling CompactMask.from_coco_rle(rles, xyxy, image_shape=(0, 480)) or with negative dims; deriving image_shape from image metadata that failed to load (e.g. None coerced to 0) or from a mismatched variable.

Common situations: Passing width-first (w, h) tuples where a field happened to be 0; computing shape from cv2.imread that returned None on a missing file and then indexing .shape of the wrong object; default-initialized placeholders never replaced.

Related errors


AI-assisted analysis of roboflow/supervision@7f254d9784 (2026-08-15). Data as JSON: /api/errors/115dc938f3208fc2. Report an issue: GitHub.