HOWTO · Matplotlib

How to Convert a NumPy Array to PIL Image in Python

Convert NumPy arrays to Pillow images with Image.fromarray(). Learn how array shape, dtype, and value range affect grayscale, RGB, and Matplotlib-colormapped images, then resize and save the result.

On this page

Use Pillow’s Image.fromarray() to create a PIL image from a NumPy array. A two-dimensional array represents grayscale pixels; arrays shaped (height, width, 3) or (height, width, 4) represent RGB or RGBA pixels. The array’s dtype and values also matter, so check them before converting. PIL is the familiar import name, while Pillow is the maintained library.

For an RGB image, create a three-channel uint8 array and pass it to Image.fromarray(). The output reports the image mode, its (width, height) size, and the pixel at the upper-left corner.

import numpy as np
from PIL import Image

pixels = np.array(
    [[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 255]]],
    dtype=np.uint8,
)
image = Image.fromarray(pixels)
print(image.mode, image.size, image.getpixel((0, 0)))
RGB (2, 2) (255, 0, 0)

The resulting image is an in-memory Pillow object. You can inspect its mode and dimensions, then display it in an environment that supports image previews or save it to a file.

Convert a NumPy array to a PIL image with Image.fromarray()

Image.fromarray(array) infers an image mode from the array’s shape and dtype. For grayscale data, use a two-dimensional array with shape (height, width). For RGB data, use (height, width, 3); an optional fourth channel gives RGBA. The first two dimensions are rows and columns, so a 40-row by 60-column array creates an image 60 pixels wide and 40 pixels high.

Use np.uint8 for ordinary 8-bit image samples when the values already represent integers from 0 through 255. Do not cast blindly: casting floating-point data truncates fractional parts, and values outside the representable range can wrap. For data measured on a different scale, decide how it should map to display intensity before conversion. For example, data in the interval 0–1 can be multiplied by 255 and rounded; data with another range needs an explicit normalization based on its meaning.

Prepare the array’s shape, dtype, and value range

An array with shape (height, width) is a grayscale image. RGB and RGBA arrays add a final channel dimension, with three or four values per pixel. A shape such as (height, width, 1) is not the usual two-dimensional grayscale shape; remove that final singleton axis with array[..., 0] when it represents grayscale. Check array.shape, array.dtype, and the minimum and maximum values before conversion. The array must contain a regular rectangular grid; ragged nested lists are not image data.

Here is a self-contained grayscale conversion. Its values are chosen directly in the 8-bit range, so no scaling step is needed. The resulting image uses grayscale mode L and has a size of (3, 2).

import numpy as np
from PIL import Image

gray = np.array([[0, 64, 128], [32, 160, 255]], dtype=np.uint8)
image = Image.fromarray(gray)
print(image.mode, image.size)
L (3, 2)

If your source is a floating-point array from 0 to 1, convert deliberately with np.round(array * 255).astype(np.uint8). That transformation is suitable only when those values are normalized intensities. For measurements such as temperatures or arbitrary scores, choose meaningful lower and upper bounds, clip or normalize to that interval, and document the mapping; otherwise contrast and pixel values can be misleading.

Apply a Matplotlib colormap before creating a PIL image

Use a Matplotlib colormap when the source is a two-dimensional scalar field and you want color to encode its values. Normalize the data to the interval expected by the chosen colormap, then convert the colormap result to an 8-bit RGB or RGBA array. The plasma colormap returns normalized red, green, blue, and alpha channels, so dropping alpha with [..., :3] gives an RGB array. This is a separate step from Image.fromarray(): the colormap creates the colors, and Pillow wraps those pixels as an image.

import numpy as np
import matplotlib
from PIL import Image

values = np.array([[0.0, 0.25], [0.75, 1.0]])
colors = matplotlib.colormaps["plasma"](values)[..., :3]
rgb = np.round(colors * 255).astype(np.uint8)
image = Image.fromarray(rgb)
print(image.mode, image.size)
RGB (2, 2)

This example assumes values is already normalized from 0 to 1. If the actual scalar range differs, normalize using appropriate data bounds before applying the colormap. A colormap is useful for visualization, but it changes scalar values into display colors and should not replace the original measurements when those values are needed for analysis. The resulting image is RGB with a size of (2, 2).

Resize and save the PIL image

Resize after conversion with image.resize((width, height)); Pillow takes the new size in width-then-height order. Saving is separate from displaying: show() opens a preview using the local environment, while save() writes an image file. Choose a filename extension that matches the format you want, such as .png for lossless output or .jpg for JPEG.

import numpy as np
from PIL import Image

pixels = np.zeros((20, 30, 3), dtype=np.uint8)
pixels[:, :15] = [255, 80, 0]
pixels[:, 15:] = [20, 90, 220]
image = Image.fromarray(pixels)
resized = image.resize((60, 40))
resized.save("resized-image.png")
print(resized.size)

The example creates its input in memory and writes resized-image.png in the current working directory. In an application, use a path appropriate for your output location. Saving does not modify the NumPy array, and resizing changes the Pillow image’s pixel dimensions.

Common conversion issues

  • Unexpected mode or rejected shape: inspect array.shape. Use (height, width) for grayscale and three or four channels in the last dimension for RGB or RGBA. Remove an unintended singleton channel or reorder channels if your source uses another convention.
  • Wrong brightness or colors: inspect the value range before converting. Values stored as floats in 0–1 need deliberate scaling for an 8-bit image; values already in 0–255 should not be multiplied again. For other ranges, normalize to documented bounds.
  • Unexpected dtype: inspect array.dtype and decide how to convert it. A cast alone does not rescale data; preserve a copy of the source if the original precision matters.
  • Colormap output looks wrong: confirm the scalar input was normalized as intended and check whether the result has three RGB channels or four RGBA channels. Convert normalized color channels to uint8 before constructing the image.
  • Image file is not created: call save() with a writable path and a supported extension. Use show() only when you want a preview; it does not save the image.