Convert the NumPy array to uint8 pixel values (0–255) and save it directly via Image.fromarray(arr).save("output.png") using Pillow (recommended for standard RGB/grayscale image files with zero extra axes/borders), cv2.imwrite("output.png", arr) using OpenCV (remembering to convert RGB to BGR first), or matplotlib.pyplot.imsave("output.png", arr, cmap="viridis") when saving 2D floating-point heatmaps or scientific arrays directly with a colormap.

Basic Example

import numpy as np
from PIL import Image

# 1. Recommended (Pillow): Save an RGB uint8 array (shape: H x W x 3, dtype: uint8)
rgb_array = np.zeros((100, 200, 3), dtype=np.uint8)
rgb_array[:, :100] = [255, 80, 80]    # Left half: red
rgb_array[:, 100:] = [80, 160, 255]   # Right half: blue

Image.fromarray(rgb_array).save("output_rgb.png")

# 2. Save a 2D grayscale array (shape: H x W, dtype: uint8):
gray_array = np.tile(np.linspace(0, 255, 256, dtype=np.uint8), (100, 1))
Image.fromarray(gray_array, mode="L").save("output_gray.png")

# 3. Save a 2D float matrix directly with a colormap using Matplotlib (`plt.imsave`):
import matplotlib.pyplot as plt

heatmap = np.random.rand(100, 100)
plt.imsave("heatmap.png", heatmap, cmap="viridis")  # 1 array element = 1 pixel, zero borders

Key Details & Edge Cases

  • Fix TypeError: Cannot handle this data type: (1, 1, 3), <f8 (float arrays in [0.0, 1.0]):
    • Pillow’s Image.fromarray() rejects multi-channel float32/float64 arrays ((H, W, 3)). If your image array holds normalized floats in [0.0, 1.0], scale and cast to uint8 before calling Image.fromarray:
      uint8_img = np.clip(float_img * 255, 0, 255).round().astype(np.uint8)
      Image.fromarray(uint8_img).save("from_float.png")
      
    • Always use np.clip(..., 0, 255) before .astype(np.uint8) so out-of-range values like 256 or -1 clamp cleanly instead of wrapping modulo 256 (256 $\rightarrow$ 0).
  • Fix TypeError: Cannot handle this data type: (1, 1, 1), |u1 (single-channel 3D arrays (H, W, 1)):
    • Pillow expects 2D shape (H, W) for grayscale images, not (H, W, 1). Squeeze the trailing singleton dimension via Image.fromarray(arr.squeeze(axis=-1)) (or arr[:, :, 0]).
  • OpenCV (cv2.imwrite) uses BGR channel order instead of RGB:
    • If your array is in standard RGB order (e.g., from Matplotlib, Pillow, or PyTorch/JAX), passing it straight to cv2.imwrite("out.png", rgb_arr) swaps red and blue channels. Convert channels first with cv2.imwrite("out.png", cv2.cvtColor(rgb_arr, cv2.COLOR_RGB2BGR)) (or slice rgb_arr[:, :, ::-1]).
  • Saving 16-bit grayscale images (uint16, e.g., depth maps or medical TIFF/PNGs):
    • Standard 8-bit uint8 truncates 16-bit depth precision. For 2D uint16 arrays ((H, W)), cv2.imwrite("depth16.png", arr_uint16) or imageio.v3.imwrite("depth16.png", arr_uint16) writes lossless 16-bit PNG/TIFF files natively without downscaling.
  • JPEG vs. PNG format caveats (RGBA alpha channels):
    • JPEG does not support transparency (RGBA, shape (H, W, 4)). Saving an RGBA array to .jpg with Pillow raises OSError: cannot write mode RGBA as JPEG—either save as .png or drop/composite the alpha channel (Image.fromarray(rgba_arr).convert("RGB").save("out.jpg")).

Comparison of Methods to Save a NumPy Array as an Image

Library & Function Expected Channel Order Handles Normalized Floats ([0.0, 1.0]) Directly? Supports 16-Bit (uint16) & Alpha (RGBA)? Best Used When
PIL.Image.fromarray(arr).save("out.png") (Recommended) RGB / RGBA / L No (requires uint8 0–255 for RGB) RGBA yes; uint16 2D only (mode="I;16") General-purpose image saving in Python with minimal dependencies and clean format control.
cv2.imwrite("out.png", arr) (opencv-python) BGR / BGRA / Gray No (expects uint8 0–255 or uint16 0–65535) Yes (native 8-bit & 16-bit PNG/TIFF) Computer vision pipelines already using OpenCV or saving 16-bit depth/sensor arrays.
matplotlib.pyplot.imsave("out.png", arr, cmap=...) RGB / RGBA / 2D scalar Yes (auto-normalizes [0.0, 1.0] and applies colormaps) RGBA yes; outputs 8-bit Exporting 2D scientific matrices, masks, or heatmaps directly to pixel-exact colormapped PNGs.
imageio.v3.imwrite("out.png", arr) (pip install imageio) RGB / RGBA / Gray No (expects uint8/uint16 for standard image formats) Yes (multi-format backend) Unified I/O across PNG, TIFF, WebP, GIF, and volumetric formats.