【Matplotlib】基础设置之图像处理05

图像基础

导入相应的包:

python 复制代码
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
%matplotlib inline

导入图像

我们首先导入上面的图像,注意 matplotlib 默认只支持 PNG 格式的图像,我们可以使用 mpimg.imread 方法读入这幅图像:

python 复制代码
img = mpimg.imread('stinkbug.png')
python 复制代码
img.shape
复制代码
(375L, 500L, 3L)

这是一个 375 x 500 x 3RGB 图像,并且每个像素使用 uint8 分别表示 RGB 三个通道的值。不过在处理的时候,matplotlib 将它们的值归一化到 0.0~1.0 之间:

python 复制代码
img.dtype
复制代码
dtype('float32')

显示图像

使用 plt.imshow() 可以显示图像:

python 复制代码
imgplot = plt.imshow(img)

伪彩色图像

从单通道模拟彩色图像:

python 复制代码
lum_img = img[:,:,0]
imgplot = plt.imshow(lum_img)

改变 colormap

python 复制代码
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('hot')
python 复制代码
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('spectral')

显示色度条:

python 复制代码
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('spectral')
plt.colorbar()
plt.show()

限制显示范围

先查看直方图:

python 复制代码
plt.hist(lum_img.flatten(), 256, range=(0.0,1.0), fc='k', ec='k')
plt.show()

将显示范围设为 0.0-0.7

python 复制代码
imgplot = plt.imshow(lum_img)
imgplot.set_clim(0.0,0.7)

resize 操作

python 复制代码
from PIL import Image
img = Image.open('stinkbug.png')
rsize = img.resize((img.size[0]/10,img.size[1]/10))
rsizeArr = np.asarray(rsize) 
imgplot = plt.imshow(rsizeArr)

上面我们将这个图像使用 PIL 的 Image 对象导入,并将其 resize 为原来的 1/100,可以看到很多细节都丢失了。

在画图时,由于画面的大小与实际像素的大小可能不一致,所以不一致的地方会进行插值处理,尝试一下不同的插值方法:

python 复制代码
imgplot = plt.imshow(rsizeArr)
imgplot.set_interpolation('nearest')
python 复制代码
imgplot = plt.imshow(rsizeArr)
imgplot.set_interpolation('bicubic')
相关推荐
乱世刀疤2 小时前
AI绘画软件Stable Diffusion详解教程(11):图生图进阶篇(局部用上传蒙版重绘)
人工智能·ai作画·stable diffusion
朱剑君3 小时前
用Python打造AI玩家:挑战2048,谁与争锋
人工智能·python
东临碣石824 小时前
【AI论文】MM-Eureka:基于规则的大规模强化学习探索视觉“啊哈”时刻
人工智能
陌陌6234 小时前
Prompt优化 COT/COD
人工智能·prompt
訾博ZiBo5 小时前
AI日报 - 2025年3月17日
人工智能
树莓集团5 小时前
树莓科技集团董事长:第五代产业园运营模式的深度剖析与展望
大数据·人工智能·科技·物联网·百度
晴空对晚照5 小时前
【论文阅读】AlexNet——深度学习奠基作之一
论文阅读·人工智能·深度学习
孔令飞5 小时前
16 | 实现简洁架构的 Store 层
人工智能·ai·云原生·golang·kubernetes
zzzyzh6 小时前
Work【2】:PGP-SAM —— 无需额外提示的自动化 SAM!
人工智能·深度学习·计算机视觉·sam·medical·image segment
极客 - L U6 小时前
机器学习 : 训练过程
人工智能·机器学习