{"record":{"id":"11f33b1823a618af","repo":"huggingface/transformers","slug":"the-image-to-be-converted-to-a-pil-image-contains","errorCode":null,"errorMessage":"The image to be converted to a PIL image contains values outside the range [0, 255], 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, 255\\], got \\[(.+?), (.+?)\\] which cannot be converted to uint8\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_transforms.py","lineNumber":140,"sourceCode":"    rescaled_image = rescaled_image.astype(dtype)  # Finally downcast to the desired dtype at the end\n\n    return rescaled_image\n\n\ndef _rescale_for_pil_conversion(image):\n    \"\"\"\n    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,","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_transforms.py#L122-L158","documentation":"_rescale_for_pil_conversion decides whether an image needs 0-1 -> 0-255 rescaling before uint8 PIL conversion. If every value is integral (np.allclose to int cast) but some fall outside [0, 255], PIL cannot store them as uint8, so it raises. This is a data-range sanity guard inside to_pil_image/resize paths.","triggerScenarios":"Calling to_pil_image on an already-uint8-range-overflowed array, e.g. values like 300 or -5 that are whole numbers; or rescaling twice so values are 0-510 but still integral; float images with integer-valued pixels above 255.","commonSituations":"Double rescaling (applying rescale(image, 255) manually and then to_pil_image rescales again), normalizing before visualization, or arithmetic on images (addition/subtraction) pushing values out of range.","solutions":["Clip the image to the valid range before conversion: image = np.clip(image, 0, 255).","Check whether you already rescaled; pass do_rescale=False to to_pil_image if values are already 0-255.","Undo any normalization (multiply back by std, add mean) before visualizing model-preprocessed images."],"exampleFix":"# before\nimg = np.clip(img, 0, 1) * 255 + 100  # integral values > 255\npil = to_pil_image(img)\n\n# after\nimg = np.clip(img, 0, 255).astype(np.uint8)\npil = to_pil_image(img, do_rescale=False)","handlingStrategy":"validation","validationCode":"if image.dtype != np.uint8:\n    if image.min() < 0 or image.max() > 255:\n        image = np.clip(image, 0, 255)\n# or explicitly: to_pil_image(image, do_rescale=False) when already 0-255","typeGuard":"def is_pil_convertible(img) -> bool:\n    if img.dtype == np.uint8:\n        return True\n    return bool(np.all(img >= 0) and (np.all(img <= 1) or (np.allclose(img, img.astype(int)) and np.all(img <= 255))))","tryCatchPattern":null,"preventionTips":["Track whether an image has been rescaled; rescale exactly once.","Clip to a declared range before any visualization."],"tags":["image-processing","pil","range-validation","valueerror"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}