Using matplotlib is it possible to take a 2D image of something and place it in a 3D figure? I'd like to take a 2D image and place it at z position of 0. I want to then move the other pixels in the image along the z-axis separately based on a calculation I am making.
Asked
Active
Viewed 2,325 times
2 Answers
1
Look for example: https://matplotlib.org/gallery/mplot3d/2dcollections3d.html
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)')
# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
c_list.extend([c] * 20)
# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x,y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)')
# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35)
plt.show()

pcu
- 1,204
- 11
- 27
-
But will this work correctly with an actual image? Not just points? I want to try to put an image in the grid...such as a .png, .jpg, etc. – sabo Apr 10 '18 at 21:59
-
Another example https://stackoverflow.com/a/37480529/7390366 Set 3rd argument of ax.plot_surface to point z . – pcu Apr 11 '18 at 06:49
0
If your image is a coloured image you must first ensure that it is an indexed image. This means that you can only have 2d matrix (and not 3 matricies for the RGB components). Command rgb2ind can help.
Then you can directly show you image in a 3D way. Use the mesh or surf command.
You can also adjust perspective with angle and azimuth.

Filipe Pinto
- 311
- 3
- 17
-
So using something like Axes3D.plot_surface() can work with an actual 2D image? I'm sort of confused with the way to plot it. Handing it an array of the x coords, y coords, and z values doesn't seem to work. – sabo Apr 10 '18 at 01:56