【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')
相关推荐
飞哥数智坊6 小时前
我的“龙虾”罢工了!正好对比下GLM、MiniMax、Kimi 3家谁更香
人工智能
风象南7 小时前
很多人说,AI 让技术平权了,小白也能乱杀老师傅 ?
人工智能·后端
董董灿是个攻城狮9 小时前
大模型连载1:了解 Token
人工智能
RoyLin11 小时前
沉睡三十年的标准:HTTP 402、生成式 UI 与智能体原生软件的时代
人工智能
needn13 小时前
TRAE为什么要发布SOLO版本?
人工智能·ai编程
毅航13 小时前
自然语言处理发展史:从规则、统计到深度学习
人工智能·后端
前端付豪14 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
ursazoo14 小时前
写了一份 7000字指南,让 AI 帮我消化每天的信息流
人工智能·开源·github
_志哥_17 小时前
Superpowers 技术指南:让 AI 编程助手拥有超能力
人工智能·ai编程·测试
YongGit18 小时前
OpenClaw 本地 AI 助手完全指南:飞书接入 + 远程部署实战
人工智能