使用python在3d绘图中叠加图像

时间:2012-11-26 17:46:02

标签: python 3d matplotlib

我有一个由matplotlib生成的3d线图。我想在特定的xy(或yz,xz)切片上叠加图像。我如何使用python做到这一点?感谢。

我有一个简单的3d绘图代码:

fig = plt.figure(1),<br>
ax = Axes3D(fig)<br>
ax.plot(f[:,0], f[:,1], f[:,2], color='r')

我还有一个图像“Im”(一个二维数组),所以我需要像:

ax.overlay(Im, slice='xy', sliceNo=10)

3 个答案:

答案 0 :(得分:25)

我在背景图像上做了一次3D表面图叠加:

3d surface plot on top of background image

如果这与你想要的类似,我可以试着用它做一个有效的例子。

或者,如果您只想在3d空间中显示图像,则可以使用曲面图:

from pylab import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.cbook import get_sample_data
from matplotlib._png import read_png
fn = get_sample_data("lena.png", asfileobj=False)
img = read_png(fn)
x, y = ogrid[0:img.shape[0], 0:img.shape[1]]
ax = gca(projection='3d')
ax.plot_surface(x, y, 10, rstride=5, cstride=5, facecolors=img)
show()

当然,为了获得更好的图像质量,步幅值可以降低到1,但是然后绘制将采用loooong =)

以上代码生成的图片:

enter image description here

答案 1 :(得分:1)

我使用 Opencv 的解决方案更接近原始解决方案。

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

# Read the image with Opencv
img = cv2.imread('lena.png')
# Change the color from BGR to RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Orgird to store data
x, y = np.ogrid[0:img.shape[0], 0:img.shape[1]]
# In Python3 matplotlib assumes rgbdata in range 0.0 to 1.0
img = img.astype('float32')/255
fig = plt.Figure()
# gca do not work thus use figure objects inbuilt function.
ax = fig.add_subplot(projection='3d')

# Plot data
ax.plot_surface(x, y, np.atleast_2d(0), rstride=10, cstride=10, facecolors=img)
# fig.show() # Throws a AttributeError
# As above did not work, save the figure instead.
fig.savefig("results.png")

我不知道为什么 fig.show() 会抛出 AttributeError 但它有效

My results

答案 2 :(得分:-1)

"""you can try this program,"""
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.cbook import get_sample_data
from matplotlib._png import read_png
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

fig = plt.figure()
ax = fig.gca(projection='3d')

# 在 matlab 命令行窗口直接输入 peaks 可以得到其表达式的 matlab 形式:
fn = get_sample_data("F:/demo3d/pic.png", asfileobj=False)
img = read_png(fn)
xx, yy = ogrid[0:img.shape[0], 0:img.shape[1]]
X = xx
Y = yy
Z1 = -5*np.ones(X.shape)
Z = np.cos(xx/10) * np.cos(xx/10) + np.sin(yy/10) * np.sin(yy/10)

# Plot the 3D surface
ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, facecolors=img, shade=False)
surf = ax.plot_surface(X, Y, Z, cmap=cm.RdYlGn_r, linewidth=0, antialiased=False)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# plt.axis('off')
plt.savefig('png', dpi=1000)
plt.show()

[enter image description here][1]