How to store images in array in Python

In this article, we have explained the process of how to display and save a Numpy array as an Image. This requires Numpy and PIL library.

Table of contents:

  1. Display Numpy array as Image
  2. Complete Python Code

Display Numpy array as Image

Import the relevant library to display and save Numpy array as Image. We import numpy library to create Numpy array and PIL library to add support for display and saving.

from PIL import Image
import numpy as np

Create a sample Numpy array and convert the array to PIL format using fromarray() function of PIL.

height = 500
weight = 500
channel = 3
img_numpy = np.zeros((height, weight, channel), dtype=np.uint8)
img = Image.fromarray(img_numpy, "RGB")

To view the image from the terminal use the show() function:

# Display the Numpy array as Image
img.show()

This will open a new terminal window where the image will be displayed.

To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it.

# Save the Numpy array as Image
image_filename = "opengenus_image.jpeg"
img.save(image_filename)

This will save the Numpy array as a jpeg image.

Complete Python Code

Following is the complete Python code to display and save Numpy array as Image:

from PIL import Image
import numpy as np

height = 500
weight = 500
channel = 3
img_numpy = np.zeros((height, weight, channel), dtype=np.uint8)
img = Image.fromarray(img_numpy, "RGB")
# Display the Numpy array as Image
img.show()

# Save the Numpy array as Image
image_filename = "opengenus_image.jpeg"
img.save(image_filename)

With this article at OpenGenus, you must have the complete idea of how to display and save Numpy array as image.

This section addresses basic image manipulation and processing using the core scientific modules NumPy and SciPy. Some of the operations covered by this tutorial may be useful for other kinds of multidimensional array processing than image processing. In particular, the submodule provides functions operating on n-dimensional NumPy arrays.

See also

For more advanced image processing and image-specific routines, see the tutorial , dedicated to the module.

Image = 2-D numerical array

(or 3-D: CT, MRI, 2D + time; 4-D, …)

Here, image == Numpy array

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
4

Tools used in this tutorial:

  • >>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
    
    5: basic array manipulation

  • >>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
    
    6:
    >>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
    
    2 submodule dedicated to image processing (n-dimensional images). See the documentation:

    >>> from scipy import ndimage
    

Common tasks in image processing:

  • Input/Output, displaying images
  • Basic manipulations: cropping, flipping, rotating, …
  • Image filtering: denoising, sharpening
  • Image segmentation: labeling pixels corresponding to different objects
  • Classification
  • Feature extraction
  • Registration

Chapters contents

Writing an array to a file:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()

How to store images in array in Python

Creating a numpy array from an image file:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))

dtype is uint8 for 8-bit images (0-255)

Opening raw files (camera, 3-D images)

>>> face.tofile('face.raw') # Create raw file
>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
>>> face_from_raw.shape
(2359296,)
>>> face_from_raw.shape = (768, 1024, 3)

Need to know the shape and dtype of the image (how to separate data bytes).

For large data, use

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
9 for memory mapping:

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))

(data are read from the file, and not loaded into memory)

Working on a list of image files

>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()

Use

>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
0 and
>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
1 to display an image inside a
>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
2:

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

Increase contrast by setting min and max values:

>>> plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)        

>>> # Remove axes and ticks
>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)

Draw contour lines:

>>> plt.contour(f, [50, 200])        

How to store images in array in Python

[]

For smooth intensity variations, use

>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
3. For fine inspection of intensity variations, use
>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
4:

>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear')        

>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest')        

How to store images in array in Python

[]

See also

More interpolation methods are in Matplotlib’s examples.

See also

3-D visualization: Mayavi

See .

  • Image plane widgets
  • Isosurfaces

How to store images in array in Python

Images are arrays: use the whole

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
5 machinery.

How to store images in array in Python

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
0

How to store images in array in Python

[]

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
1

>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
6

