开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情
前言
图像可以抽象为一个函数,并将其可视化,以进行进一步的分析/处理。灰度图像可以认为是像素位置的二元函数 ,$f(x, y) 将每个像素映射到其相应灰度强度级别( [0, 255] 中的整数或 [0, 1] 中的浮点数),即:
对于 RGB 图像,有三个这样的函数,可以表示为:
其分别对应于每个通道及其色值,我们可以使用 matplotlib 库的三维绘图函数绘制以上函数,使用 Python 代码在 3D 空间中单独绘制每个 RGB 通道。
在3D空间中显示RGB图像颜色通道
(1) 首先,导入所有必需的包。为了读取图像,我们需要 scikit-image 库的 io 模块中的 imread() 函数;由于我们将图像加载为 array 类型,因此需要 Numpy 操作数据类型 array;为了显示图像,我们将使用 matplotlib.pyplot 函数;对于 3D 图像的显示,我们需要使用 mpl_toolkit 库的 mplt3d 模块以及 matplotlib 库中的其他模块:
from skimage.io import imread
import numpy as np
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
(2) 使用 plot_surface() 函数绘制通道的像素值,这是绘制 3D 图像的关键函数:
Axes3D.plot_surface(X, Y, Z, *args, **kwargs)
接下来,我们实现 plot_3d() 的函数,在以下代码中,X 轴和 Y 轴分别用于显示水平轴和垂直轴,Z 轴用于显示图像的深度。需要注意的是,x、y 和 z 的尺寸必须相同,cmap 用于显示不同像素值的颜色映射:
def plot_3d(x, y, z, cmap='Reds', title=''):
fig = plt.figure(figsize=(15,15))
ax = fig.gca(projection='3d')
# 曲面绘制
surf = ax.plot_surface(x, y, z, cmap=cmap, linewidth=0, antialiased=False, rstride=2, cstride=2, alpha=0.5)
ax.xaxis.set_major_locator(LinearLocator(10))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.view_init(elev=10., azim=5)
ax.set_title(title, size=20)
plt.show()
(3) 从磁盘读取 RGB 图像,并使用 scikit-image 库 io 模块的 imread() 函数将其加载到内存中:
skimage.io.imread(fname, as_gray=False, plugin=None, flatten=None, **plugin_args)
使用 imread() 函数从文件加载图像:
im = imread('1.png')
(4) 然后,使用 Numpy 库的 arange() 和 meshbrid() 函数创建像素坐标 的二维网格:
y = np.arange(im.shape[0])
x = np.arange(im.shape[1])
x, y = np.meshgrid(x, y)
(5) 最后,将图像的红色、绿色和蓝色通道分别分配给相应变量,这些通道使用 plot_3D() 函数以 3D 方式显示:
z1 = im[...,0]
z2 = im[...,1]
z3 = im[...,2]
(6) 在 3D 空间中可视化图像,使用 plot_3d() 函数可视化 RGB 图像的颜色通道。使用 Z 轴作为深度轴,并从图像的高度中减去 y 轴值,以便将坐标原点从左上角移动到左侧中心点处。使用函数 plot_3d() 可视化红色通道:
plot_3d(z1, x, im.shape[1]-y, cmap='Reds', title='3D plot for the Red Channel')
红色通道的 3D 绘图结果如下所示:
最后,再次使用函数 plot_3d() 分别可视化输入图像的绿色通道和蓝色通道:
plot_3d(z2, x, im.shape[1]-y, cmap='Greens', title='3D plot for the Green Channel')
plot_3d(z3, x, im.shape[1]-y, cmap='Blues', title='3D plot for the Blue Channel')
从以上绘图结果可以看出,每个通道中的颜色深度和 3D 绘图结果在视觉上与原始 2D 图像类似。