How do I convert a numpy array to and display an image?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
To turn a NumPy array into an image, you need to match the array’s shape and value type to what image libraries expect. Once the array has the right dimensions and numeric range, you can display it directly with Matplotlib or convert it to an image object with Pillow.
Understand Shape and Value Ranges
Image libraries usually expect one of these shapes:
- grayscale: height by width
- RGB: height by width by
3 - RGBA: height by width by
4
For many libraries, the most common dtype is uint8 with values from 0 to 255.
If your array contains floats in the range 0 to 1, that can still be displayed by some tools, but it is safer to know which convention you are using.
Display with Matplotlib
For quick inspection, Matplotlib is the easiest choice.
For grayscale images:
This is perfect for debugging intermediate model outputs or processed arrays.
Convert to a Pillow Image
If you want an actual image object you can save to disk, use Pillow.
For grayscale:
The mode matters. RGB is for three color channels, while L is the common grayscale mode.
Normalizing Float Arrays
Model outputs often come as floating-point arrays that are not already in display range. In that case, normalize them before conversion.
Without normalization, the image may appear all black, all white, or badly clipped.
Watch Out for Channel Order
If you use OpenCV alongside Pillow or Matplotlib, remember that OpenCV often uses BGR order instead of RGB. A red image can appear blue if the channel order is wrong.
That is not a NumPy problem; it is a library convention mismatch.
A Practical Utility Function
Having one conversion helper reduces repeated mistakes across notebooks and scripts.
Common Pitfalls
One common mistake is passing arrays with the wrong shape, such as height by width by one, when the target library expects plain height by width for grayscale.
Another issue is forgetting dtype conversion. Many libraries display uint8 arrays more predictably than arbitrary float arrays.
A third pitfall is ignoring channel order when switching between Matplotlib, Pillow, and OpenCV.
Summary
- Match the array shape to grayscale or RGB image expectations.
- Use Matplotlib for quick display and Pillow for image objects and file output.
- Normalize float arrays before converting them to
uint8. - Check channel order when moving between imaging libraries.
- Centralizing conversion logic makes image debugging much easier.

