Plot 3D array as image Python

Note

Click to download the full example code

3D voxel / volumetric plot

Demonstrates plotting 3D volumetric objects with .

Plot 3D array as image Python

import matplotlib.pyplot as plt
import numpy as np


# prepare some coordinates
x, y, z = np.indices((8, 8, 8))

# draw cuboids in the top left and bottom right corners, and a link between
# them
cube1 = (x < 3) & (y < 3) & (z < 3)
cube2 = (x >= 5) & (y >= 5) & (z >= 5)
link = abs(x - y) + abs(y - z) + abs(z - x) <= 2

# combine the objects into a single boolean array
voxelarray = cube1 | cube2 | link

# set the colors of each object
colors = np.empty(voxelarray.shape, dtype=object)
colors[link] = 'red'
colors[cube1] = 'blue'
colors[cube2] = 'green'

# and plot everything
ax = plt.figure().add_subplot(projection='3d')
ax.voxels(voxelarray, facecolors=colors, edgecolor='k')

plt.show()

Download Python source code: voxels.py

Download Jupyter notebook: voxels.ipynb

Gallery generated by Sphinx-Gallery

How to convert 3D array to image in Python?

NumPy can be used to convert an array into image..
Create a numpy array..
Reshape the above array to suitable dimensions..
Create an image object from the above array using PIL library..
Save the image object in a suitable file format..

How to plot 3D image Python?

3D Plotting.
import numpy as np from mpl_toolkits import mplot3d import matplotlib.pyplot as plt plt..
fig = plt. figure(figsize = (10,10)) ax = plt. axes(projection='3d') plt..
x = [1, 2, 3, 4] y = [3, 4, 5] X, Y = np. meshgrid(x, y) print(X) [[1 2 3 4] [1 2 3 4] [1 2 3 4]].

How do you plot a 3 dimensional array in Python?

Creating a 3D plot in Matplotlib from a 3D numpy array.
Create a new figure or activate an existing figure using figure() method..
Add an '~. axes. ... .
Create a random data of size=(3, 3, 3)..
Extract x, y, and z data from the 3D array..
Plot 3D scattered points on the created axis..
To display the figure, use show() method..

How do I save an array as an image in Python?

To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it. This will save the Numpy array as a jpeg image.