{"record":{"id":"1ab0b04a61e1279a","repo":"huggingface/transformers","slug":"the-image-to-be-converted-to-a-pil-image-contains-1ab0b0","errorCode":null,"errorMessage":"The image to be converted to a PIL image contains values outside the range [0, 1], got [{image.min()}, {image.max()}] which cannot be converted to uint8.","messagePattern":"The image to be converted to a PIL image contains values outside the range \\[0, 1\\], got \\[(.+?), (.+?)\\] which cannot be converted to uint8\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_transforms.py","lineNumber":147,"sourceCode":"    Detects whether or not the image needs to be rescaled before being converted to a PIL image.\n\n    The assumption is that if the image is of type `np.float` and all values are between 0 and 1, it needs to be\n    rescaled.\n    \"\"\"\n    if image.dtype == np.uint8:\n        do_rescale = False\n    elif np.allclose(image, image.astype(int)):\n        if np.all(image >= 0) and np.all(image <= 255):\n            do_rescale = False\n        else:\n            raise ValueError(\n                \"The image to be converted to a PIL image contains values outside the range [0, 255], \"\n                f\"got [{image.min()}, {image.max()}] which cannot be converted to uint8.\"\n            )\n    elif np.all(image >= 0) and np.all(image <= 1):\n        do_rescale = True\n    else:\n        raise ValueError(\n            \"The image to be converted to a PIL image contains values outside the range [0, 1], \"\n            f\"got [{image.min()}, {image.max()}] which cannot be converted to uint8.\"\n        )\n    return do_rescale\n\n\ndef to_pil_image(\n    image: Union[np.ndarray, \"PIL.Image.Image\", \"torch.Tensor\"],\n    do_rescale: bool | None = None,\n    image_mode: str | None = None,\n    input_data_format: str | ChannelDimension | None = None,\n) -> \"PIL.Image.Image\":\n    \"\"\"\n    Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if\n    needed.\n\n    Args:\n        image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):","sourceCodeStart":129,"sourceCodeEnd":165,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_transforms.py#L129-L165","documentation":"Companion guard in _rescale_for_pil_conversion: when the image holds non-integral values that are not all within [0, 1], PIL conversion is impossible. Float pixels are expected to be either full-range [0, 255] integers-in-float or normalized [0, 1]; anything else (e.g. [0, 2], negatives, standardized data) fails.","triggerScenarios":"to_pil_image on a normalized image ((img - mean)/std produces values like -2.1..2.1), float arrays with values 0-510, or images scaled to [0, 2]. Also triggered inside resize when a non-PIL image with bad range is passed.","commonSituations":"Visualizing images after Normalize, mixing rescale and normalize step order, or custom float pipelines that never establish a 0-1 or 0-255 convention.","solutions":["De-normalize before display: img = img * std + mean, then rescale to 0-255 if it was 0-1.","If your floats are in [0, 1], ensure no stray value exceeds 1 (clip with np.clip(img, 0, 1)).","Explicitly control conversion: to_pil_image((img * 255).astype(np.uint8), do_rescale=False)."],"exampleFix":"# before\npil = to_pil_image(normalized_img)  # values in [-2.4, 2.6] -> raises\n\n# after\ndenorm = normalized_img * np.array(std) + np.array(mean)\npil = to_pil_image(np.clip(denorm, 0, 1), do_rescale=True)","handlingStrategy":"validation","validationCode":"assert np.all(image >= 0) and np.all(image <= 1) or np.allclose(image, np.clip(image, 0, 255)), \"image range not 0-1 nor integral 0-255; de-normalize or rescale first\"","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always de-normalize (x*std+mean) before converting preprocessed tensors to PIL.","Standardize your pipeline on one representation: uint8 0-255 for I/O, float 0-1 for math."],"tags":["image-processing","pil","range-validation","normalization","valueerror"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}