【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')
相关推荐
二川bro15 小时前
零门槛上手DeepSeek Harness,从零自制arxiv搜索插件
人工智能
cxr82815 小时前
数学的本质:关系、模式与不变量的结构世界
人工智能·算法·机器学习
东莞和裕包装15 小时前
如何管控广州定制纸箱生产中的啤切精度与印刷色差质量问题
大数据·运维·网络·人工智能
AIDANHANG15 小时前
放开靠时间戳对日志前先核请求ID跨服务传播与采样关联
前端·人工智能
牛肉胡辣汤15 小时前
手握实战经验,分享AI工程落地的踩坑与收获
人工智能
2601_9632827715 小时前
山地复杂环境对讲机通信失效实战排查与组网优化方案
人工智能·语音识别
两万五千个小时15 小时前
DeepSeek Harness 从 0 开始:15 schedule 域(定时任务)
人工智能·程序员·架构
IT智慧客073115 小时前
2026年3月前端面试:20个高频考点全解析
人工智能
火山引擎开发者社区16 小时前
Agent Plan × DeepSeek Harness 实践指南
人工智能
桃西西呀16 小时前
DeepSeek Harness vs Codex CLI vs Claude Code,谁该用什么
人工智能