Exercise

  • Open as an array the
    >>> for i in range(10):
    ...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
    ...     imageio.imsave('random_%02d.png' % i, im)
    >>> from glob import glob
    >>> filelist = glob('random*.png')
    >>> filelist.sort()
    
    7 logo (http://scikit-image.org/_static/img/logo.png), or an image that you have on your computer.
  • Crop a meaningful part of the image, for example the python circle in the logo.
  • Display the image array using
    >>> for i in range(10):
    ...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
    ...     imageio.imsave('random_%02d.png' % i, im)
    >>> from glob import glob
    >>> filelist = glob('random*.png')
    >>> filelist.sort()
    
    0. Change the interpolation method and zoom to see the difference.
  • Transform your image to greyscale
  • Increase the contrast of the image by changing its minimum and maximum values. Optional: use
    >>> for i in range(10):
    ...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
    ...     imageio.imsave('random_%02d.png' % i, im)
    >>> from glob import glob
    >>> filelist = glob('random*.png')
    >>> filelist.sort()
    
    9 (read the docstring!) to saturate 5% of the darkest pixels and 5% of the lightest pixels.
  • Save the array to two different file formats (png, jpg, tiff)
How to store images in array in Python

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
2

How to store images in array in Python

[]

Local filters: replace the value of pixels by a function of the values of neighboring pixels.

Neighbourhood: square (choose size), disk, or more complicated structuring element.

How to store images in array in Python

Gaussian filter from

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
2:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
3

Uniform filter

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
4

How to store images in array in Python

[]

Sharpen a blurred image:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
5

increase the weight of edges by adding an approximation of the Laplacian:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
6

How to store images in array in Python

[]

Noisy face:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
7

A Gaussian filter smoothes the noise out… and the edges as well:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
8

Most local linear isotropic filters blur the image (

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

1)

A median filter preserves better the edges:

from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
9

How to store images in array in Python

[]

Median filter: better result for straight boundaries (low curvature):

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
0

How to store images in array in Python

[]

Other rank filter:

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

2,
>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

3

Other local non-linear filters: Wiener (

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

4), etc.

Non-local filters

Exercise: denoising

  • Create a binary image (of 0s and 1s) with several objects (circles, ellipses, squares, or random shapes).
  • Add some noise (e.g., 20% of noise)
  • Try two different denoising methods for denoising the image: gaussian filtering and median filtering.
  • Compare the histograms of the two different denoised images. Which one is the closest to the histogram of the original (noise-free) image?

See also

More denoising filters are available in

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

5, see the tutorial.

See wikipedia for a definition of mathematical morphology.

Probe an image with a simple shape (a structuring element), and modify this image according to how the shape locally fits or misses the image.

Structuring element:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
1

How to store images in array in Python

Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
2

How to store images in array in Python

Dilation: maximum filter:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
3

Also works for grey-valued images:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
4

How to store images in array in Python

[]

Opening: erosion + dilation:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
5

Application: remove noise:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
6

How to store images in array in Python

[]

Closing: dilation + erosion

Many other mathematical morphology operations: hit and miss transform, tophat, etc.

Synthetic data:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
7

Use a gradient operator (Sobel) to find high intensity variations:

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
8

How to store images in array in Python

[]

  • Histogram-based segmentation (no spatial information)

>>> from scipy import misc
>>> import imageio
>>> face = misc.face()
>>> imageio.imsave('face.png', face) # First we need to create the PNG file

>>> face = imageio.imread('face.png')
>>> type(face)      

>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))
9

How to store images in array in Python

[]

Use mathematical morphology to clean up the result:

>>> face.tofile('face.raw') # Create raw file
>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
>>> face_from_raw.shape
(2359296,)
>>> face_from_raw.shape = (768, 1024, 3)
0

How to store images in array in Python

[]

Exercise

Check that reconstruction operations (erosion + propagation) produce a better result than opening/closing:

>>> face.tofile('face.raw') # Create raw file
>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
>>> face_from_raw.shape
(2359296,)
>>> face_from_raw.shape = (768, 1024, 3)
1

Exercise

Check how a first denoising step (e.g. with a median filter) modifies the histogram, and check that the resulting histogram-based segmentation is more accurate.

See also

More advanced segmentation algorithms are found in the

>>> for i in range(10):
...     im = np.random.randint(0, 256, 10000).reshape((100, 100))
...     imageio.imsave('random_%02d.png' % i, im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()
7: see .

See also

Other Scientific Packages provide algorithms that can be useful for image processing. In this example, we use the spectral clustering function of the

>>> f = misc.face(gray=True)  # retrieve a grayscale image
>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)        

7 in order to segment glued objects.

How do you store an array of images in Python?

Create a sample Numpy array and convert the array to PIL format using fromarray() function of PIL. This will open a new terminal window where the image will be displayed. To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it.

How do I store multiple images in an array in Python?

You can use simply append() function to add your each image to an array.

How do you create an array of images in Python?

Approach:.
Create a numpy array..
Reshape the above array to suitable dimensions..
Create an image object from the above array using PIL library..
Save the image object in a suitable file format..

How do you import an image into an array in Python?

Converting an Image to Array using NumPy:.
from numpy import asarray..
data = asarray(image).
print(data).