plt.imshow
plt.imshow(X, interpolation=None)
-
X:图像数据
- (M, N):标量数据的图像,灰度图
- (M, N, 3):RGB图像
- (M, N, 4):RGBA图像
注意:其中RGB和RGBA图像为float类型[0, 1],或者int类型[0, 255]
显示图像
Display an image, i.e. data on a 2D regular raster.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# x = np.random.rand(25, 25)
x = np.random.rand(25, 25, 3)
# x = np.random.rand(25, 25, 4)
# 可以是float类型[0, 1]
print(x.dtype)
# plt.imshow(x)
# 也可以是int类型[0, 255]
max = np.max(x)
x = x*255/max # expand pixel from [0, 1] to [0, 255], then normalization
# x = np.uint8(x) # 可以转化为uint8类型
x = x.astype(int) # 也可以转化为int32类型,都是为了使float-->int
print(x.dtype)
plt.imshow(x)
'''
输出:
float64
int32
'''
如果最后不显示图像的话,需要再加一句plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/4a0918870471e6a8c9eacf7cc1d0465e.png)
interpolation参数
这里特别讲一下interpolation参数,此参数显示了不同图像之间的插值方式
下面直接给出官方示例:链接
import matplotlib.pyplot as plt
import numpy as np
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']
# Fixing random state for reproducibility
np.random.seed(19680801)
grid = np.random.rand(4, 4)
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),
subplot_kw={'xticks': [], 'yticks': []})
for ax, interp_method in zip(axs.flat, methods):
ax.imshow(grid, interpolation=interp_method, cmap='viridis')
ax.set_title(str(interp_method))
plt.tight_layout()
plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/7f05275f10ec6ca22eeb6bd2d1997015.png)