{"record":{"id":"1f30622fb01915e3","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"the-input-image-should-np-float32-in-the-range-0","errorCode":null,"errorMessage":"The input image should np.float32 in the range [0, 1]","messagePattern":"The input image should np\\.float32 in the range \\[0, 1\\]","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"pytorch_classification/grad_cam/utils.py","lineNumber":198,"sourceCode":"                      use_rgb: bool = False,\n                      colormap: int = cv2.COLORMAP_JET) -> np.ndarray:\n    \"\"\" This function overlays the cam mask on the image as an heatmap.\n    By default the heatmap is in BGR format.\n\n    :param img: The base image in RGB or BGR format.\n    :param mask: The cam mask.\n    :param use_rgb: Whether to use an RGB or BGR heatmap, this should be set to True if 'img' is in RGB format.\n    :param colormap: The OpenCV colormap to be used.\n    :returns: The default image with the cam overlay.\n    \"\"\"\n\n    heatmap = cv2.applyColorMap(np.uint8(255 * mask), colormap)\n    if use_rgb:\n        heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)\n    heatmap = np.float32(heatmap) / 255\n\n    if np.max(img) > 1:\n        raise Exception(\n            \"The input image should np.float32 in the range [0, 1]\")\n\n    cam = heatmap + img\n    cam = cam / np.max(cam)\n    return np.uint8(255 * cam)\n\n\ndef center_crop_img(img: np.ndarray, size: int):\n    h, w, c = img.shape\n\n    if w == h == size:\n        return img\n\n    if w < h:\n        ratio = size / w\n        new_w = size\n        new_h = int(h * ratio)\n    else:","sourceCodeStart":180,"sourceCodeEnd":216,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_classification/grad_cam/utils.py#L180-L216","documentation":"grad_cam's show_cam_on_image overlays a heatmap onto img, which must be a float32 array normalized to [0, 1]. It detects values > 1 (typically a uint8 0-255 image) and raises rather than producing a washed-out overlay. The check guards the additive blending cam = heatmap + img.","triggerScenarios":"Calling show_cam_on_image(img, mask) with img read by cv2.imread or kept as np.uint8 in [0, 255]; also fires if img is float32 but scaled beyond 1.0.","commonSituations":"Forgetting the standard preprocessing img = np.float32(img) / 255 after cv2.imread; passing a PIL image converted via np.array without scaling; mixing BGR uint8 OpenCV reads with CAM utilities.","solutions":["Normalize before the call: img = np.float32(img) / 255 (and convert BGR->RGB if needed)","Use cv2.cvtColor + astype(np.float32)/255.0 immediately after cv2.imread","Clamp/verify range with assert np.max(img) <= 1 in your preprocessing"],"exampleFix":"// before\nrgb_img = cv2.imread(path)\ncv2.waitKey()\nshow_cam_on_image(rgb_img, grayscale_cam)\n// after\nrgb_img = cv2.imread(path)[:, :, ::-1]\nrgb_img = np.float32(rgb_img) / 255\nshow_cam_on_image(rgb_img, grayscale_cam)","handlingStrategy":"type-guard","validationCode":"img = cv2.imread(path)[:, :, ::-1]\nassert img.dtype == np.uint8\nimg = np.float32(img) / 255.0\nassert 0.0 <= img.min() and img.max() <= 1.0","typeGuard":"def is_unit_float_image(img: 'np.ndarray') -> bool:\n    return img.dtype == np.float32 and img.max() <= 1.0 and img.min() >= 0.0","tryCatchPattern":"try:\n    visualization = show_cam_on_image(img, grayscale_cam)\nexcept Exception as e:\n    if 'np.float32 in the range [0, 1]' in str(e):\n        img = np.float32(img) / 255.0\n        visualization = show_cam_on_image(img, grayscale_cam)\n    else:\n        raise","preventionTips":["Standardize a to_float_rgb() helper applied to every image before CAM utilities","Never pass cv2.imread output directly to show_cam_on_image","Assert dtype/float32 and range in your visualization pipeline"],"tags":["pytorch","grad-cam","opencv","image-normalization"],"backgroundTag":"image-not-normalized-float32","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}