Sunday, November 17, 2024
Google search engine
HomeLanguagesGetting Started With ImageIO Library in Python

Getting Started With ImageIO Library in Python

Imageio is a Python library that provides an easy interface to read and write a wide range of image and video data, including animated images, volumetric data, and scientific formats. It is cross-platform.

Installation:

This module does not come built-in with Python. To install it type the below command in the terminal.

pip install imageio

Requirements:

  • A recent version of Python
  • Numpy 
  • Pillow 

For accessing input images files click here. Let’s see the code for some working of imageio library:

1) Read an image: For reading an image we have to used iio.imread() method.

Syntax: 

imageio.v3.imread("filename or path")

Parameter:

  •  filename/path: Absolute or Relative path of the image file.
  • (optional) index: Integer indicating which image to read if the file contains multiple (e.g., GIF, TIFF, video)
  • (optional) plugin: A string indicating which plugin/backend to use (default: select automatically)

Return: a numpy array filled with decoded image data

Example:

Python3




# import library
import imageio.v3 as iio
 
# read an image
image = iio.imread('testa.png')
 
# print shape of the image
print(image.shape)


Output:

(134, 151, 4)

2) Reading GIF file: For reading a GIF we can again use the imageio.v3.imread method.

Example:

Python3




# import library
import imageio.v3 as iio
 
# create an image object
images = iio.imread('test.gif')
print(images.shape)
 
# read frames one-by-one instead
for i in range(16):
    img = iio-imread('test.gif', index=i)
    # Each frame is a numpy matrix
    print(img.shape)


Output:

(16, 300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)

3) Creating Image file: For creating an image file we have to used imageio.v3.imwrite() method.

Syntax: 

imageio.imwrite(filename,numPy_ndarray, format=None) 

Parameters:

  • filename: Path / Name of file to be saved as
  • numpy_ndarray: The image data. Must be NxM, NxMx3 or NxMx4.
  • (optional) plugin: A string indicating which plugin/backend to use (default: select automatically)
  • (optional) extension: If set, treat the file/data as if it had the given file extension (instead of its actual one). This is used for choosing/overwriting the output format (e.g. “.jpeg” to write JPEG images) 

Example:

Python3




# import required libraries
import imageio.v3 as iio
import numpy as np
 
 
rows, cols = (5, 5)
 
# create numpy 2-d array
arr = np.zeros((rows, cols))
 
# create an image
image = iio.imwrite('image_writing.png', arr)


Output:

image_writing.png.png

As Data-values were zeros so this is empty image with 68 bytes size.

RELATED ARTICLES

Most Popular

Recent Comments