Saving a Numpy array as an image
To convert a Numpy array to an image, matplotlib.pyplot.imsave()
is your friend. Here's the fast track with matplotlib:
For the RGB real deal, remove the cmap
parameter. If imageio is more your style—it loves playing with image formats:
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:
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:
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
:
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:
Transparency, done right
Messing with RGBA arrays? Remember, the fourth channel is the alpha—a.k.a., the ghost that makes your images transparent:
Scaling: Size matters
Scale your arrays for a consistent look. It's like having an image stylist for your arrays:
In-memory image processing
Why only use files when you can use memory efficiently? Write directly to a file-like object with matplotlib:
Before reading, give your buffer a quick rewind:
Was this article helpful?