numpy
image processing
python
data visualization
array manipulation

Save a NumPy array as an image (Pillow, Matplotlib, OpenCV)

Codemia Knowledge Hub ·

The usual way to save a NumPy array as an image is Pillow: Image.fromarray(array).save("output.png"), with the array in uint8 (values 0 to 255). Matplotlib's plt.imsave accepts float arrays in the 0.0 to 1.0 range directly, and OpenCV's cv2.imwrite works too if you convert RGB to BGR first. Preparing the data correctly is what prevents corrupted or wrongly colored output.

Convert to uint8 first

Most image formats expect pixels as unsigned 8-bit integers (uint8) from 0 to 255. Floating-point arrays, common in scientific computing, need converting:

python
1import numpy as np
2
3# Float array with values between 0.0 and 1.0
4float_array = np.random.rand(100, 100, 3)
5
6# Convert to uint8 by scaling to 0-255
7uint8_array = (float_array * 255).astype(np.uint8)

Skipping this is the most common mistake, often producing an all-black or garbled image. Libraries handle mismatched types differently: some silently produce garbled images, others throw errors. Also match the array shape to the format: (height, width, 3) for RGB, (height, width) for grayscale.

Pillow (PIL)

Pillow is the most widely used library for basic image I/O. Image.fromarray() turns an array into a PIL Image that you can save:

python
1from PIL import Image
2import numpy as np
3
4# Create a 100x100 RGB image with random pixel values
5array = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
6
7# Save as PNG
8img = Image.fromarray(array)
9img.save("output.png")

For grayscale, pass a 2D array and specify the mode, since leaving out mode='L' can misinterpret the data:

python
gray_array = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
img = Image.fromarray(gray_array, mode='L')
img.save("grayscale.png")

For RGBA (with transparency), use shape (height, width, 4):

python
rgba_array = np.random.randint(0, 256, (100, 100, 4), dtype=np.uint8)
img = Image.fromarray(rgba_array, mode='RGBA')
img.save("transparent.png")

Pillow requires uint8. A float array gives unexpected results or an error.

Matplotlib

plt.imsave is convenient if you already use Matplotlib, and it handles float arrays in the 0.0 to 1.0 range natively:

python
1import matplotlib.pyplot as plt
2import numpy as np
3
4# Float array works directly with matplotlib
5float_array = np.random.rand(100, 100, 3)
6plt.imsave("output_mpl.png", float_array)
7
8# For grayscale, specify a colormap
9gray_array = np.random.rand(100, 100)
10plt.imsave("gray_mpl.png", gray_array, cmap='gray')

plt.imsave saves RGBA PNGs by default, even for grayscale input, so files may be larger than expected. It also clips float values outside 0.0 to 1.0, which can silently alter your data. Do not confuse its float range with uint8 arrays in the 0 to 255 range.

OpenCV

OpenCV is the standard for computer vision, and cv2.imwrite saves arrays to disk. The key difference is that OpenCV uses BGR channel order by default, not RGB:

python
1import cv2
2import numpy as np
3
4# Create an RGB array
5rgb_array = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
6
7# Convert RGB to BGR before saving with OpenCV
8bgr_array = cv2.cvtColor(rgb_array, cv2.COLOR_RGB2BGR)
9cv2.imwrite("output_cv2.png", bgr_array)

Skip the conversion and red and blue are swapped in the saved image. Grayscale needs no conversion:

python
gray_array = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
cv2.imwrite("gray_cv2.png", gray_array)

OpenCV can also save 16-bit images, useful for scientific and medical imaging:

python
depth_array = np.random.randint(0, 65535, (100, 100), dtype=np.uint16)
cv2.imwrite("depth.png", depth_array)

Replacing the removed scipy.misc.imsave

Older tutorials use scipy.misc.imsave. It was deprecated in SciPy 1.0 and removed in SciPy 1.2, so replace it with Pillow:

python
1# Old (deprecated, will not work in modern SciPy)
2# from scipy.misc import imsave
3# imsave("output.png", array)
4
5# Modern replacement
6from PIL import Image
7Image.fromarray(array).save("output.png")

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design