Menu Close

How to save a Numpy array as an image with Python?

Sometimes, we want to save a Numpy array as an image with Python.

In this article, we’ll look at how to save a Numpy array as an image with Python.

How to save a Numpy array as an image with Python?

To save a Numpy array as an image with Python, we can use the Image.fromarray method.

For instance, we write:

from PIL import Image
import numpy

w, h = 200, 100
img = numpy.zeros((h, w, 3), dtype=numpy.uint8)

img[:] = (0, 0, 255)

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Image.fromarray(img).convert("RGB").save("art.png")

We call numpy.zeroes to generate an array and assign that to img.

Then we set the entries in img to the (0, 0, 255) tuple.

We then change the colors of some of the entries in the img to (255, 0, 0) with:

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Finally, we call Image.fromarray with the img array to create an image from img.

Then we call convert with 'RGB' and save to convert the image to RGB color and save it to the given path.

Now we should see an art.png image file with a blue background and a red rectangle inside.

Conclusion

To save a Numpy array as an image with Python, we can use the Image.fromarray method.

Posted in Python, Python Answers