Matplotlib 中的 Imread
这篇文章解释了我们如何使用 Matplotlib 包中的 imread()
方法将一个图像文件读到一个数组中。
matplotlib.pyplot.imread()
matplotlib.pyplot.imread()
将文件中的图像读入一个数组。
语法
matplotlib.pyplot.imread(fname,
format=None)
这里,fname
代表要读取的图像文件的名称,format
代表图像文件的格式。如果 format=None
函数将从文件名中提取格式。
函数返回一个数组,灰度图像为 MxN
,RGB 图像为 MxNx3
,RGBA 图像为 MxNx4
,其中 M
是图像的宽度,N
是图像的高度。
示例: 使用 matplotlib.pyplot.imread()
函数读取图像
import numpy as np
import matplotlib.pyplot as plt
img_array=plt.imread("lena.png")
plt.imshow(img_array)
plt.title('Display Image read using imread()')
plt.axis('off')
plt.show()
输出:
它使用 imread()
方法将当前工作目录下的图像 lena.png
读入数组,然后使用 imshow()
方法显示图像。
默认情况下,它在显示的图像中有 X 轴
和 Y 轴
,并带有刻度线。要删除轴和刻度,我们使用 plt.axis('off')
语句。最后,我们使用 matplotlib.pyplot.show()
函数来显示图像。
我们可以使用 shape
属性来查看图像数组的形状。
import matplotlib.pyplot as plt
img_array=plt.imread("lena.png")
print(img_array.shape)
输出:
(330, 330, 3)
它打印图像的形状-(330, 330, 3)
,代表一个三维图像数组,宽度为 330,高度为 330,有 3 个通道。
示例:使用 matplotlib.pyplot.imread()
函数剪辑图像
在 matplotlib.pyplot.imread()
将图像读入 NumPy 数组后,我们可以通过使用:
操作符对数组进行索引来剪辑图像。
import matplotlib.pyplot as plt
img_array=plt.imread("lena.png")[50:300,30:300]
plt.imshow(img_array)
plt.axis('off')
plt.title("Clipped Image")
plt.show()
输出:
在这里,imread()
方法将完整的图像读取到一个数组中,我们只选择宽度为 50 到 300 位置的元素和高度为 30 到 300 位置的元素,并将索引数组存储在 img_array
中。然后我们使用 imshow()
函数来显示索引数组。
import matplotlib.pyplot as plt
import matplotlib.patches as patches
img_array=plt.imread("lena.png")
fig, ax = plt.subplots()
im = ax.imshow(img_array)
patch = patches.Circle((160, 160), radius=150, transform=ax.transData)
im.set_clip_path(patch)
ax.axis('off')
plt.show()
输出:
它显示的是使用圆形补丁剪切的图像。在这里,我们使用圆形补丁剪裁图像,中心为 (160, 160)
,半径为 150。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串