HOWTO · NumPy
How to Save a NumPy Array as an Image in Python
This tutorial demonstrates how to save a numpy array as image in Python.
On this page
A NumPy array can be written to an image file with Pillow, imageio, Matplotlib, or OpenCV. The right choice depends on which library your project already uses and how your array stores pixel data. A two-dimensional array commonly represents grayscale pixels; a three-dimensional array commonly represents color channels as height × width × channels. RGB data has three channels in the final dimension, while RGBA adds an alpha channel.
For common 8-bit images, numpy.uint8 values from 0 through 255 are a practical starting point. A floating-point array may be interpreted or rescaled differently by each library, so check the writer’s expected range before saving. The runnable examples below use small arrays and temporary PNG paths. Install NumPy and the library used by the example if they are not already available (for Pillow, for example, run python -m pip install numpy pillow).
Prepare a NumPy Array for Image Output
Choose an array shape that matches the image data: (height, width) for grayscale, (height, width, 3) for RGB, or (height, width, 4) for RGBA when the writer expects channels last. Shape describes the layout, but it does not identify channel meaning. Check whether your source data is RGB or BGR before passing color pixels to a library.
Use a dtype and numeric range supported by both the image format and the chosen writer. For ordinary 8-bit output, numpy.uint8 with values from 0 through 255 is widely accepted. If your source values are floating point or use another range, convert or scale them deliberately; writers may clip, rescale, or reject values differently.
Use the Image.fromarray() Function to Save a NumPy Array as an Image
Pillow’s Image.fromarray() creates an image from an array, and Image.save() writes it to a file. A two-dimensional uint8 array represents grayscale data. For color, provide a suitable three-channel array in RGB order. This example saves a small grayscale array as gray.png:
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
from PIL import Image
pixels = np.array([[0, 64, 128], [192, 224, 255]], dtype=np.uint8)
with TemporaryDirectory() as directory:
output_path = Path(directory) / "gray.png"
image = Image.fromarray(pixels)
image.save(output_path)
print("Saved gray.png")
Saved gray.png
The temporary directory makes the example self-contained. A color example can use an array with shape (height, width, 3) and RGB channel order; Pillow can infer RGB from a suitable three-channel array.
Use the imageio.imwrite() Function to Save a NumPy Array as an Image
imageio.imwrite() writes an array to the path passed as its first argument. The filename extension typically selects the writer, so use an extension supported by the installed imageio plugins. This self-contained example creates its own grayscale array and keeps the output path inside the temporary directory for the entire write. The supplied runtime results do not cover this imageio example; install NumPy and imageio (for example, with python -m pip install numpy imageio) to run it in your environment.
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
pixels = np.array([[0, 64, 128], [192, 224, 255]], dtype=np.uint8)
try:
import imageio.v2 as imageio
except ImportError:
print("imageio is unavailable; install imageio to write the image.")
else:
with TemporaryDirectory() as directory:
output_path = Path(directory) / "gray.png"
imageio.imwrite(output_path, pixels)
print("Saved gray.png")
Use an image-writing library such as imageio for this task. The historical scipy.io.imsave() example is not presented as current guidance; this article does not rely on historical or deprecation claims about SciPy APIs.
Use the matplotlib.pyplot.imsave() Function to Save a NumPy Array as an Image
Matplotlib writes arrays directly with matplotlib.pyplot.imsave(). For a 2D array, pass cmap="gray" to request grayscale output. Without an explicit colormap, Matplotlib can map scalar values to colors. Three-channel input is treated as RGB. This example saves grayscale values with an explicit gray colormap:
from pathlib import Path
from tempfile import TemporaryDirectory
import matplotlib.pyplot as plt
import numpy as np
pixels = np.array([[0, 64, 128], [192, 224, 255]], dtype=np.uint8)
with TemporaryDirectory() as directory:
output_path = Path(directory) / "gray.png"
plt.imsave(output_path, pixels, cmap="gray")
print("Saved gray.png")
Saved gray.png
For scalar data whose numeric range carries meaning, choose the normalization and colormap deliberately. This keeps a visualization color mapping distinct from the original pixel channels.
Use the cv2.imwrite() Function to Save a NumPy Array as an Image
OpenCV’s cv2.imwrite() chooses an encoder from the filename extension and returns a Boolean for whether the write succeeded. Check that value, especially if the output directory or codec may be unavailable. OpenCV uses BGR channel order for color arrays by convention. Convert RGB data before writing when you want the saved colors to match the source. A 2D grayscale array needs no channel-order conversion. The example creates a live output path and handles both a false return value and a missing OpenCV installation with an actionable message. The supplied runtime results do not cover this OpenCV example; install NumPy and opencv-python (for example, with python -m pip install numpy opencv-python) to run it in your environment.
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
pixels = np.array([[0, 64, 128], [192, 224, 255]], dtype=np.uint8)
try:
import cv2
except ImportError:
print("OpenCV is unavailable; install opencv-python to write the image.")
else:
with TemporaryDirectory() as directory:
output_path = Path(directory) / "gray.png"
written = cv2.imwrite(str(output_path), pixels)
if written:
print("Saved gray.png")
else:
print(f"Could not write {output_path}; check the directory and image encoder.")
For RGB color input, convert with cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) before calling cv2.imwrite(). Keep the conversion and array layout consistent with the source data.
Choose an Output Format and Verify the Image
A filename extension usually determines or implies the output format, but supported formats and options vary by library and installed plugins. PNG is lossless; JPEG is lossy and does not preserve transparency. Confirm that the selected writer supports the extension you choose.
Check a return value when the API provides one, as OpenCV does. When you need to confirm the result, reopen the saved file and inspect its dimensions, mode or channel count, and pixel values. Unexpected colors can indicate RGB/BGR channel order, while colored grayscale output can indicate that Matplotlib applied a colormap. If the output looks wrong, compare the array’s shape, dtype, range, and channel order with the writer’s expectations.