Method 1: Using PIL/Pillow
Python Imaging Library (PIL) and its fork, Pillow, provide extensive file format support, efficient internal representation, and fairly powerful image processing capabilities. To convert a NumPy array to a JPEG image, simply use the Image.fromarray() method from PIL/Pillow, which creates an image memory from an object exporting the array interface, such as a NumPy array. Then, you can use the save() function specifying ‘JPEG’ as the format.
Here’s an example:
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
from PIL import Image
import numpy as np
array = np.zeros((100, 100, 3), dtype=np.uint8)
img = Image.fromarray(array, 'RGB')
img.save('output.jpeg')Output: ‘output.jpeg’ – A JPEG image file with a 100×100 black square.
This snippet creates a 100×100 pixel black square by first generating a zero-initialized NumPy array with shape (100, 100, 3) for the RGB channels. It then converts this array into a PIL Image object and finally saves it as a JPEG file named ‘output.jpeg’.
Method 2: Using Matplotlib
Matplotlib is a popular plotting library for Python which also contains functions to save images. With its imsave() function, you get a convenient way to save a NumPy array as an image file. Specify the filename and array, and Matplotlib handles the conversion to a JPEG image internally.
Here’s an example:
import matplotlib.pyplot as plt
import numpy as np
array = np.random.rand(100, 100, 3)
plt.imsave('random_output.jpeg', array)Output: ‘random_output.jpeg’ – A JPEG image file with randomly colored pixels.
The code generates a 100×100 pixel image filled with random colors by creating a NumPy array with random values between 0 and 1 in each channel. The plt.imsave() function then takes the array and saves it directly as a ‘random_output.jpeg’ file without the need to display it first.
Method 3: Using OpenCV
OpenCV is a robust framework for computer vision tasks, which includes features for image processing and file I/O. The cv2.imwrite() function is perfect for writing NumPy arrays as image files, including the JPEG format. Simply supply the filename with a ‘.jpeg’ extension and the array.
Here’s an example:
import cv2
import numpy as np
array = np.full((100, 100, 3), 255, dtype=np.uint8)
cv2.imwrite('white_output.jpeg', array)Output: ‘white_output.jpeg’ – A JPEG image file showing a 100×100 white square.
This code creates a white 100×100 pixel image. A white color is represented by setting all color channels to maximum, which is done here by filling the NumPy array with 255s. The cv2.imwrite() function then writes the array to a ‘white_output.jpeg’ file.
Method 4: Using Imageio
Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, volumetric data, and scientific formats. It’s as straightforward as calling the imageio.imwrite() function with a filename that ends with ‘.jpg’ or ‘.jpeg’ and the NumPy array.
Here’s an example:
import imageio
import numpy as np
array = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
imageio.imwrite('colorful_output.jpeg', array)Output: ‘colorful_output.jpeg’ – A JPEG file with a 100×100 array of random colors.
The snippet creates an image filled with random pixel colors by using the np.random.randint() function to fill a NumPy array with random values in the range 0 to 255 for each color channel. The imageio.imwrite() method then saves this array as a ‘colorful_output.jpeg’.
Bonus One-Liner Method 5: Using SciPy
As part of its miscellaneous utility functions, SciPy used to offer scipy.misc.imsave(), which has since been deprecated, but for legacy purposes, it offers a very concise way to save a NumPy array as an image. This method is generally not recommended for new code.
Here’s an example:
# Note: 'scipy.misc.imsave()' is deprecated.
# Use 'imageio.imwrite()' as an alternative.
import scipy.misc
import numpy as np
array = np.ones((100, 100, 3), dtype=np.uint8) * 127
scipy.misc.imsave('gray_output.jpeg', array)Output: ‘gray_output.jpeg’ – A JPEG file showing a 100×100 gray square.
Even though it’s shown for informative purposes, this example uses the scipy.misc.imsave() function to save a NumPy array with all values set to 127, resulting in a gray square, as a JPEG image.
Summary/Discussion
- Method 1: PIL/Pillow. Great for simplicity and additional image processing. However, requires installation of a third-party library.
- Method 2: Matplotlib. A quick option for those already using Matplotlib for plotting. Doesn’t always produce the smallest file sizes.
- Method 3: OpenCV. Ideal for computer vision projects. May be an overkill for simple image-saving purposes.
- Method 4: Imageio. Simple and powerful tool for image reading/writing tasks. Supports a wide array of formats.
- Bonus Method 5: SciPy. Provided as a one-liner legacy method; however, not recommended for use in new projects due to its deprecation.
