{"record":{"id":"d710e17d2b238da5","repo":"matplotlib/matplotlib","slug":"unknown-image-mode","errorCode":null,"errorMessage":"Unknown image mode","messagePattern":"Unknown image mode","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"lib/matplotlib/image.py","lineNumber":1793,"sourceCode":"        - (M, N, 3) for RGB images.\n        - (M, N, 4) for RGBA images.\n    \"\"\"\n    if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:\n        # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array\n        return np.asarray(pilImage)\n    elif pilImage.mode.startswith('I;16'):\n        # return MxN luminance array of uint16\n        raw = pilImage.tobytes('raw', pilImage.mode)\n        if pilImage.mode.endswith('B'):\n            x = np.frombuffer(raw, '>u2')\n        else:\n            x = np.frombuffer(raw, '<u2')\n        return x.reshape(pilImage.size[::-1]).astype('=u2')\n    else:  # try to convert to an rgba image\n        try:\n            pilImage = pilImage.convert('RGBA')\n        except ValueError as err:\n            raise RuntimeError('Unknown image mode') from err\n        return np.asarray(pilImage)  # return MxNx4 RGBA array\n\n\ndef _pil_png_to_float_array(pil_png):\n    \"\"\"Convert a PIL `PNGImageFile` to a 0-1 float array.\"\"\"\n    # Unlike pil_to_array this converts to 0-1 float32s for backcompat with the\n    # old libpng-based loader.\n    # The supported rawmodes are from PIL.PngImagePlugin._MODES.  When\n    # mode == \"RGB(A)\", the 16-bit raw data has already been coarsened to 8-bit\n    # by Pillow.\n    mode = pil_png.mode\n    rawmode = pil_png.png.im_rawmode\n    if rawmode == \"1\":  # Grayscale.\n        return np.asarray(pil_png, np.float32)\n    if rawmode == \"L;2\":  # Grayscale.\n        return np.divide(pil_png, 2**2 - 1, dtype=np.float32)\n    if rawmode == \"L;4\":  # Grayscale.\n        return np.divide(pil_png, 2**4 - 1, dtype=np.float32)","sourceCodeStart":1775,"sourceCodeEnd":1811,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/matplotlib/image.py#L1775-L1811","documentation":"pil_to_array handles Pillow modes RGBA/RGBX/RGB/L directly and the I;16* family via raw byte swapping; every other mode must be convertible via pilImage.convert('RGBA'). When that conversion itself raises ValueError (exotic, corrupt, or unsupported pixel formats), matplotlib re-raises it as RuntimeError('Unknown image mode') during plt.imread.","triggerScenarios":"plt.imread on an image whose Pillow mode cannot convert to RGBA — e.g. some CMYK/palette variants with broken profiles, 1-bit or unusual bit-depth files depending on the Pillow version, or truncated/corrupt downloads (partial file saved from a failed transfer).","commonSituations":"Bulk-loading user-uploaded or scraped images where formats are uncontrolled; Pillow major-version upgrades changing supported modes; reading files whose extension lies about the actual format.","solutions":["Pre-open and normalize with Pillow yourself: arr = np.asarray(PIL.Image.open(path).convert('RGB')) before handing data to matplotlib.","Catch the RuntimeError and retry with an explicit convert(), logging the offending file's mode for triage.","Verify file integrity (PIL.Image.open(...).verify()) and re-download corrupt transfers."],"exampleFix":"# before\narr = plt.imread('scan.dat.png')  # RuntimeError: Unknown image mode\n\n# after\nimport numpy as np, PIL.Image\nwith PIL.Image.open('scan.dat.png') as im:\n    arr = np.asarray(im.convert('RGB'))","handlingStrategy":"try-catch","validationCode":"import PIL.Image\n\nwith PIL.Image.open(path) as im:\n    if im.mode not in {'RGBA', 'RGBX', 'RGB', 'L'} and not im.mode.startswith('I;16'):\n        im = im.convert('RGBA')  # normalize before imread/matplotlib\narr = plt.imread(path)","typeGuard":null,"tryCatchPattern":"try:\n    arr = plt.imread(path)\nexcept RuntimeError as err:\n    if 'Unknown image mode' not in str(err):\n        raise\n    import numpy as np, PIL.Image\n    with PIL.Image.open(path) as im:\n        arr = np.asarray(im.convert('RGB'))","preventionTips":["Pre-convert untrusted images with PIL Image.convert('RGB'|'RGBA').","Verify() downloads before reading to catch truncated files.","Log im.mode of failing files to detect Pillow-version regressions."],"tags":["matplotlib","imread","pillow","image-mode","file-corruption"],"backgroundTag":"unsupported-image-format","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}