如何使用 Matplotlib 从灰度图像创建曲面图?

How to create surface plot from greyscale image with Matplotlib?

假设我有一张灰度图像(尺寸:550x150 像素)。我用 matplolib

加载图像
import matplotlib.pyplot as plt
import matplotlib.image as mp_img
image = mp_img.imread("my-cat.png")
plt.imshow(image)
plt.show()

现在,plt.imshow 将图像显示在屏幕上。但我想要的是灰度值的表面图,如下所示:

.颜色不是必需品,但对身高线有帮助。我知道,我需要 f(x,y) -> z 形式的函数来创建曲面图。所以,我想在我的图像中使用 (x_pixel,y_pixel) 处的灰度值来获取 f 的值。这导致了我的问题:

所以这很简单。加载数据,构建绘图:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# generate some sample data
import scipy.misc
lena = scipy.misc.lena()

# downscaling has a "smoothing" effect
lena = scipy.misc.imresize(lena, 0.15, interp='cubic')

# create the x and y coordinate arrays (here we just use pixel indices)
xx, yy = np.mgrid[0:lena.shape[0], 0:lena.shape[1]]

# create the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx, yy, lena ,rstride=1, cstride=1, cmap=plt.cm.gray,
        linewidth=0)

# show it
plt.show()

结果:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cv2

# generate some sample data
import scipy.misc
lena = cv2.imread("./data/lena.png", 0)

# downscaling has a "smoothing" effect
lena = cv2.resize(lena, (100,100))

# create the x and y coordinate arrays (here we just use pixel indices)
xx, yy = np.mgrid[0:lena.shape[0], 0:lena.shape[1]]

# create the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx, yy, lena ,rstride=1, cstride=1, cmap=plt.cm.jet,
                linewidth=0)

# show it
plt.show()

如果你想得到彩色图,把代码改成:“cmap=plt.cm.jet”。 所以你可以得到这样的东西: color plot