Python中的 ImageIO 库入门
Imageio是一个Python库,它提供了一个简单的界面来读取和写入各种图像数据,包括动画图像、体积数据和科学格式。它是跨平台的。
安装:
这个模块没有内置在Python中。要安装它,请在终端中键入以下命令。
pip install imageio
要求:
- Python 3.5+
- 麻木的
- 枕头
要访问输入图像文件,请单击此处。让我们看看 imageio 库的一些工作代码:
1)读取图像:为了读取图像,我们必须使用imageio.imread()方法。
Syntax: imageio.imread(“filename or path”)
Parameter:
- filename/path: Absolute or Relative path of the image file.
Return: returns a numpy array, which comes with a dict of meta data at its ‘meta’ attribute.
例子:
Python3
# import library
import imageio
# read an image
image = imageio.imread('testa.png')
# print shape of the image
print(image.shape)
Python3
# import library
import imageio
# create an image object
image = imageio.get_reader('test.gif')
# iterating through matrix:
for i in image :
# Each frame is a numpy matrix
print(i.shape)
Python3
# import required libraries
import imageio
import numpy as np
rows, cols = (5, 5)
# create numpy 2-d array
arr = np.zeros((rows, cols))
# create an image
image = imageio.imwrite('image_writing.png',
arr)
输出:
(134, 151, 4)
2)读取 GIF 文件:为了读取GIF文件,我们必须使用imageio.get_reader()方法。
Syntax: imageio.get_reader(filename, format, mode)
Parameters:
- path/filename: FileName of required image/file/gif .
- format: str, The format to used to read the file, By default imageio select the appropriate for you ,based on the filename and its contents.
- mode: {‘i’, ‘I’, ‘v’, ‘V’, ‘?’}
- Used to give the reader a hint on what the user expects (default “?”):
- ‘i’ for an image
- I’ for multiple images
- ‘v’ for a volume
- ‘V’ for multiple volumes
- ?’ for don’t care
Returns: Reader`object which can be used to read data and meta-data from the specified file.
例子:
Python3
# import library
import imageio
# create an image object
image = imageio.get_reader('test.gif')
# iterating through matrix:
for i in image :
# Each frame is a numpy matrix
print(i.shape)
输出:
(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)创建图像文件:为了创建图像文件,我们必须使用imageio.imwrite()方法。
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.
- format: str, The format to used to read the file. By default, imageio selects, the appropriate for you, based on the filename and its contents.
例子:
Python3
# import required libraries
import imageio
import numpy as np
rows, cols = (5, 5)
# create numpy 2-d array
arr = np.zeros((rows, cols))
# create an image
image = imageio.imwrite('image_writing.png',
arr)
输出:
由于数据值为零,因此这是 68 字节大小的空图像。