Explain Codes LogoExplain Codes Logo

Saving a Numpy array as an image

python
image-processing
numpy
opencv
Anton ShumikhinbyAnton Shumikhin·Mar 5, 2025
TLDR

To convert a Numpy array to an image, matplotlib.pyplot.imsave() is your friend. Here's the fast track with matplotlib:

import matplotlib.pyplot as plt import numpy as np # Quick grayscale—to show we're not scared of shades! plt.imsave('image.png', np.random.rand(100, 100), cmap='gray')

For the RGB real deal, remove the cmap parameter. If imageio is more your style—it loves playing with image formats:

import imageio import numpy as np # Because who doesn't like a little bit of RGB randomness in their life? imageio.imwrite('image.png', (255 * np.random.rand(100, 100, 3)).astype(np.uint8))

Remember, please be kind to your array—scale it to 0-255 and cast to uint8 for the respect it deserves as a true 8-bit color.

Pictures with Python: Meet the libraries

While the fast answer gets you to the picnic, let's unpack the basket for some more options.

Playing with OpenCV

OpenCV is not just library—it's a full-blown Swiss Army knife for image processing. Use cv2.imwrite() like this:

import cv2 import numpy as np # Look at the colors dance! array = (np.random.rand(100, 100, 3) * 255).astype(np.uint8) cv2.imwrite('PsychedelicJPG.jpg', array)

OpenCV got moves—it knows how to handle different formats and encoding options.

Pillow: More than just sleep

Pillow, an improvement over PIL, knows how to work with images and is as fresh as a morning croissant! Here you go:

from PIL import Image import numpy as np # More random values to keep things spicy! array = np.random.rand(100, 100, 3) * 255 image = Image.fromarray(array.astype(np.uint8)) image.save('pic_with_pillow.png')

Pillow favours the brave—it supports a wide range of image formats.

Manual PNG creation: Control freak's delight

For the control freak in you, manually write a PNG file using zlib and struct:

import zlib import struct import numpy as np array = np.random.rand(100, 100).astype(np.uint8) # Here is where we get our hands dirty. Very. Dirty. # ...implement PNG creation process...

But beware, with great power comes great responsibility—here be binary dragons!

Bulletproof your image-saving

Making grayscale great again

Dealing with monochrome? Add a cmap when using matplotlib:

# Even in black and white, we shine! plt.imshow(array, cmap="gray") plt.imsave("monochrome_matters.png", array, cmap="gray")

Transparency, done right

Messing with RGBA arrays? Remember, the fourth channel is the alpha—a.k.a., the ghost that makes your images transparent:

# Like sneaking bulgogi into a vegetarian's taco...nobody will notice rgba_array = np.random.rand(100, 100, 4) * 255 imageio.imwrite('being_hauntingly_transparent.png', rgba_array.astype(np.uint8))

Scaling: Size matters

Scale your arrays for a consistent look. It's like having an image stylist for your arrays:

#We're always in style with consistent brightness and contrast! array_normalized = (array - array.min()) / (array.max() - array.min()) * 255 image = Image.fromarray(array_normalized.astype(np.uint8)) image.save('image_scaling_vogue.png')

In-memory image processing

Why only use files when you can use memory efficiently? Write directly to a file-like object with matplotlib:

import io # Ah, the things we can do with bytes! buffer = io.BytesIO() plt.imsave(buffer, array, format='png')

Before reading, give your buffer a quick rewind:

# T-minus 3...2...1...blast off! buffer.seek(0)