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

时间:2015-08-04 09:29:24

标签: python matplotlib plot smooth

假设我有一张灰度图像(尺寸: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的值。这导致了我的问题:

  • 我想在绘图期间对我的图像值进行一些插值(例如平滑)。这还取决于我的meshgrid的大小,所以我该如何控制它?和,
  • 如何从我的图像中制作灰度值的曲面图?

2 个答案:

答案 0 :(得分:12)

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

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()

结果:

enter image description here

答案 1 :(得分:0)

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