lllyasviel/ControlNet · error · Exception

Image must have H x W x 3, H x W x 1 or H x W dimensions.

Error message

Image must have H x W x 3, H x W x 1 or H x W dimensions.

What it means

write_pfm only supports color (HxWx3), greyscale single-channel (HxWx1), and plain 2D (HxW) images. Any other rank/channel count (e.g. HxWx4 RGBA, batched NxHxW, HxWx2) fails this check.

Source

Thrown at annotator/midas/utils.py:82

        scale (int, optional): Scale. Defaults to 1.
    """

    with open(path, "wb") as file:
        color = None

        if image.dtype.name != "float32":
            raise Exception("Image dtype must be float32.")

        image = np.flipud(image)

        if len(image.shape) == 3 and image.shape[2] == 3:  # color image
            color = True
        elif (
            len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1
        ):  # greyscale
            color = False
        else:
            raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.")

        file.write("PF\n" if color else "Pf\n".encode())
        file.write("%d %d\n".encode() % (image.shape[1], image.shape[0]))

        endian = image.dtype.byteorder

        if endian == "<" or endian == "=" and sys.byteorder == "little":
            scale = -scale

        file.write("%f\n".encode() % scale)

        image.tofile(file)


def read_image(path):
    """Read image and output RGB image (0-1).

    Args:

View on GitHub (pinned to ed85cd1e25)

Solutions

  1. Remove the batch dimension: img = output[0] before writing
  2. Convert RGBA to RGB or take a single channel: img[..., :3] or img[..., 0]
  3. For multi-channel maps, select the channel of interest and write each slice separately

Example fix

# before
write_pfm('d.pfm', model_output)  # shape (1, H, W)
# after
write_pfm('d.pfm', model_output[0])  # shape (H, W)
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
img = np.asarray(image)
assert img.ndim in (2, 3) and (img.ndim == 2 or img.shape[2] in (1, 3)), f'bad shape {img.shape}'

Type guard

def is_pfm_writable(img) -> bool:
    import numpy as np
    img = np.asarray(img)
    return img.ndim == 2 or (img.ndim == 3 and img.shape[2] in (1, 3))

Try / catch

try:
    write_pfm(path, img)
except Exception as e:
    if 'H x W' in str(e) and img.ndim == 3 and img.shape[0] == 1:
        write_pfm(path, img[0])
    else:
        raise

Prevention

When it happens

Trigger: Calling write_pfm with an array that has 4 channels, a leading batch dimension, or a squeezed axis producing shape (H, W, 2), etc.

Common situations: Passing a batched model output without indexing [0]; images with an alpha channel; intermediate feature maps with many channels.

Related errors


AI-assisted analysis of lllyasviel/ControlNet@ed85cd1e25 (2026-08-27). Data as JSON: /api/errors/cbc22c44805aa2cd. Report an issue: GitHub.