matplotlib 使用plot_Surface在3D图形中显示背景图像

nhn9ugyo  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(304)

我正在寻找一种方法来显示一个.png图像的3D图形的背景。我尝试了this Post这里,但即使我复制的确切代码:

  1. from mpl_toolkits.mplot3d import Axes3D
  2. from matplotlib import cm
  3. from matplotlib.ticker import LinearLocator, FormatStrFormatter
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. from matplotlib._png import read_png
  7. from matplotlib.cbook import get_sample_data
  8. fig = plt.figure()
  9. ax = fig.gca(projection='3d')
  10. X = np.arange(-5, 5, .25)
  11. Y = np.arange(-5, 5, .25)
  12. X, Y = np.meshgrid(X, Y)
  13. R = np.sqrt(X**2 + Y**2)
  14. Z = np.sin(R)
  15. surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.winter,
  16. linewidth=0, antialiased=True)
  17. ax.set_zlim(-2.01, 1.01)
  18. ax.zaxis.set_major_locator(LinearLocator(10))
  19. ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
  20. fn = get_sample_data("./grace_hopper.png", asfileobj=False)
  21. arr = read_png(fn)
  22. # 10 is equal length of x and y axises of your surface
  23. stepX, stepY = 10. / arr.shape[0], 10. / arr.shape[1]
  24. X1 = np.arange(-5, 5, stepX)
  25. Y1 = np.arange(-5, 5, stepY)
  26. X1, Y1 = np.meshgrid(X1, Y1)
  27. Z =
  28. # stride args allows to determine image quality
  29. # stride = 1 work slow
  30. ax.plot_surface(X1, Y1, 2.0, rstride=1, cstride=1, facecolors=arr)
  31. plt.show()

我总是得到这个错误:

  1. Traceback (most recent call last):
  2. File "c:\Users\XXX\ZeichnenFabrik\readTextFile.py", line 161, in <module>
  3. main()
  4. File "c:\Users\XXX\ZeichnenFabrik\readTextFile.py", line 157, in main
  5. plotGraph(nodedict,slines)
  6. File "c:\Users\XXX\ZeichnenFabrik\readTextFile.py", line 145, in plotGraph
  7. ax.plot_surface(X1, Y1, 0)
  8. File "C:\Program Files\Python36\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1609, in plot_surface
  9. if Z.ndim != 2:
  10. AttributeError: 'int' object has no attribute 'ndim'

我有办法解决吗?

ecfdbz9o

ecfdbz9o1#

看起来matplotlib中有一个变化--plot_surface的第三个参数必须是一个2D数组,所以用np.atleast_2d Package 常量:

  1. ax.plot_surface(X1, Y1, np.atleast_2d(-2.0), rstride=10, cstride=10, facecolors=arr)

另请注意,arr.shape(600, 512, 3),而X1.shape(512, 600)。这会导致形状不匹配,从而产生IndexError。要避免此问题,请交换stepXstepY的定义:
x一个一个一个一个x一个一个二个x

相关问题